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): add customer tasks (#94196)

Arthur Moreira de Deus04d974685836
diff --git a/.claude/agents/access-control.md b/.claude/agents/access-control.md
index caf5da4a8852..33cb60fe5ecf 100644
--- a/.claude/agents/access-control.md
+++ b/.claude/agents/access-control.md
@@ -442,6 +442,28 @@ accessible_notebooks = user_access_control.filter_queryset_by_access_level(
)
```
+### Granting object access from product code
+
+When a product must keep a rule in step with its own state (an assignee, a share link), write the rule through the facade instead of the `AccessControl` model. Product code outside `products/access_control/` cannot import the model.
+
+```python
+from products.access_control.backend.facade import contracts
+from products.access_control.backend.facade.api import set_object_access_control
+
+set_object_access_control(
+ team_id=team.id,
+ input=contracts.SetObjectAccessControlInput(
+ resource="customer_task",
+ resource_id=str(task.id),
+ organization_member_id=assignee_membership.id,
+ access_level="editor", # None removes the rule
+ created_by_id=actor.id,
+ ),
+)
+```
+
+The helper validates the resource, the level, and that the subject belongs to the team's organization. It does not check whether the actor may change access; the caller decides that. A `UserAccessControl` built before the call keeps its preloaded rows, so build a new one before re-checking the object in the same request.
+
### Performance Optimization
For bulk operations, preload access controls:
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 8f877c7d69a5..cfe3dbeb62a0 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -118,6 +118,8 @@ rules:
|CoreMemory
|CustomerJourney
|CustomerProfileConfig
+ |CustomerTask
+ |CustomerTaskActivity
|CustomOAuth2Integration
|CustomPropertyDefinition
|CustomPropertySource
@@ -520,6 +522,8 @@ rules:
|CoreMemory
|CustomerJourney
|CustomerProfileConfig
+ |CustomerTask
+ |CustomerTaskActivity
|CustomOAuth2Integration
|CustomPropertyDefinition
|CustomPropertySource
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 711f9237a106..3c90e5acf4bc 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6320,6 +6320,10 @@ snapshots:
hash: v1.k794b7964.828fae9c91deb58c84ba0d76bf0824931870cb75f43a3d9b723d7cd9fbf7be83.JszjQiSxPVwlGEw-b_MPuQBnfdUHtG9CcnhUdSNvmSg
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
+ scenes-app-customer-analytics-dashboard--customer-tasks--light:
+ hash: v1.k794b7964.acedcb03c7c39d27c2b9f0ed3f1b1ac44fe3fdc58f68a0ed0d0b9e475e70ca96.nKLpWDvqLrHFG2HwFEAexR8rc63-OmxYQogH_Utdg9I
scenes-app-customer-analytics-dashboard--feature-request-details--dark:
hash: v1.k794b7964.dd76e36d821568ab1a8ea103274a39792a5916586913dcc54d4b8c6022aed968.ofepc5cJ-e3ysJbDmjbn2yyefm6X7NwNtnjOfyB4WmA
scenes-app-customer-analytics-dashboard--feature-request-details--light:
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
index b0d5ffd13ee7..cfe220be0f31 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
@@ -409,6 +409,7 @@ export interface accessControlsLogicActions {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -581,6 +582,7 @@ export interface accessControlsLogicMeta {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -730,6 +732,7 @@ export interface accessControlsLogicMeta {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -851,6 +854,7 @@ export interface accessControlsLogicMeta {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
index f7a88bc8ce7b..4e57e1294ce6 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
@@ -234,6 +234,7 @@ export interface accessDetailLogicActions {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts
index 7a646595ff71..78183959e04d 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts
@@ -80,6 +80,7 @@ export interface addObjectOverrideModalLogicActions {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -199,6 +200,7 @@ export interface addObjectOverrideModalLogicActions {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -339,6 +341,7 @@ export interface addObjectOverrideModalLogicActions {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -463,6 +466,7 @@ export interface addObjectOverrideModalLogicActions {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -586,6 +590,7 @@ export interface addObjectOverrideModalLogicActions {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -730,6 +735,7 @@ export interface addObjectOverrideModalLogicMeta {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts
index 1c22e64c8d09..3b756072cd17 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts
@@ -43,6 +43,7 @@ export interface groupedAccessControlRuleModalLogicValues {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -168,6 +169,7 @@ export interface groupedAccessControlRuleModalLogicValues {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -285,6 +287,7 @@ export interface groupedAccessControlRuleModalLogicValues {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -415,6 +418,7 @@ export interface groupedAccessControlRuleModalLogicValues {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -550,6 +554,7 @@ export interface groupedAccessControlRuleModalLogicActions {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -687,6 +692,7 @@ export interface groupedAccessControlRuleModalLogicActions {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -804,6 +810,7 @@ export interface groupedAccessControlRuleModalLogicActions {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -960,6 +967,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -1079,6 +1087,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -1197,6 +1206,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -1315,6 +1325,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -1434,6 +1445,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -1552,6 +1564,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -1681,6 +1694,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -1799,6 +1813,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
index 386fdbfcd659..67656c783430 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
@@ -334,6 +334,7 @@ export interface accessControlLogicMeta {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -555,6 +556,7 @@ export interface accessControlLogicMeta {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
@@ -673,6 +675,7 @@ export interface accessControlLogicMeta {
| 'customer_analytics'
| 'customer_journey'
| 'customer_profile_config'
+ | 'customer_task'
| 'dashboard'
| 'dashboard_template'
| 'data_catalog'
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 55d631882171..a81b5ee4de1e 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -286,6 +286,7 @@ export const FEATURE_FLAGS = {
CUSTOMER_ANALYTICS: 'customer-analytics-roadmap', // owner: @arthurdedeus #team-customer-analytics
CUSTOMER_ANALYTICS_ACCOUNT_SCENE: 'customer-analytics-account-scene', // owner: @arthurdedeus #team-customer-analytics
CUSTOMER_ANALYTICS_CSP: 'customer-analytics-csp', // owner: @arthurdedeus #team-customer-analytics, gates the Customer analytics > Accounts settings tab (account_group_type_index dropdown)
+ CUSTOMER_ANALYTICS_CUSTOMER_TASKS: 'customer-analytics-customer-tasks', // owner: @arthurdedeus #team-web-analytics
CUSTOMER_ANALYTICS_FEATURE_REQUESTS: 'customer-analytics-feature-requests',
CUSTOMER_ANALYTICS_JOURNEYS: 'customer-analytics-journeys', // owner: @arthurdedeus #team-customer-analytics
CUSTOMER_ANALYTICS_TRACK_RULES: 'customer-analytics-track-rules', // owner: @arthurdedeus #team-customer-analytics
diff --git a/frontend/src/lib/scopes.test.ts b/frontend/src/lib/scopes.test.ts
index 8f0920b201b6..79b71208b1b0 100644
--- a/frontend/src/lib/scopes.test.ts
+++ b/frontend/src/lib/scopes.test.ts
@@ -24,6 +24,13 @@ describe('getScopeDescription', () => {
expect(getScopeDescription('user:read')).toBe('Read access to users')
})
+ it('uses customer task labels in the scope picker', () => {
+ expect(API_SCOPES.find(({ key }) => key === 'customer_task')).toMatchObject({
+ objectName: 'Customer task',
+ objectPlural: 'customer tasks',
+ })
+ })
+
it('derives a readable label for OAuth-hidden scopes absent from API_SCOPES', () => {
expect(getScopeDescription('wizard_session:write')).toBe('Write access to wizard session')
})
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index 8077bddab093..19a9030b8e40 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -75,6 +75,7 @@ export const API_SCOPES: APIScope[] = [
info: 'Programmatic access to the PostHog AI (Max) chat via the conversations API.',
},
{ key: 'customer_analytics', objectName: 'Customer analytics', objectPlural: 'customer analytics' },
+ { key: 'customer_task', objectName: 'Customer task', objectPlural: 'customer tasks' },
{ key: 'customer_journey', objectName: 'Customer journey', objectPlural: 'customer journeys' },
{ key: 'data_catalog', objectName: 'Data catalog', objectPlural: 'data catalog' },
{
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 31ad73160013..5a6325a63767 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -109,6 +109,7 @@ export const productRoutes: Record<string, [string, string]> = {
'/customer_analytics/notes': ['CustomerAnalytics', 'customerAnalyticsNotes'],
'/customer_analytics/announcements': ['CustomerAnalytics', 'customerAnalyticsAnnouncements'],
'/customer_analytics/feed': ['CustomerAnalytics', 'customerAnalyticsFeed'],
+ '/customer_analytics/tasks': ['CustomerAnalytics', 'customerAnalyticsTasks'],
'/customer_analytics/feature-requests': ['CustomerAnalytics', 'customerAnalyticsFeatureRequests'],
'/customer_analytics/feature-requests/:requestId': ['CustomerAnalytics', 'customerAnalyticsFeatureRequests'],
'/customer_analytics/journeys/new': ['CustomerJourneyBuilder', 'customerJourneyBuilder'],
@@ -1121,6 +1122,7 @@ export const productUrls = {
customerAnalyticsNotes: (): string => '/customer_analytics/notes',
customerAnalyticsAnnouncements: (): string => '/customer_analytics/announcements',
customerAnalyticsFeed: (): string => '/customer_analytics/feed',
+ customerAnalyticsTasks: (): string => '/customer_analytics/tasks',
customerAnalyticsFeatureRequests: (requestId?: string): string =>
`/customer_analytics/feature-requests${requestId ? `/${requestId}` : ''}`,
customerAnalyticsJourneys: (): string => '/customer_analytics/journeys',
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 13e532711959..6b2ad04b3bfe 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -290,6 +290,7 @@ export enum AccessControlResourceType {
Organization = 'organization',
Action = 'action',
CustomerAnalytics = 'customer_analytics',
+ CustomerTask = 'customer_task',
FeatureFlag = 'feature_flag',
Heatmap = 'heatmap',
Insight = 'insight',
@@ -5860,6 +5861,7 @@ export const API_SCOPE_OBJECTS = [
'comment',
'conversation',
'customer_analytics',
+ 'customer_task',
'customer_journey',
'customer_profile_config',
'data_catalog',
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 05d812ee4292..2a604fd1e658 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -34,6 +34,7 @@ APIScopeObject = Literal[
"comment",
"conversation",
"customer_analytics",
+ "customer_task",
"customer_journey",
"customer_profile_config",
"data_catalog",
diff --git a/posthog/test/test_scopes.py b/posthog/test/test_scopes.py
index e0cf538d2c44..0f5d0a783679 100644
--- a/posthog/test/test_scopes.py
+++ b/posthog/test/test_scopes.py
@@ -16,6 +16,7 @@ from posthog.scopes import (
OAUTH_SCOPES_HIDDEN,
OIDC_SCOPES,
PRIVILEGED_SCOPES,
+ PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION,
UNPRIVILEGED_SCOPES,
clamp_scopes_to_ceiling,
downgrade_scopes_to_read_only,
@@ -109,7 +110,9 @@ class TestScopeSets(BaseTest):
def test_unprivileged_scopes_excludes_internal_scope(self, scope: str) -> None:
self.assertNotIn(scope, UNPRIVILEGED_SCOPES)
- @parameterized.expand([("insight:read",), ("dashboard:write",), ("query:read",)])
+ @parameterized.expand(
+ [("insight:read",), ("dashboard:write",), ("query:read",), ("customer_task:read",), ("customer_task:write",)]
+ )
def test_unprivileged_scopes_covers_known_public_scope(self, scope: str) -> None:
# Spot-check: a generic OAuth client should be able to request these.
self.assertIn(scope, UNPRIVILEGED_SCOPES)
@@ -142,6 +145,11 @@ class TestScopeSets(BaseTest):
self.assertIn(oidc, supported)
self.assertEqual(supported - set(OIDC_SCOPES), UNPRIVILEGED_SCOPES)
+ def test_project_secret_api_keys_exclude_user_bound_customer_task_scopes(self) -> None:
+ # Customer task endpoints need a user for RBAC and activity attribution.
+ self.assertNotIn(("customer_task", "read"), PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION)
+ self.assertNotIn(("customer_task", "write"), PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION)
+
def test_all_scope_objects_fit_in_oauthapplication_scopes_charfield(self) -> None:
# OAuthApplication.scopes is ArrayField(CharField(max_length=100)), matching
# PersonalAPIKey.scopes. Verify every `obj:action` string fits so admin-set
diff --git a/products/access_control/backend/facade/api.py b/products/access_control/backend/facade/api.py
index 7623d9b6b2db..d4a30cd5d0ae 100644
--- a/products/access_control/backend/facade/api.py
+++ b/products/access_control/backend/facade/api.py
@@ -18,18 +18,27 @@ Do NOT:
from __future__ import annotations
+from typing import cast
from uuid import UUID
from django.shortcuts import get_object_or_404
from posthog.models import OrganizationMembership, PropertyDefinition, Team
+from posthog.scopes import API_SCOPE_OBJECTS, INTERNAL_API_SCOPE_OBJECTS, APIScopeObject
from products.access_control.backend.models.role import Role
+from ..models.access_control import AccessControl
from ..models.property_access_control import PropertyAccessControl
from ..property_access_control import is_property_access_control_enabled
from . import contracts
from .contracts import PropertyAccessLevel
+from .user_access_control import highest_access_level, minimum_access_level, ordered_access_levels
+
+
+class InvalidObjectAccessControlError(Exception):
+ """Raised when an object access control rule names an unknown resource, an access level the
+ resource does not support, or a subject outside the team's organization."""
class PropertyDefinitionNotFoundError(Exception):
@@ -231,6 +240,99 @@ def delete_property_access_control(
raise PropertyAccessControlRuleNotFoundError
+# --- Object access controls ---
+
+
+def _to_object_rule(rule: AccessControl) -> contracts.ObjectAccessControlRule:
+ assert rule.resource_id is not None
+ return contracts.ObjectAccessControlRule(
+ id=rule.id,
+ resource=rule.resource,
+ resource_id=rule.resource_id,
+ access_level=rule.access_level,
+ organization_member_id=rule.organization_member_id,
+ role_id=rule.role_id,
+ )
+
+
+def _validate_object_access_control(
+ *, organization_id: UUID, input: contracts.SetObjectAccessControlInput
+) -> APIScopeObject:
+ resource = input.resource
+ if resource not in API_SCOPE_OBJECTS or resource in INTERNAL_API_SCOPE_OBJECTS:
+ raise InvalidObjectAccessControlError(f"{resource} is not an access controlled resource.")
+ scoped_resource = cast(APIScopeObject, resource)
+
+ if input.access_level is not None:
+ levels = ordered_access_levels(scoped_resource)
+ if input.access_level not in levels:
+ raise InvalidObjectAccessControlError(
+ f"Invalid access level for {resource}. Must be one of: {', '.join(levels)}."
+ )
+ # `ordered_access_levels` can include levels the settings UI never offers for a resource
+ # (for example "none" on a project), so the bounds apply here as well as in the API.
+ level_index = levels.index(input.access_level)
+ if level_index < levels.index(minimum_access_level(scoped_resource)):
+ raise InvalidObjectAccessControlError(f"Access level is below the minimum for {resource}.")
+ if level_index > levels.index(highest_access_level(scoped_resource)):
+ raise InvalidObjectAccessControlError(f"Access level is above the maximum for {resource}.")
+
+ if (
+ input.organization_member_id is not None
+ and not OrganizationMembership.objects.filter(
+ id=input.organization_member_id, organization_id=organization_id
+ ).exists()
+ ):
+ raise InvalidObjectAccessControlError("organization_member does not belong to this team's organization.")
+ if (
+ input.role_id is not None
+ and not Role.objects.filter(id=input.role_id, organization_id=organization_id).exists()
+ ):
+ raise InvalidObjectAccessControlError("role does not belong to this team's organization.")
+ return scoped_resource
+
+
+def set_object_access_control(
+ *,
+ team_id: int,
+ input: contracts.SetObjectAccessControlInput,
+) -> contracts.ObjectAccessControlRule | None:
+ """Grant, change, or remove one subject's access to one object.
+
+ This is the programmatic counterpart of the `PUT .../access_controls` endpoint, for product code
+ that must keep a rule in step with its own state (for example, the assignee of a work item).
+ It writes the rule only. The caller decides whether the actor may change access, and the
+ caller owns the reverse write when its state changes again.
+
+ A `UserAccessControl` built before this call still holds its preloaded rows. Build a new one
+ or clear its cache before checking the object again in the same request.
+
+ Returns the stored rule, or None when `access_level` is None and the rule was removed.
+ """
+ team = Team.objects.only("id", "organization_id").get(id=team_id)
+ resource = _validate_object_access_control(organization_id=team.organization_id, input=input)
+ if input.access_level is None:
+ AccessControl.objects.filter(
+ team_id=team_id,
+ resource=resource,
+ resource_id=input.resource_id,
+ organization_member_id=input.organization_member_id,
+ role_id=cast(UUID | str, input.role_id),
+ ).delete()
+ return None
+
+ rule, _created = AccessControl.objects.update_or_create(
+ team_id=team_id,
+ resource=resource,
+ resource_id=input.resource_id,
+ organization_member_id=input.organization_member_id,
+ role_id=cast(UUID | str, input.role_id),
+ defaults={"access_level": input.access_level},
+ create_defaults={"access_level": input.access_level, "created_by_id": input.created_by_id},
+ )
+ return _to_object_rule(rule)
+
+
# --- Convenience for external callers (avoids importing UUID type at call sites) ---
diff --git a/products/access_control/backend/facade/contracts.py b/products/access_control/backend/facade/contracts.py
index 36278a343cf8..136ae1978651 100644
--- a/products/access_control/backend/facade/contracts.py
+++ b/products/access_control/backend/facade/contracts.py
@@ -69,3 +69,35 @@ class DeletePropertyAccessControlInput:
property_definition_id: str
organization_member_id: UUID | None = None
role_id: UUID | None = None
+
+
+@dataclass(frozen=True)
+class SetObjectAccessControlInput:
+ """Input for granting, changing, or removing one subject's access to one object.
+
+ `access_level=None` removes the rule. Exactly one of `organization_member_id` or `role_id`
+ names the subject.
+ """
+
+ resource: str
+ resource_id: str
+ access_level: str | None
+ organization_member_id: UUID | None = None
+ role_id: UUID | None = None
+ created_by_id: int | None = None
+
+ def __post_init__(self) -> None:
+ if (self.organization_member_id is None) == (self.role_id is None):
+ raise ValueError("Set exactly one of organization_member_id or role_id.")
+
+
+@dataclass(frozen=True)
+class ObjectAccessControlRule:
+ """One object-level access control rule as stored."""
+
+ id: UUID
+ resource: str
+ resource_id: str
+ access_level: str
+ organization_member_id: UUID | None
+ role_id: UUID | None
diff --git a/products/access_control/backend/facade/user_access_control.py b/products/access_control/backend/facade/user_access_control.py
index 6a311e4e9cd2..7dbab8b360fa 100644
--- a/products/access_control/backend/facade/user_access_control.py
+++ b/products/access_control/backend/facade/user_access_control.py
@@ -109,6 +109,7 @@ RESOURCE_INHERITANCE_MAP: dict[APIScopeObject, APIScopeObject] = {
"llm_prompt": "llm_analytics",
"account": "customer_analytics",
"customer_journey": "customer_analytics",
+ "customer_task": "customer_analytics",
"experiment_saved_metric": "experiment",
"experiment_holdout": "experiment",
"dashboard_template": "dashboard",
@@ -337,6 +338,8 @@ def model_to_resource(model: Model) -> Optional[APIScopeObject]:
return "warehouse_table"
if name == "customerjourney":
return "customer_journey"
+ if name == "customertask":
+ return "customer_task"
if name in ("replayscanner", "replayobservation"):
return "replay_scanner"
if name in ("visionalertconfiguration", "visionalertevent"):
diff --git a/products/access_control/backend/tests/test_api.py b/products/access_control/backend/tests/test_api.py
index e69de29bb2d1..864e0540e3fc 100644
--- a/products/access_control/backend/tests/test_api.py
+++ b/products/access_control/backend/tests/test_api.py
@@ -0,0 +1,101 @@
+import pytest
+from posthog.test.base import BaseTest
+
+from parameterized import parameterized
+
+from posthog.constants import AvailableFeature
+from posthog.models import User
+from posthog.models.organization import Organization, OrganizationMembership
+
+from products.access_control.backend.facade import contracts
+from products.access_control.backend.facade.api import InvalidObjectAccessControlError, set_object_access_control
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.access_control.backend.models.access_control import AccessControl
+from products.access_control.backend.models.role import Role, RoleMembership
+from products.dashboards.backend.models.dashboard import Dashboard
+
+
+class TestSetObjectAccessControl(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+ self.other_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ self.other_membership = OrganizationMembership.objects.get(user=self.other_user, organization=self.organization)
+ self.dashboard = Dashboard.objects.create(team=self.team, created_by=self.user)
+ AccessControl.objects.create(team=self.team, resource="dashboard", resource_id=None, access_level="none")
+
+ def _grant(
+ self, access_level: str | None = "viewer", **overrides: object
+ ) -> contracts.ObjectAccessControlRule | None:
+ input_kwargs: dict = {
+ "resource": "dashboard",
+ "resource_id": str(self.dashboard.id),
+ "access_level": access_level,
+ "organization_member_id": self.other_membership.id,
+ }
+ input_kwargs.update(overrides)
+ return set_object_access_control(
+ team_id=self.team.id, input=contracts.SetObjectAccessControlInput(**input_kwargs)
+ )
+
+ def _other_user_level(self) -> str | None:
+ return UserAccessControl(user=self.other_user, team=self.team).get_user_access_level(self.dashboard)
+
+ def test_grant_update_and_revoke_are_visible_through_user_access_control(self) -> None:
+ assert self._other_user_level() == "none"
+
+ rule = self._grant("viewer")
+ assert rule is not None and rule.access_level == "viewer"
+ assert self._other_user_level() == "viewer"
+
+ updated = self._grant("editor")
+ assert updated is not None and updated.id == rule.id
+ assert self._other_user_level() == "editor"
+
+ assert self._grant(None) is None
+ assert self._other_user_level() == "none"
+ assert self._grant(None) is None
+
+ def test_role_rule_grants_role_members(self) -> None:
+ role = Role.objects.create(name="Sales", organization=self.organization)
+ RoleMembership.objects.create(user=self.other_user, role=role)
+
+ self._grant("viewer", organization_member_id=None, role_id=role.id)
+
+ assert self._other_user_level() == "viewer"
+
+ @parameterized.expand(
+ [
+ ("unknown_resource", {"resource": "not_a_resource"}),
+ ("internal_resource", {"resource": "INTERNAL"}),
+ ("unknown_level", {"access_level": "owner"}),
+ ("level_below_resource_minimum", {"resource": "action", "access_level": "none"}),
+ ("level_above_resource_maximum", {"resource": "activity_log", "access_level": "editor"}),
+ ]
+ )
+ def test_rejects_invalid_rules(self, _name: str, overrides: dict) -> None:
+ with pytest.raises(InvalidObjectAccessControlError):
+ self._grant(**overrides)
+ assert not AccessControl.objects.filter(resource_id=str(self.dashboard.id)).exists()
+
+ def test_rejects_subjects_from_another_organization(self) -> None:
+ other_org = Organization.objects.create(name="Other")
+ outsider = User.objects.create_and_join(other_org, "[email protected]", "testtest")
+ outsider_membership = OrganizationMembership.objects.get(user=outsider, organization=other_org)
+ other_org_role = Role.objects.create(name="Outside", organization=other_org)
+
+ with pytest.raises(InvalidObjectAccessControlError):
+ self._grant("viewer", organization_member_id=outsider_membership.id)
+ with pytest.raises(InvalidObjectAccessControlError):
+ self._grant("viewer", organization_member_id=None, role_id=other_org_role.id)
+
+ def test_requires_exactly_one_subject(self) -> None:
+ role = Role.objects.create(name="Sales", organization=self.organization)
+ with pytest.raises(ValueError):
+ self._grant("viewer", organization_member_id=None)
+ with pytest.raises(ValueError):
+ self._grant("viewer", role_id=role.id)
diff --git a/products/access_control/backend/tests/test_user_access_control.py b/products/access_control/backend/tests/test_user_access_control.py
index 951beea27b10..559e771a4ecb 100644
--- a/products/access_control/backend/tests/test_user_access_control.py
+++ b/products/access_control/backend/tests/test_user_access_control.py
@@ -1775,6 +1775,22 @@ class TestResourceInheritance(BaseUserAccessControlTest):
assert resource_access and resource_access.access_level == "none"
assert self.user_access_control.check_access_level_for_resource("session_recording_playlist", "viewer") is False
+ def test_customer_task_inherits_customer_analytics_access(self):
+ assert RESOURCE_INHERITANCE_MAP["customer_task"] == "customer_analytics"
+
+ self._create_access_control(
+ resource="customer_analytics",
+ resource_id=None,
+ access_level="viewer",
+ organization_member=self.organization_membership,
+ )
+ self._clear_uac_caches()
+
+ customer_task_access = self.user_access_control.access_level_for_resource("customer_task")
+ assert customer_task_access and customer_task_access.access_level == "viewer"
+ assert self.user_access_control.check_access_level_for_resource("customer_task", "viewer") is True
+ assert self.user_access_control.check_access_level_for_resource("customer_task", "editor") is False
+
def test_support_ticket_rule_does_not_gate_the_posthog_ai_conversation_scope(self):
"""`conversation` must not inherit from `ticket`.
diff --git a/products/customer_analytics/backend/constants.py b/products/customer_analytics/backend/constants.py
index 07ee239463af..0c9c9614a893 100644
--- a/products/customer_analytics/backend/constants.py
+++ b/products/customer_analytics/backend/constants.py
@@ -11,6 +11,7 @@ SLACK_ARCHIVES_ORIGIN = "https://posthog.slack.com/archives"
CUSTOMER_ANALYTICS_CSP_FLAG = "customer-analytics-csp"
CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG = "customer-analytics-feature-requests"
CUSTOMER_ANALYTICS_TRACK_RULES_FLAG = "customer-analytics-track-rules"
+CUSTOMER_ANALYTICS_CUSTOMER_TASKS_FLAG = "customer-analytics-customer-tasks"
# Mirrors frontend `FEATURE_FLAGS.WAREHOUSE_PERSON_PROPERTIES`. Gates the whole warehouse -> person
# properties feature: creating person-target custom property sources (API + UI), staging rows during
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 3f514d2e7f8d..ed066f20a53a 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -72,6 +72,7 @@ from posthog.models.tag import tagify
from posthog.models.tagged_item import TaggedItem
from posthog.models.team import Team
+from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.conversations.backend.facade.api import (
AccountEmailThreadMessage as AccountEmailThreadMessage,
AccountEmailThreadSummary as AccountEmailThreadSummary,
@@ -100,6 +101,7 @@ from products.customer_analytics.backend.logic import (
announcements as _announcements_logic,
channel_summaries as _channel_summaries_logic,
custom_property_values as _custom_property_values_logic,
+ customer_tasks as _customer_tasks_logic,
feature_requests as _feature_requests_logic,
relationships as _relationships_logic,
)
@@ -137,6 +139,10 @@ from products.customer_analytics.backend.models import (
Announcement,
CustomerJourney,
CustomerProfileConfig,
+ CustomerTask,
+ CustomerTaskActivity,
+ CustomerTaskActivityType,
+ CustomerTaskStatus,
CustomPropertyDefinition,
CustomPropertySource,
CustomPropertySyncRun,
@@ -187,7 +193,6 @@ _ACCOUNT_PROPERTY_INPUT_KEY = "properties"
if TYPE_CHECKING:
from posthog.models.user import User
- from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.customer_analytics.backend.models import CustomPropertyValue
from products.workflows.backend.services.account_audience import AccountAudienceFilters
@@ -3566,6 +3571,7 @@ def delete_account_for_view(
# linger in a Slack destination filter.
streams = _event_streams_containing_account(account)
team = account.team
+ _customer_tasks_logic.remove_customer_task_assignee_access_for_account(team=team, account_id=account.id)
account.delete()
schedule_email_thread_link_recalculation(team_id)
for stream in streams:
@@ -4545,6 +4551,239 @@ def delete_account_relationship(
return True
+def _to_customer_task_user_view(user: "User | None") -> contracts.CustomerTaskUserView | None:
+ if user is None:
+ return None
+ return contracts.CustomerTaskUserView(
+ id=user.id,
+ email=user.email,
+ first_name=user.first_name,
+ last_name=user.last_name,
+ )
+
+
+def _to_customer_task_view(task: CustomerTask, user_access_control: "UserAccessControl") -> contracts.CustomerTaskView:
+ account = (
+ contracts.CustomerTaskAccountView(id=task.account.id, name=task.account.name)
+ if task.account is not None
+ else None
+ )
+ return contracts.CustomerTaskView(
+ id=task.id,
+ account=account,
+ name=task.name,
+ description=task.description,
+ status=task.status,
+ assigned_to=_to_customer_task_user_view(task.assigned_to),
+ due_at=task.due_at,
+ completed_at=task.completed_at,
+ completed_by=_to_customer_task_user_view(task.completed_by),
+ created_by=_to_customer_task_user_view(task.created_by),
+ archived_at=task.archived_at,
+ created_at=task.created_at,
+ updated_at=task.updated_at,
+ can_edit=_customer_tasks_logic.can_edit_customer_task(task, user_access_control),
+ can_restore=_customer_tasks_logic.can_restore_customer_task(task, user_access_control),
+ )
+
+
+def _to_customer_task_change_value(
+ *,
+ field: str,
+ value: object | None,
+ account_context_present: bool,
+ account_context_id: object | None,
+ visible_account_ids: frozenset[str],
+) -> object | None:
+ if field == "account":
+ if value is None:
+ return None
+ if isinstance(value, dict):
+ account_id = value.get("id")
+ account_name = value.get("name")
+ if isinstance(account_id, str) and isinstance(account_name, str):
+ try:
+ normalized_account_id = str(UUID(account_id))
+ except ValueError:
+ pass
+ else:
+ if normalized_account_id in visible_account_ids:
+ return {"id": account_id, "name": account_name}
+ return {"id": None, "name": "Restricted account"}
+ if not account_context_present:
+ return None
+ if account_context_id is None:
+ return value
+ if isinstance(account_context_id, str):
+ try:
+ normalized_account_id = str(UUID(account_context_id))
+ except ValueError:
+ return None
+ if normalized_account_id in visible_account_ids:
+ return value
+ return None
+
+
+def _to_customer_task_activity_view(
+ activity: CustomerTaskActivity, visible_account_ids: frozenset[str]
+) -> contracts.CustomerTaskActivityView:
+ changes = []
+ for change in activity.changes:
+ if not isinstance(change, dict):
+ continue
+ field = str(change.get("field", ""))
+ changes.append(
+ contracts.CustomerTaskChange(
+ field=field,
+ before=_to_customer_task_change_value(
+ field=field,
+ value=change.get("before"),
+ account_context_present="before_account_id" in change,
+ account_context_id=change.get("before_account_id"),
+ visible_account_ids=visible_account_ids,
+ ),
+ after=_to_customer_task_change_value(
+ field=field,
+ value=change.get("after"),
+ account_context_present="after_account_id" in change,
+ account_context_id=change.get("after_account_id"),
+ visible_account_ids=visible_account_ids,
+ ),
+ )
+ )
+ return contracts.CustomerTaskActivityView(
+ id=activity.id,
+ activity_type=activity.activity_type,
+ changes=changes,
+ actor=_to_customer_task_user_view(activity.actor),
+ created_at=activity.created_at,
+ )
+
+
+CUSTOMER_TASK_ACTIVITY_TYPE_CHOICES = CustomerTaskActivityType.choices
+CUSTOMER_TASK_STATUS_CHOICES = CustomerTaskStatus.choices
+
+
+def list_customer_tasks(
+ *,
+ team_id: int,
+ user_access_control: "UserAccessControl",
+ filters: contracts.CustomerTaskListFilters,
+ offset: int,
+ limit: int,
+) -> tuple[list[contracts.CustomerTaskView], int]:
+ tasks, count = _customer_tasks_logic.list_customer_tasks(
+ team_id=team_id,
+ user_access_control=user_access_control,
+ filters=filters,
+ offset=offset,
+ limit=limit,
+ )
+ return [_to_customer_task_view(task, user_access_control) for task in tasks], count
+
+
+def get_customer_task(
+ *, team_id: int, task_id: UUID | str, user_access_control: "UserAccessControl"
+) -> contracts.CustomerTaskView | None:
+ task = _customer_tasks_logic.get_customer_task(
+ team_id=team_id,
+ task_id=task_id,
+ user_access_control=user_access_control,
+ )
+ return _to_customer_task_view(task, user_access_control) if task is not None else None
+
+
+def create_customer_task(
+ *,
+ team: Team,
+ input: contracts.CreateCustomerTaskInput,
+ actor: "User | None",
+ user_access_control: "UserAccessControl",
+) -> contracts.CustomerTaskView:
+ task = _customer_tasks_logic.create_customer_task(
+ team=team,
+ input=input,
+ actor=actor,
+ user_access_control=user_access_control,
+ )
+ return _to_customer_task_view(task, user_access_control)
+
+
+def update_customer_task(
+ *,
+ team: Team,
+ task_id: UUID | str,
+ input: contracts.UpdateCustomerTaskInput,
+ actor: "User | None",
+ user_access_control: "UserAccessControl",
+) -> contracts.CustomerTaskView | None:
+ task = _customer_tasks_logic.update_customer_task(
+ team=team,
+ task_id=task_id,
+ input=input,
+ actor=actor,
+ user_access_control=user_access_control,
+ )
+ if task is None:
+ return None
+ fresh_user_access_control = UserAccessControl(user=user_access_control.user, team=team)
+ return _to_customer_task_view(task, fresh_user_access_control)
+
+
+def archive_customer_task(
+ *,
+ team_id: int,
+ task_id: UUID | str,
+ actor: "User | None",
+ user_access_control: "UserAccessControl",
+) -> contracts.CustomerTaskView | None:
+ task = _customer_tasks_logic.archive_customer_task(
+ team_id=team_id,
+ task_id=task_id,
+ actor=actor,
+ user_access_control=user_access_control,
+ )
+ return _to_customer_task_view(task, user_access_control) if task is not None else None
+
+
+def restore_customer_task(
+ *,
+ team_id: int,
+ task_id: UUID | str,
+ actor: "User | None",
+ user_access_control: "UserAccessControl",
+) -> contracts.CustomerTaskView | None:
+ task = _customer_tasks_logic.restore_customer_task(
+ team_id=team_id,
+ task_id=task_id,
+ actor=actor,
+ user_access_control=user_access_control,
+ )
+ return _to_customer_task_view(task, user_access_control) if task is not None else None
+
+
+def list_customer_task_activities(
+ *,
+ team_id: int,
+ task_id: UUID | str,
+ user_access_control: "UserAccessControl",
+ offset: int,
+ limit: int,
+) -> tuple[list[contracts.CustomerTaskActivityView], int] | None:
+ result = _customer_tasks_logic.list_customer_task_activities(
+ team_id=team_id,
+ task_id=task_id,
+ user_access_control=user_access_control,
+ offset=offset,
+ limit=limit,
+ )
+ if result is None:
+ return None
+ return [
+ _to_customer_task_activity_view(activity, result.visible_account_ids) for activity in result.activities
+ ], result.total_count
+
+
# --- EventStream ---
diff --git a/products/customer_analytics/backend/facade/constants.py b/products/customer_analytics/backend/facade/constants.py
index f051895f6e51..6f314ae6ce11 100644
--- a/products/customer_analytics/backend/facade/constants.py
+++ b/products/customer_analytics/backend/facade/constants.py
@@ -11,6 +11,7 @@ from products.customer_analytics.backend.constants import (
CUSTOM_PROPERTY_DISPLAY_TYPE_CHOICES,
CUSTOM_PROPERTY_OPTION_COLORS,
CUSTOMER_ANALYTICS_CSP_FLAG,
+ CUSTOMER_ANALYTICS_CUSTOMER_TASKS_FLAG,
CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG,
CUSTOMER_ANALYTICS_TRACK_RULES_FLAG,
DEFAULT_ACTIVITY_EVENT,
@@ -25,6 +26,7 @@ __all__ = [
"CUSTOM_PROPERTY_DISPLAY_TYPE_CHOICES",
"CUSTOM_PROPERTY_OPTION_COLORS",
"CUSTOMER_ANALYTICS_CSP_FLAG",
+ "CUSTOMER_ANALYTICS_CUSTOMER_TASKS_FLAG",
"CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG",
"CUSTOMER_ANALYTICS_TRACK_RULES_FLAG",
"DEFAULT_ACTIVITY_EVENT",
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index 46407aebda28..b64a6f50e161 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -1181,3 +1181,118 @@ class AnnouncementView:
created_by: UserBasicInfo | None = None
deliveries: list[AnnouncementDeliveryView] = field(default_factory=list)
channels: list[str] = field(default_factory=list)
+
+
+class CustomerTaskAccountNotFound(Exception):
+ pass
+
+
+class CustomerTaskAssigneeInvalid(Exception):
+ pass
+
+
+class CustomerTaskAssigneeCannotViewAccount(Exception):
+ pass
+
+
+class CustomerTaskInvalidTransition(Exception):
+ def __init__(self, current: str, requested: str) -> None:
+ self.current = current
+ self.requested = requested
+ super().__init__(current, requested)
+
+
+class CustomerTaskArchived(Exception):
+ pass
+
+
+class CustomerTaskAccessDenied(Exception):
+ pass
+
+
+@stdlib_dataclass(frozen=True)
+class CustomerTaskUserView:
+ id: int
+ email: str
+ first_name: str
+ last_name: str
+
+
+@stdlib_dataclass(frozen=True)
+class CustomerTaskAccountView:
+ id: UUID
+ name: str
+
+
+@stdlib_dataclass(frozen=True)
+class CustomerTaskView:
+ id: UUID
+ account: CustomerTaskAccountView | None
+ name: str
+ description: str | None
+ status: str
+ assigned_to: CustomerTaskUserView | None
+ due_at: datetime | None
+ completed_at: datetime | None
+ completed_by: CustomerTaskUserView | None
+ created_by: CustomerTaskUserView | None
+ archived_at: datetime | None
+ created_at: datetime
+ updated_at: datetime
+ can_edit: bool
+ can_restore: bool
+
+
+@stdlib_dataclass(frozen=True)
+class CustomerTaskChange:
+ field: str
+ before: object | None
+ after: object | None
+
+
+@stdlib_dataclass(frozen=True)
+class CustomerTaskActivityView:
+ id: UUID
+ activity_type: str
+ changes: list[CustomerTaskChange]
+ actor: CustomerTaskUserView | None
+ created_at: datetime
+
+
+@stdlib_dataclass(frozen=True)
+class CustomerTaskListFilters:
+ search: str | None = None
+ account_id: UUID | None = None
+ assigned_to: str | None = None
+ statuses: tuple[str, ...] = ()
+ archive_state: str = "active"
+ due_after: datetime | None = None
+ due_before: datetime | None = None
+ has_due_at: bool | None = None
+ ordering: str | None = None
+
+
+@stdlib_dataclass(frozen=True)
+class CreateCustomerTaskInput:
+ account_id: UUID | None = None
+ name: str = ""
+ description: str | None = None
+ assigned_to_id: int | None = None
+ due_at: datetime | None = None
+ status: str = "open"
+
+
+@stdlib_dataclass(frozen=True)
+class UpdateCustomerTaskInput:
+ account_id: UUID | None = None
+ name: str | None = None
+ description: str | None = None
+ assigned_to_id: int | None = None
+ due_at: datetime | None = None
+ status: str | None = None
+ account_id_provided: bool = False
+ name_provided: bool = False
+ description_provided: bool = False
+ assigned_to_id_provided: bool = False
+ due_at_provided: bool = False
+ status_provided: bool = False
diff --git a/products/customer_analytics/backend/logic/customer_tasks.py b/products/customer_analytics/backend/logic/customer_tasks.py
new file mode 100644
index 000000000000..a66ea22739ff
--- /dev/null
+++ b/products/customer_analytics/backend/logic/customer_tasks.py
@@ -0,0 +1,573 @@
+from __future__ import annotations
+
+from collections.abc import Iterable
+from datetime import datetime
+from typing import cast
+from uuid import UUID
+
+from django.core.exceptions import ValidationError as DjangoValidationError
+from django.db import transaction
+from django.db.models import Case, CharField, F, IntegerField, Q, QuerySet, Value, When
+from django.db.models.functions import Coalesce, Concat, Lower, NullIf, Trim
+from django.utils import timezone
+
+from posthog.dataclasses import frozen
+from posthog.models import OrganizationMembership, Team, User
+
+from products.access_control.backend.facade import (
+ api as access_control_api,
+ contracts as access_control_contracts,
+)
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.customer_analytics.backend.facade import contracts
+from products.customer_analytics.backend.facade.contracts import (
+ CustomerTaskAccessDenied,
+ CustomerTaskAccountNotFound,
+ CustomerTaskArchived,
+ CustomerTaskAssigneeCannotViewAccount,
+ CustomerTaskAssigneeInvalid,
+ CustomerTaskInvalidTransition,
+)
+from products.customer_analytics.backend.models import Account, CustomerTask, CustomerTaskActivity
+from products.customer_analytics.backend.models.customer_task import CustomerTaskActivityType, CustomerTaskStatus
+
+CUSTOMER_TASK_ACTIVITY_TYPE_CHOICES = CustomerTaskActivityType.choices
+CUSTOMER_TASK_STATUS_CHOICES = CustomerTaskStatus.choices
+
+
+@frozen
+class _CustomerTaskActivityPage:
+ activities: list[CustomerTaskActivity]
+ total_count: int
+ visible_account_ids: frozenset[str]
+
+
+_ALLOWED_TRANSITIONS: dict[str, frozenset[str]] = {
+ CustomerTaskStatus.OPEN.value: frozenset(
+ {CustomerTaskStatus.IN_PROGRESS.value, CustomerTaskStatus.COMPLETED.value, CustomerTaskStatus.CANCELED.value}
+ ),
+ CustomerTaskStatus.IN_PROGRESS.value: frozenset(
+ {CustomerTaskStatus.OPEN.value, CustomerTaskStatus.COMPLETED.value, CustomerTaskStatus.CANCELED.value}
+ ),
+ CustomerTaskStatus.COMPLETED.value: frozenset({CustomerTaskStatus.OPEN.value}),
+ CustomerTaskStatus.CANCELED.value: frozenset({CustomerTaskStatus.OPEN.value}),
+}
+
+
+def _task_queryset(team_id: int) -> QuerySet[CustomerTask]:
+ return CustomerTask.objects.for_team(team_id).select_related("account", "assigned_to", "completed_by", "created_by")
+
+
+def _visible_account_queryset(team_id: int, user_access_control: UserAccessControl) -> QuerySet[Account]:
+ accounts = Account.objects.for_team(team_id)
+ return user_access_control.filter_queryset_by_access_level(accounts, resource="account")
+
+
+def _task_by_id(queryset: QuerySet[CustomerTask], task_id: UUID | str) -> CustomerTask | None:
+ try:
+ return queryset.filter(id=task_id).first()
+ except (DjangoValidationError, ValueError):
+ return None
+
+
+def _visible_task_queryset(team_id: int, user_access_control: UserAccessControl) -> QuerySet[CustomerTask]:
+ visible_account_ids = _visible_account_queryset(team_id, user_access_control).values("id")
+ account_filter = Q(account__isnull=True) | Q(account_id__in=visible_account_ids)
+ return user_access_control.filter_queryset_by_access_level(
+ _task_queryset(team_id), resource="customer_task"
+ ).filter(account_filter)
+
+
+def _account_for_write(team_id: int, account_id: UUID | None, user_access_control: UserAccessControl) -> Account | None:
+ if account_id is None:
+ return None
+ account = _visible_account_queryset(team_id, user_access_control).filter(id=account_id).first()
+ if account is None:
+ raise CustomerTaskAccountNotFound()
+ return account
+
+
+def _validate_assignee(
+ *,
+ team: Team,
+ account: Account | None,
+ assignee_id: int | None,
+) -> User | None:
+ if assignee_id is None:
+ return None
+ membership_exists = OrganizationMembership.objects.filter(
+ organization_id=team.organization_id, user_id=assignee_id
+ ).exists()
+ if not membership_exists:
+ raise CustomerTaskAssigneeInvalid()
+ assignee = User.objects.filter(id=assignee_id).first()
+ if assignee is None:
+ raise CustomerTaskAssigneeInvalid()
+ assignee_access = UserAccessControl(user=assignee, team=team)
+ if not assignee_access.check_access_level_for_object(team, required_level="member"):
+ raise CustomerTaskAssigneeInvalid()
+ if account is not None and not assignee_access.check_access_level_for_object(account, required_level="viewer"):
+ raise CustomerTaskAssigneeCannotViewAccount()
+ return assignee
+
+
+def _set_customer_task_assignee_access(
+ *,
+ task: CustomerTask,
+ organization_id: UUID,
+ before_assignee: User | None,
+ after_assignee: User | None,
+ actor: User | None,
+) -> None:
+ if before_assignee == after_assignee:
+ return
+
+ for assignee, access_level in ((before_assignee, None), (after_assignee, "editor")):
+ if assignee is None:
+ continue
+ membership_id = (
+ OrganizationMembership.objects.filter(organization_id=organization_id, user_id=assignee.id)
+ .values_list("id", flat=True)
+ .first()
+ )
+ if membership_id is None:
+ if access_level is not None:
+ raise CustomerTaskAssigneeInvalid()
+ continue
+ access_control_api.set_object_access_control(
+ team_id=task.team_id,
+ input=access_control_contracts.SetObjectAccessControlInput(
+ resource="customer_task",
+ resource_id=str(task.id),
+ organization_member_id=membership_id,
+ access_level=access_level,
+ created_by_id=actor.id if actor is not None else None,
+ ),
+ )
+
+
+def can_edit_customer_task(task: CustomerTask, user_access_control: UserAccessControl) -> bool:
+ return task.archived_at is None and user_access_control.check_access_level_for_object(task, "editor")
+
+
+def can_restore_customer_task(task: CustomerTask, user_access_control: UserAccessControl) -> bool:
+ return task.archived_at is not None and user_access_control.check_access_level_for_object(task, "editor")
+
+
+def _timestamp(value: datetime | None) -> str | None:
+ if value is None:
+ return None
+ return value.isoformat().replace("+00:00", "Z")
+
+
+def _snapshot_account(account: Account | None) -> dict[str, object] | None:
+ if account is None:
+ return None
+ return {"id": str(account.id), "name": account.name}
+
+
+def _snapshot_user(user: User | None) -> dict[str, object] | None:
+ if user is None:
+ return None
+ return {"id": user.id, "email": user.email, "first_name": user.first_name, "last_name": user.last_name}
+
+
+def _changes(
+ *,
+ before_account: Account | None,
+ after_account: Account | None,
+ before_name: str | None,
+ after_name: str | None,
+ before_description: str | None,
+ after_description: str | None,
+ before_status: str | None,
+ after_status: str | None,
+ before_assignee: User | None,
+ after_assignee: User | None,
+ before_due_at: datetime | None,
+ after_due_at: datetime | None,
+) -> list[dict[str, object | None]]:
+ values: Iterable[tuple[str, object | None, object | None]] = (
+ ("account", _snapshot_account(before_account), _snapshot_account(after_account)),
+ ("name", before_name, after_name),
+ ("description", before_description, after_description),
+ ("status", before_status, after_status),
+ ("assigned_to", _snapshot_user(before_assignee), _snapshot_user(after_assignee)),
+ ("due_at", _timestamp(before_due_at), _timestamp(after_due_at)),
+ )
+ before_account_id = str(before_account.id) if before_account is not None else None
+ after_account_id = str(after_account.id) if after_account is not None else None
+ changes: list[dict[str, object | None]] = []
+ for field, before, after in values:
+ if before == after:
+ continue
+ change: dict[str, object | None] = {"field": field, "before": before, "after": after}
+ if field != "account":
+ change["before_account_id"] = before_account_id
+ change["after_account_id"] = after_account_id
+ changes.append(change)
+ return changes
+
+
+def _record_activity(
+ *, task: CustomerTask, activity_type: str, actor: User | None, changes: list[dict[str, object | None]]
+) -> None:
+ CustomerTaskActivity.objects.for_team(task.team_id).create(
+ team_id=task.team_id,
+ task=task,
+ actor=actor,
+ activity_type=activity_type,
+ changes=changes,
+ )
+
+
+def _order_by_annotation(queryset: QuerySet[CustomerTask], annotation: str, descending: bool) -> QuerySet[CustomerTask]:
+ ordering = F(annotation).desc(nulls_last=True) if descending else F(annotation).asc(nulls_last=True)
+ return queryset.order_by(ordering, "id")
+
+
+def _apply_ordering(queryset: QuerySet[CustomerTask], ordering: str) -> QuerySet[CustomerTask]:
+ descending = ordering.startswith("-")
+ field = ordering.removeprefix("-")
+ if field == "status":
+ queryset = queryset.alias(
+ _ordering_status=Case(
+ When(status=CustomerTaskStatus.OPEN, then=Value(0)),
+ When(status=CustomerTaskStatus.IN_PROGRESS, then=Value(1)),
+ When(status=CustomerTaskStatus.COMPLETED, then=Value(2)),
+ When(status=CustomerTaskStatus.CANCELED, then=Value(3)),
+ default=Value(4),
+ output_field=IntegerField(),
+ )
+ )
+ return _order_by_annotation(queryset, "_ordering_status", descending)
+ if field == "assigned_to":
+ queryset = queryset.alias(
+ _ordering_assigned_to=Lower(
+ Coalesce(
+ NullIf(Trim(Concat("assigned_to__first_name", Value(" "), "assigned_to__last_name")), Value("")),
+ "assigned_to__email",
+ output_field=CharField(),
+ )
+ )
+ )
+ return _order_by_annotation(queryset, "_ordering_assigned_to", descending)
+ if field == "account":
+ queryset = queryset.alias(_ordering_account=Lower("account__name"))
+ return _order_by_annotation(queryset, "_ordering_account", descending)
+ if field == "name":
+ queryset = queryset.alias(_ordering_name=Lower("name"))
+ return _order_by_annotation(queryset, "_ordering_name", descending)
+ return _order_by_annotation(queryset, field, descending)
+
+
+def remove_customer_task_assignee_access_for_account(*, team: Team, account_id: UUID) -> None:
+ tasks = _task_queryset(team.id).filter(account_id=account_id, assigned_to__isnull=False)
+ for task in tasks.iterator():
+ _set_customer_task_assignee_access(
+ task=task,
+ organization_id=team.organization_id,
+ before_assignee=task.assigned_to,
+ after_assignee=None,
+ actor=None,
+ )
+
+
+def list_customer_tasks(
+ *,
+ team_id: int,
+ user_access_control: UserAccessControl,
+ filters: contracts.CustomerTaskListFilters,
+ offset: int,
+ limit: int,
+) -> tuple[list[CustomerTask], int]:
+ queryset = _visible_task_queryset(team_id, user_access_control)
+ if filters.search:
+ queryset = queryset.filter(Q(name__icontains=filters.search) | Q(description__icontains=filters.search))
+ if filters.account_id is not None:
+ queryset = queryset.filter(account_id=filters.account_id)
+ if filters.assigned_to == "me":
+ queryset = queryset.filter(assigned_to_id=user_access_control.user.id)
+ elif filters.assigned_to == "unassigned":
+ queryset = queryset.filter(assigned_to_id__isnull=True)
+ elif filters.assigned_to:
+ queryset = queryset.filter(assigned_to_id=int(filters.assigned_to))
+ if filters.statuses:
+ queryset = queryset.filter(status__in=filters.statuses)
+ if filters.archive_state == "active":
+ queryset = queryset.filter(archived_at__isnull=True)
+ elif filters.archive_state == "archived":
+ queryset = queryset.filter(archived_at__isnull=False)
+ if filters.due_after is not None:
+ queryset = queryset.filter(due_at__gte=filters.due_after)
+ if filters.due_before is not None:
+ queryset = queryset.filter(due_at__lt=filters.due_before)
+ if filters.has_due_at is not None:
+ queryset = queryset.filter(due_at__isnull=not filters.has_due_at)
+
+ if filters.ordering is None:
+ queryset = queryset.order_by(F("due_at").asc(nulls_last=True), "-updated_at", "id")
+ else:
+ queryset = _apply_ordering(queryset, filters.ordering)
+ count = queryset.count()
+ return list(queryset[offset : offset + limit]), count
+
+
+def get_customer_task(
+ *, team_id: int, task_id: UUID | str, user_access_control: UserAccessControl
+) -> CustomerTask | None:
+ return _task_by_id(_visible_task_queryset(team_id, user_access_control), task_id)
+
+
+def _task_for_write(
+ *, team_id: int, task_id: UUID | str, user_access_control: UserAccessControl
+) -> CustomerTask | None:
+ queryset = _visible_task_queryset(team_id, user_access_control).select_for_update(of=("self",))
+ return _task_by_id(queryset, task_id)
+
+
+def create_customer_task(
+ *,
+ team: Team,
+ input: contracts.CreateCustomerTaskInput,
+ actor: User | None,
+ user_access_control: UserAccessControl,
+) -> CustomerTask:
+ account = _account_for_write(team.id, input.account_id, user_access_control)
+ assignee = _validate_assignee(team=team, account=account, assignee_id=input.assigned_to_id)
+ completed_at = timezone.now() if input.status == CustomerTaskStatus.COMPLETED else None
+ completed_by = actor if completed_at is not None and actor is not None else assignee if completed_at else None
+ with transaction.atomic():
+ task = CustomerTask.objects.for_team(team.id).create(
+ team_id=team.id,
+ account=account,
+ name=input.name,
+ description=input.description,
+ assigned_to=assignee,
+ due_at=input.due_at,
+ status=input.status,
+ completed_at=completed_at,
+ completed_by=completed_by,
+ created_by=actor,
+ )
+ _set_customer_task_assignee_access(
+ task=task,
+ organization_id=team.organization_id,
+ before_assignee=None,
+ after_assignee=assignee,
+ actor=actor,
+ )
+ _record_activity(
+ task=task,
+ activity_type=CustomerTaskActivityType.CREATED,
+ actor=actor,
+ changes=_changes(
+ before_account=None,
+ after_account=account,
+ before_name=None,
+ after_name=task.name,
+ before_description=None,
+ after_description=task.description,
+ before_status=None,
+ after_status=task.status,
+ before_assignee=None,
+ after_assignee=assignee,
+ before_due_at=None,
+ after_due_at=task.due_at,
+ ),
+ )
+ return task
+
+
+def update_customer_task(
+ *,
+ team: Team,
+ task_id: UUID | str,
+ input: contracts.UpdateCustomerTaskInput,
+ actor: User | None,
+ user_access_control: UserAccessControl,
+) -> CustomerTask | None:
+ with transaction.atomic():
+ task = _task_for_write(team_id=team.id, task_id=task_id, user_access_control=user_access_control)
+ if task is None:
+ return None
+ if not can_access_customer_task_object(task=task, user_access_control=user_access_control, write=True):
+ raise CustomerTaskAccessDenied()
+ if task.archived_at is not None:
+ raise CustomerTaskArchived()
+
+ before_account = task.account
+ before_name = task.name
+ before_description = task.description
+ before_status = task.status
+ before_assignee = task.assigned_to
+ before_due_at = task.due_at
+ semantic_change = (
+ (input.account_id_provided and input.account_id != task.account_id)
+ or (input.name_provided and input.name != task.name)
+ or (input.description_provided and input.description != task.description)
+ or (input.assigned_to_id_provided and input.assigned_to_id != task.assigned_to_id)
+ or (input.due_at_provided and input.due_at != task.due_at)
+ or (input.status_provided and input.status != task.status)
+ )
+ if not semantic_change:
+ return task
+
+ account = _account_for_write(
+ team.id, input.account_id if input.account_id_provided else task.account_id, user_access_control
+ )
+ assignee_id = input.assigned_to_id if input.assigned_to_id_provided else task.assigned_to_id
+ assignee = _validate_assignee(team=team, account=account, assignee_id=assignee_id)
+ requested_status = input.status if input.status_provided else task.status
+ if requested_status is None:
+ raise CustomerTaskInvalidTransition(task.status, "")
+ if (
+ input.status_provided
+ and requested_status != task.status
+ and requested_status not in _ALLOWED_TRANSITIONS[task.status]
+ ):
+ raise CustomerTaskInvalidTransition(task.status, requested_status)
+
+ if requested_status == CustomerTaskStatus.COMPLETED and task.status != CustomerTaskStatus.COMPLETED:
+ completed_at = timezone.now()
+ completed_by = actor if actor is not None else assignee
+ elif requested_status == CustomerTaskStatus.OPEN and task.status == CustomerTaskStatus.COMPLETED:
+ completed_at = None
+ completed_by = None
+ else:
+ completed_at = task.completed_at
+ completed_by = task.completed_by
+
+ task.account = account
+ if input.name_provided:
+ task.name = cast(str, input.name)
+ task.description = input.description if input.description_provided else task.description
+ task.assigned_to = assignee
+ task.due_at = input.due_at if input.due_at_provided else task.due_at
+ task.status = requested_status
+ task.completed_at = completed_at
+ task.completed_by = completed_by
+ task.save()
+ _set_customer_task_assignee_access(
+ task=task,
+ organization_id=team.organization_id,
+ before_assignee=before_assignee,
+ after_assignee=assignee,
+ actor=actor,
+ )
+ changes = _changes(
+ before_account=before_account,
+ after_account=task.account,
+ before_name=before_name,
+ after_name=task.name,
+ before_description=before_description,
+ after_description=task.description,
+ before_status=before_status,
+ after_status=task.status,
+ before_assignee=before_assignee,
+ after_assignee=task.assigned_to,
+ before_due_at=before_due_at,
+ after_due_at=task.due_at,
+ )
+ if changes:
+ _record_activity(task=task, activity_type=CustomerTaskActivityType.UPDATED, actor=actor, changes=changes)
+ return task
+
+
+def archive_customer_task(
+ *, team_id: int, task_id: UUID | str, actor: User | None, user_access_control: UserAccessControl
+) -> CustomerTask | None:
+ with transaction.atomic():
+ task = _task_for_write(team_id=team_id, task_id=task_id, user_access_control=user_access_control)
+ if task is None:
+ return None
+ if not can_access_customer_task_object(task=task, user_access_control=user_access_control, write=True):
+ raise CustomerTaskAccessDenied()
+ if task.archived_at is None:
+ task.archived_at = timezone.now()
+ task.save(update_fields=["archived_at", "updated_at"])
+ _record_activity(task=task, activity_type=CustomerTaskActivityType.ARCHIVED, actor=actor, changes=[])
+ return task
+
+
+def restore_customer_task(
+ *, team_id: int, task_id: UUID | str, actor: User | None, user_access_control: UserAccessControl
+) -> CustomerTask | None:
+ with transaction.atomic():
+ task = _task_for_write(team_id=team_id, task_id=task_id, user_access_control=user_access_control)
+ if task is None:
+ return None
+ if not can_access_customer_task_object(task=task, user_access_control=user_access_control, write=True):
+ raise CustomerTaskAccessDenied()
+ if task.archived_at is not None:
+ task.archived_at = None
+ task.save(update_fields=["archived_at", "updated_at"])
+ _record_activity(task=task, activity_type=CustomerTaskActivityType.RESTORED, actor=actor, changes=[])
+ return task
+
+
+def _list_visible_historical_account_ids(
+ *,
+ team_id: int,
+ activities: list[CustomerTaskActivity],
+ user_access_control: UserAccessControl,
+) -> frozenset[str]:
+ historical_account_ids: set[UUID] = set()
+ for activity in activities:
+ for change in activity.changes:
+ if not isinstance(change, dict):
+ continue
+ for context_key in ("before_account_id", "after_account_id"):
+ account_id = change.get(context_key)
+ if not isinstance(account_id, str):
+ continue
+ try:
+ historical_account_ids.add(UUID(account_id))
+ except ValueError:
+ continue
+ if change.get("field") != "account":
+ continue
+ for key in ("before", "after"):
+ snapshot = change.get(key)
+ if not isinstance(snapshot, dict) or not isinstance(snapshot.get("id"), str):
+ continue
+ try:
+ historical_account_ids.add(UUID(snapshot["id"]))
+ except ValueError:
+ continue
+ if not historical_account_ids:
+ return frozenset()
+ visible_ids = _visible_account_queryset(team_id, user_access_control).filter(id__in=historical_account_ids)
+ return frozenset(str(account_id) for account_id in visible_ids.values_list("id", flat=True))
+
+
+def list_customer_task_activities(
+ *, team_id: int, task_id: UUID | str, user_access_control: UserAccessControl, offset: int, limit: int
+) -> _CustomerTaskActivityPage | None:
+ task = get_customer_task(team_id=team_id, task_id=task_id, user_access_control=user_access_control)
+ if task is None or not can_access_customer_task_object(
+ task=task, user_access_control=user_access_control, write=False
+ ):
+ return None
+ queryset = CustomerTaskActivity.objects.for_team(team_id).filter(task_id=task.id).select_related("actor")
+ count = queryset.count()
+ activities = list(queryset.order_by("-created_at", "-id")[offset : offset + limit])
+ visible_account_ids = _list_visible_historical_account_ids(
+ team_id=team_id,
+ activities=activities,
+ user_access_control=user_access_control,
+ )
+ return _CustomerTaskActivityPage(
+ activities=activities,
+ total_count=count,
+ visible_account_ids=visible_account_ids,
+ )
+
+
+def can_access_customer_task_object(*, task: CustomerTask, user_access_control: UserAccessControl, write: bool) -> bool:
+ if (
+ task.account_id is not None
+ and not _visible_account_queryset(task.team_id, user_access_control).filter(id=task.account_id).exists()
+ ):
+ return False
+ return user_access_control.check_access_level_for_object(task, "editor" if write else "viewer")
diff --git a/products/customer_analytics/backend/migrations/0047_customertask_customertaskactivity_and_more.py b/products/customer_analytics/backend/migrations/0047_customertask_customertaskactivity_and_more.py
new file mode 100644
index 000000000000..e232d734a464
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0047_customertask_customertaskactivity_and_more.py
@@ -0,0 +1,179 @@
+# Generated by Django 5.2.17 on 2026-09-02 16:55
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("customer_analytics", "0046_usercustomeranalyticsconfig"),
+ ("posthog", "1333_uploaded_media_library_index"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="CustomerTask",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("name", models.CharField(max_length=400)),
+ ("description", models.TextField(blank=True, null=True)),
+ ("properties", models.JSONField(db_default={}, default=dict)),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("open", "Open"),
+ ("in_progress", "In progress"),
+ ("completed", "Completed"),
+ ("canceled", "Canceled"),
+ ],
+ default="open",
+ max_length=20,
+ ),
+ ),
+ ("due_at", models.DateTimeField(blank=True, null=True)),
+ ("completed_at", models.DateTimeField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ("archived_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "account",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="customer_tasks",
+ to="customer_analytics.account",
+ ),
+ ),
+ (
+ "assigned_to",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ db_index=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "completed_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ db_index=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ db_index=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ ),
+ migrations.CreateModel(
+ name="CustomerTaskActivity",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "activity_type",
+ models.CharField(
+ choices=[
+ ("created", "Created"),
+ ("updated", "Updated"),
+ ("archived", "Archived"),
+ ("restored", "Restored"),
+ ],
+ max_length=20,
+ ),
+ ),
+ ("changes", models.JSONField(default=list)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "actor",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ db_index=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "task",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="activities",
+ to="customer_analytics.customertask",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ ),
+ migrations.AddConstraint(
+ model_name="customertask",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ models.Q(("status", "completed"), ("completed_at__isnull", False)),
+ models.Q(
+ models.Q(("status", "completed"), _negated=True),
+ ("completed_at__isnull", True),
+ ),
+ _connector="OR",
+ ),
+ name="customer_task_completion_consistency",
+ ),
+ ),
+ ]
diff --git a/products/customer_analytics/backend/migrations/0048_add_customer_task_foreign_keys.py b/products/customer_analytics/backend/migrations/0048_add_customer_task_foreign_keys.py
new file mode 100644
index 000000000000..afdefc7a5922
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0048_add_customer_task_foreign_keys.py
@@ -0,0 +1,52 @@
+from django.db import migrations
+
+from posthog.migration_helpers import AddForeignKeyNotValid
+
+
+class Migration(migrations.Migration):
+ dependencies = [("customer_analytics", "0047_customertask_customertaskactivity_and_more")]
+
+ operations = [
+ AddForeignKeyNotValid(
+ model_name="customertask",
+ name="ca_customer_task_team_id_fk",
+ column="team_id",
+ to_table="posthog_team",
+ to_column="id",
+ ),
+ AddForeignKeyNotValid(
+ model_name="customertask",
+ name="ca_customer_task_assigned_to_id_fk",
+ column="assigned_to_id",
+ to_table="posthog_user",
+ to_column="id",
+ ),
+ AddForeignKeyNotValid(
+ model_name="customertask",
+ name="ca_customer_task_completed_by_id_fk",
+ column="completed_by_id",
+ to_table="posthog_user",
+ to_column="id",
+ ),
+ AddForeignKeyNotValid(
+ model_name="customertask",
+ name="ca_customer_task_created_by_id_fk",
+ column="created_by_id",
+ to_table="posthog_user",
+ to_column="id",
+ ),
+ AddForeignKeyNotValid(
+ model_name="customertaskactivity",
+ name="ca_customer_task_activity_team_id_fk",
+ column="team_id",
+ to_table="posthog_team",
+ to_column="id",
+ ),
+ AddForeignKeyNotValid(
+ model_name="customertaskactivity",
+ name="ca_customer_task_activity_actor_id_fk",
+ column="actor_id",
+ to_table="posthog_user",
+ to_column="id",
+ ),
+ ]
diff --git a/products/customer_analytics/backend/migrations/0049_validate_customer_task_foreign_keys.py b/products/customer_analytics/backend/migrations/0049_validate_customer_task_foreign_keys.py
new file mode 100644
index 000000000000..11db59284cd9
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0049_validate_customer_task_foreign_keys.py
@@ -0,0 +1,22 @@
+from django.db import migrations
+
+from posthog.migration_helpers import ValidateForeignKey
+
+
+class Migration(migrations.Migration):
+ dependencies = [("customer_analytics", "0048_add_customer_task_foreign_keys")]
+
+ operations = [
+ ValidateForeignKey(model_name="customertask", name="ca_customer_task_team_id_fk"),
+ ValidateForeignKey(model_name="customertask", name="ca_customer_task_assigned_to_id_fk"),
+ ValidateForeignKey(model_name="customertask", name="ca_customer_task_completed_by_id_fk"),
+ ValidateForeignKey(model_name="customertask", name="ca_customer_task_created_by_id_fk"),
+ ValidateForeignKey(
+ model_name="customertaskactivity",
+ name="ca_customer_task_activity_team_id_fk",
+ ),
+ ValidateForeignKey(
+ model_name="customertaskactivity",
+ name="ca_customer_task_activity_actor_id_fk",
+ ),
+ ]
diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txt
index eaae41f38b6e..8a077a281e3d 100644
--- a/products/customer_analytics/backend/migrations/max_migration.txt
+++ b/products/customer_analytics/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0046_usercustomeranalyticsconfig
+0049_validate_customer_task_foreign_keys
diff --git a/products/customer_analytics/backend/models/__init__.py b/products/customer_analytics/backend/models/__init__.py
index fb42fe9b7cac..48d839d4be7b 100644
--- a/products/customer_analytics/backend/models/__init__.py
+++ b/products/customer_analytics/backend/models/__init__.py
@@ -17,6 +17,7 @@ from .custom_property_sync_run import CustomPropertySyncRun, SyncStatus, SyncTri
from .custom_property_value import CustomPropertyValue
from .customer_journey import CustomerJourney
from .customer_profile_config import CustomerProfileConfig
+from .customer_task import CustomerTask, CustomerTaskActivity, CustomerTaskActivityType, CustomerTaskStatus
from .event_stream import EventStream, EventStreamMember
from .feature_request import (
FeatureRequest,
@@ -52,6 +53,10 @@ __all__ = [
"CustomPropertySyncRun",
"CustomPropertyValue",
"CustomerJourney",
+ "CustomerTask",
+ "CustomerTaskActivity",
+ "CustomerTaskActivityType",
+ "CustomerTaskStatus",
"CustomerProfileConfig",
"DataType",
"DisplayType",
diff --git a/products/customer_analytics/backend/models/customer_task.py b/products/customer_analytics/backend/models/customer_task.py
new file mode 100644
index 000000000000..903aa18c530a
--- /dev/null
+++ b/products/customer_analytics/backend/models/customer_task.py
@@ -0,0 +1,94 @@
+from django.db import models
+from django.db.models import Q
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import UUIDModel
+
+
+class CustomerTaskStatus(models.TextChoices):
+ OPEN = "open", "Open"
+ IN_PROGRESS = "in_progress", "In progress"
+ COMPLETED = "completed", "Completed"
+ CANCELED = "canceled", "Canceled"
+
+
+class CustomerTaskActivityType(models.TextChoices):
+ CREATED = "created", "Created"
+ UPDATED = "updated", "Updated"
+ ARCHIVED = "archived", "Archived"
+ RESTORED = "restored", "Restored"
+
+
+class CustomerTask(TeamScopedRootMixin, UUIDModel):
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+ account = models.ForeignKey(
+ "customer_analytics.Account",
+ on_delete=models.CASCADE,
+ null=True,
+ blank=True,
+ related_name="customer_tasks",
+ )
+ name = models.CharField(max_length=400)
+ description = models.TextField(null=True, blank=True)
+ properties = models.JSONField(default=dict, db_default={})
+ status = models.CharField(max_length=20, choices=CustomerTaskStatus.choices, default=CustomerTaskStatus.OPEN)
+ assigned_to = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="+",
+ db_constraint=False,
+ db_index=False,
+ )
+ due_at = models.DateTimeField(null=True, blank=True)
+ completed_at = models.DateTimeField(null=True, blank=True)
+ completed_by = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="+",
+ db_constraint=False,
+ db_index=False,
+ )
+ created_by = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="+",
+ db_constraint=False,
+ db_index=False,
+ )
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+ archived_at = models.DateTimeField(null=True, blank=True)
+
+ class Meta:
+ constraints = [
+ models.CheckConstraint(
+ condition=(
+ (Q(status=CustomerTaskStatus.COMPLETED) & Q(completed_at__isnull=False))
+ | (~Q(status=CustomerTaskStatus.COMPLETED) & Q(completed_at__isnull=True))
+ ),
+ name="customer_task_completion_consistency",
+ ),
+ ]
+
+
+class CustomerTaskActivity(TeamScopedRootMixin, UUIDModel):
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+ task = models.ForeignKey(CustomerTask, on_delete=models.CASCADE, related_name="activities")
+ actor = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="+",
+ db_constraint=False,
+ db_index=False,
+ )
+ activity_type = models.CharField(max_length=20, choices=CustomerTaskActivityType.choices)
+ changes = models.JSONField(default=list)
+ created_at = models.DateTimeField(auto_now_add=True)
diff --git a/products/customer_analytics/backend/presentation/views/customer_tasks.py b/products/customer_analytics/backend/presentation/views/customer_tasks.py
new file mode 100644
index 000000000000..f991f2fc21b8
--- /dev/null
+++ b/products/customer_analytics/backend/presentation/views/customer_tasks.py
@@ -0,0 +1,474 @@
+from __future__ import annotations
+
+from functools import cached_property
+from typing import Any, cast
+
+from drf_spectacular.helpers import forced_singular_serializer
+from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field
+from rest_framework import serializers, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import ValidationError
+from rest_framework.pagination import LimitOffsetPagination
+from rest_framework.permissions import BasePermission
+from rest_framework.request import Request
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.models import Team, User
+from posthog.permissions import PostHogFeatureFlagPermission, get_authenticator_scoped_team_ids
+
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+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."
+# 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
+
+_ORDERING_CHOICES = [
+ "name",
+ "-name",
+ "status",
+ "-status",
+ "assigned_to",
+ "-assigned_to",
+ "due_at",
+ "-due_at",
+ "updated_at",
+ "-updated_at",
+ "account",
+ "-account",
+ "created_at",
+ "-created_at",
+]
+
+
+class CustomerTaskUserSerializer(serializers.Serializer):
+ id = serializers.IntegerField(read_only=True, help_text="PostHog user ID.")
+ email = serializers.EmailField(read_only=True, help_text="Email address of the user.")
+ first_name = serializers.CharField(read_only=True, help_text="First name of the user.")
+ last_name = serializers.CharField(read_only=True, help_text="Last name of the user.")
+
+
+class CustomerTaskAccountSerializer(serializers.Serializer):
+ id = serializers.UUIDField(read_only=True, help_text="UUID of the linked account.")
+ name = serializers.CharField(read_only=True, help_text="Name of the linked account.")
+
+
+class CustomerTaskSerializer(serializers.Serializer):
+ id = serializers.UUIDField(read_only=True, help_text="UUID of the task.")
+ account = CustomerTaskAccountSerializer(read_only=True, allow_null=True, help_text="Linked account, if any.")
+ name = serializers.CharField(read_only=True, help_text="Task name.")
+ description = serializers.CharField(read_only=True, allow_null=True, help_text="Task description, if any.")
+ status = serializers.ChoiceField(
+ read_only=True, choices=api.CUSTOMER_TASK_STATUS_CHOICES, help_text="Task lifecycle status."
+ )
+ assigned_to = CustomerTaskUserSerializer(
+ read_only=True, allow_null=True, help_text="Assigned project member, if any."
+ )
+ due_at = serializers.DateTimeField(read_only=True, allow_null=True, help_text="Task deadline, if any.")
+ completed_at = serializers.DateTimeField(
+ read_only=True, allow_null=True, help_text="When the task was completed, if applicable."
+ )
+ completed_by = CustomerTaskUserSerializer(
+ read_only=True, allow_null=True, help_text="User credited with completion, if known."
+ )
+ created_by = CustomerTaskUserSerializer(
+ read_only=True, allow_null=True, help_text="User who created the task, if known."
+ )
+ archived_at = serializers.DateTimeField(read_only=True, allow_null=True, help_text="When the task was archived.")
+ created_at = serializers.DateTimeField(read_only=True, help_text="When the task was created.")
+ updated_at = serializers.DateTimeField(read_only=True, help_text="When the task was last updated.")
+ can_edit = serializers.BooleanField(read_only=True, help_text="Whether the current user can edit this task.")
+ can_restore = serializers.BooleanField(read_only=True, help_text="Whether the current user can restore this task.")
+
+
+class CustomerTaskAssigneeErrorSerializer(serializers.Serializer):
+ assigned_to_id = serializers.CharField(read_only=True, help_text="Why the selected assignee 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."
+ )
+ name = serializers.CharField(max_length=400, error_messages={"blank": "Enter a task name."}, help_text="Task name.")
+ description = serializers.CharField(
+ required=False, allow_null=True, allow_blank=True, help_text="Task description, or null to leave it empty."
+ )
+ assigned_to_id = serializers.IntegerField(
+ required=False, allow_null=True, help_text="PostHog user ID to assign, or null to leave unassigned."
+ )
+ due_at = serializers.DateTimeField(
+ required=False, allow_null=True, help_text="ISO 8601 deadline, or null for no deadline."
+ )
+ status = serializers.ChoiceField(
+ required=False, default="open", choices=api.CUSTOMER_TASK_STATUS_CHOICES, help_text="Initial task status."
+ )
+
+ def validate_name(self, value: str) -> str:
+ value = value.strip()
+ if not value:
+ raise serializers.ValidationError("Enter a task name.")
+ return value
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ unexpected = set(self.initial_data) - set(self.fields)
+ if unexpected:
+ raise serializers.ValidationError(dict.fromkeys(unexpected, "This field is not accepted."))
+ return attrs
+
+
+class CustomerTaskUpdateSerializer(serializers.Serializer):
+ account_id = serializers.UUIDField(
+ required=False, allow_null=True, help_text="UUID of a visible account, or null to remove the account link."
+ )
+ name = serializers.CharField(
+ max_length=400,
+ allow_null=False,
+ error_messages={"blank": "Enter a task name."},
+ help_text="Replacement task name.",
+ )
+ description = serializers.CharField(
+ required=False, allow_null=True, allow_blank=True, help_text="Replacement description, or null to clear it."
+ )
+ assigned_to_id = serializers.IntegerField(
+ required=False, allow_null=True, help_text="Replacement assignee ID, or null to unassign."
+ )
+ due_at = serializers.DateTimeField(
+ required=False, allow_null=True, help_text="Replacement ISO 8601 deadline, or null to clear it."
+ )
+ status = serializers.ChoiceField(
+ required=False,
+ allow_null=False,
+ choices=api.CUSTOMER_TASK_STATUS_CHOICES,
+ help_text="Replacement task status.",
+ )
+
+ def validate_name(self, value: str) -> str:
+ value = value.strip()
+ if not value:
+ raise serializers.ValidationError("Enter a task name.")
+ return value
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ unexpected = set(self.initial_data) - set(self.fields)
+ if unexpected:
+ raise serializers.ValidationError(dict.fromkeys(unexpected, "This field is not accepted."))
+ return attrs
+
+
+@extend_schema_field({"oneOf": [{"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "object"}]})
+class CustomerTaskChangeValueField(serializers.JSONField):
+ pass
+
+
+class CustomerTaskChangeSerializer(serializers.Serializer):
+ field = serializers.CharField(read_only=True, help_text="Semantic task field that changed.")
+ before = CustomerTaskChangeValueField(read_only=True, allow_null=True, help_text="Value before the change.")
+ after = CustomerTaskChangeValueField(read_only=True, allow_null=True, help_text="Value after the change.")
+
+
+class CustomerTaskActivitySerializer(serializers.Serializer):
+ id = serializers.UUIDField(read_only=True, help_text="UUID of the activity.")
+ activity_type = serializers.ChoiceField(
+ read_only=True,
+ choices=api.CUSTOMER_TASK_ACTIVITY_TYPE_CHOICES,
+ help_text="Action that produced the activity.",
+ )
+ changes = CustomerTaskChangeSerializer(
+ many=True, read_only=True, help_text="Semantic field changes in this action."
+ )
+ actor = CustomerTaskUserSerializer(read_only=True, allow_null=True, help_text="User who made the change, if known.")
+ created_at = serializers.DateTimeField(read_only=True, help_text="When the activity was recorded.")
+
+
+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.")
+ statuses = serializers.CharField(required=False, help_text="Comma-separated task statuses.")
+ archive_state = serializers.ChoiceField(
+ required=False,
+ default="active",
+ choices=[("active", "active"), ("archived", "archived"), ("all", "all")],
+ help_text="Which archive state to include.",
+ )
+ due_after = serializers.DateTimeField(required=False, help_text="Inclusive lower deadline bound.")
+ due_before = serializers.DateTimeField(required=False, help_text="Exclusive upper deadline bound.")
+ has_due_at = serializers.BooleanField(required=False, help_text="Filter tasks by whether a deadline exists.")
+ ordering = serializers.ChoiceField(
+ required=False,
+ choices=[(value, value) for value in _ORDERING_CHOICES],
+ help_text="Sort by task name, status, assignee, deadline, last update, account, or creation time. Prefix with - for descending order.",
+ )
+ limit = serializers.IntegerField(
+ required=False, default=50, min_value=1, max_value=100, help_text="Page size, from 1 to 100."
+ )
+ offset = serializers.IntegerField(required=False, default=0, min_value=0, help_text="Number of rows to skip.")
+
+ def validate_assigned_to(self, value: str) -> str:
+ if value in {"me", "unassigned"}:
+ return value
+ # str.isdigit() accepts characters such as "²" that int() rejects.
+ try:
+ member_id = int(value)
+ except ValueError:
+ raise serializers.ValidationError(_ASSIGNED_TO_ERROR) from None
+ if not 1 <= member_id <= _MAX_MEMBER_ID:
+ raise serializers.ValidationError(_ASSIGNED_TO_ERROR)
+ return str(member_id)
+
+ def validate_statuses(self, value: str) -> tuple[str, ...]:
+ values = tuple(part.strip() for part in value.split(","))
+ if not values or any(part not in dict(api.CUSTOMER_TASK_STATUS_CHOICES) for part in values):
+ raise serializers.ValidationError("statuses must contain only open, in_progress, completed, or canceled.")
+ return values
+
+
+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."
+ )
+ offset = serializers.IntegerField(required=False, default=0, min_value=0, help_text="Number of rows to skip.")
+
+
+class CustomerTaskPageSerializer(serializers.Serializer):
+ count = serializers.IntegerField(read_only=True, help_text="Total number of matching tasks.")
+ next = serializers.URLField(read_only=True, allow_null=True, help_text="URL of the next page, if available.")
+ previous = serializers.URLField(
+ read_only=True, allow_null=True, help_text="URL of the previous page, if available."
+ )
+ results = CustomerTaskSerializer(many=True, read_only=True, help_text="Tasks in this page.")
+
+
+class CustomerTaskActivityPageSerializer(serializers.Serializer):
+ count = serializers.IntegerField(read_only=True, help_text="Total number of matching activities.")
+ next = serializers.URLField(read_only=True, allow_null=True, help_text="URL of the next page, if available.")
+ previous = serializers.URLField(
+ read_only=True, allow_null=True, help_text="URL of the previous page, if available."
+ )
+ results = CustomerTaskActivitySerializer(many=True, read_only=True, help_text="Activities in this page.")
+
+
+def _paginated_response(
+ request: Request,
+ page: list[Any],
+ count: int,
+ limit: int,
+ offset: int,
+ serializer_class: type[serializers.Serializer],
+) -> Response:
+ paginator = LimitOffsetPagination()
+ paginator.request = request
+ paginator.limit = limit
+ paginator.offset = offset
+ paginator.count = count
+ return paginator.get_paginated_response(serializer_class(instance=page, many=True).data)
+
+
+class CustomerTaskCanonicalTeamAccessPermission(BasePermission):
+ message = "You don't have access to the project."
+
+ def has_permission(self, request: Request, view: APIView) -> bool:
+ if not request.user.is_authenticated:
+ return True
+ customer_task_view = cast(CustomerTaskViewSet, view)
+ if customer_task_view.canonical_team_id == customer_task_view.team_id:
+ return True
+ scoped_team_ids = get_authenticator_scoped_team_ids(request.successful_authenticator)
+ if scoped_team_ids and customer_task_view.canonical_team_id not in scoped_team_ids:
+ return False
+ membership_level = customer_task_view.user_permissions.team(
+ customer_task_view.canonical_team
+ ).effective_membership_level
+ return membership_level is not None
+
+
+class CustomerTaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ scope_object = "customer_task"
+ serializer_class = CustomerTaskSerializer
+ queryset = None
+ pagination_class = None
+ posthog_feature_flag = CUSTOMER_ANALYTICS_CUSTOMER_TASKS_FLAG
+ scope_object_read_actions = ["list", "retrieve", "activities"]
+ scope_object_write_actions = ["create", "update", "partial_update", "archive", "restore"]
+ permission_classes = [CustomerTaskCanonicalTeamAccessPermission, PostHogFeatureFlagPermission]
+
+ @cached_property
+ def canonical_team_id(self) -> int:
+ return self.team.parent_team_id or self.team.id
+
+ @cached_property
+ def canonical_team(self) -> Team:
+ if self.canonical_team_id == self.team.id:
+ return self.team
+ parent_team = self.team.parent_team
+ assert parent_team is not None
+ return parent_team
+
+ @cached_property
+ def user_access_control(self) -> UserAccessControl:
+ return UserAccessControl(
+ user=cast(User, self.request.user),
+ team=self.canonical_team,
+ organization_id=self.organization_id,
+ )
+
+ @validated_request(
+ query_serializer=CustomerTaskListQuerySerializer,
+ responses={200: OpenApiResponse(response=forced_singular_serializer(CustomerTaskPageSerializer))},
+ )
+ def list(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
+ data = request.validated_query_data
+ 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"),
+ statuses=data.get("statuses", ()),
+ archive_state=data["archive_state"],
+ due_after=data.get("due_after"),
+ due_before=data.get("due_before"),
+ has_due_at=data.get("has_due_at") if "has_due_at" in request.query_params else None,
+ ordering=data.get("ordering"),
+ ),
+ offset=data["offset"],
+ limit=data["limit"],
+ )
+ return _paginated_response(request, page, count, data["limit"], data["offset"], CustomerTaskSerializer)
+
+ @extend_schema(responses={200: CustomerTaskSerializer, 404: OpenApiResponse(description="Task not found.")})
+ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ task = api.get_customer_task(
+ team_id=self.canonical_team_id,
+ task_id=self.kwargs["pk"],
+ user_access_control=self.user_access_control,
+ )
+ if task is None:
+ return Response({"detail": "Task not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(CustomerTaskSerializer(instance=task).data)
+
+ @extend_schema(request=CustomerTaskCreateSerializer, responses={201: CustomerTaskSerializer})
+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ serializer = CustomerTaskCreateSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ task = api.create_customer_task(
+ team=self.canonical_team,
+ input=contracts.CreateCustomerTaskInput(**serializer.validated_data),
+ actor=cast(User, request.user),
+ user_access_control=self.user_access_control,
+ )
+ return Response(CustomerTaskSerializer(instance=task).data, status=status.HTTP_201_CREATED)
+
+ def _update_customer_task(self, request: Request, *, partial: bool) -> Response:
+ serializer = CustomerTaskUpdateSerializer(data=request.data, partial=partial)
+ serializer.is_valid(raise_exception=True)
+ if partial and not request.data:
+ raise ValidationError({"detail": "Change at least one task field."})
+ data = serializer.validated_data
+ task = api.update_customer_task(
+ team=self.canonical_team,
+ task_id=self.kwargs["pk"],
+ input=contracts.UpdateCustomerTaskInput(
+ **data,
+ account_id_provided="account_id" in request.data,
+ name_provided="name" in request.data,
+ description_provided="description" in request.data,
+ assigned_to_id_provided="assigned_to_id" in request.data,
+ due_at_provided="due_at" in request.data,
+ status_provided="status" in request.data,
+ ),
+ actor=cast(User, request.user),
+ user_access_control=self.user_access_control,
+ )
+ if task is None:
+ return Response({"detail": "Task not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(CustomerTaskSerializer(instance=task).data)
+
+ @extend_schema(request=CustomerTaskUpdateSerializer, responses={200: CustomerTaskSerializer})
+ def partial_update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ return self._update_customer_task(request, partial=True)
+
+ @extend_schema(request=CustomerTaskUpdateSerializer, responses={200: CustomerTaskSerializer})
+ def update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ return self._update_customer_task(request, partial=False)
+
+ @extend_schema(request=None, responses={200: CustomerTaskSerializer})
+ @action(detail=True, methods=["post"])
+ def archive(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ task = api.archive_customer_task(
+ team_id=self.canonical_team_id,
+ task_id=self.kwargs["pk"],
+ actor=cast(User, request.user),
+ user_access_control=self.user_access_control,
+ )
+ if task is None:
+ return Response({"detail": "Task not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(CustomerTaskSerializer(instance=task).data)
+
+ @extend_schema(request=None, responses={200: CustomerTaskSerializer})
+ @action(detail=True, methods=["post"])
+ def restore(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ task = api.restore_customer_task(
+ team_id=self.canonical_team_id,
+ task_id=self.kwargs["pk"],
+ actor=cast(User, request.user),
+ user_access_control=self.user_access_control,
+ )
+ if task is None:
+ return Response({"detail": "Task not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(CustomerTaskSerializer(instance=task).data)
+
+ @extend_schema(
+ operation_id="customerTasksActivitiesList",
+ parameters=[CustomerTaskActivityQuerySerializer],
+ responses={200: OpenApiResponse(response=CustomerTaskActivityPageSerializer)},
+ )
+ @action(detail=True, methods=["get"])
+ @validated_request(query_serializer=CustomerTaskActivityQuerySerializer)
+ def activities(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
+ data = request.validated_query_data
+ result = api.list_customer_task_activities(
+ team_id=self.canonical_team_id,
+ task_id=self.kwargs["pk"],
+ user_access_control=self.user_access_control,
+ offset=data["offset"],
+ limit=data["limit"],
+ )
+ if result is None:
+ return Response({"detail": "Task not found."}, status=status.HTTP_404_NOT_FOUND)
+ page, count = result
+ return _paginated_response(request, page, count, data["limit"], data["offset"], CustomerTaskActivitySerializer)
+
+ def handle_exception(self, exc: Exception) -> Response:
+ if isinstance(exc, contracts.CustomerTaskAccountNotFound):
+ return Response({"detail": "Account not found."}, status=status.HTTP_404_NOT_FOUND)
+ if isinstance(exc, contracts.CustomerTaskAssigneeInvalid):
+ error = CustomerTaskAssigneeErrorSerializer(instance={"assigned_to_id": "Select a member of this project."})
+ return Response(error.data, status=status.HTTP_400_BAD_REQUEST)
+ if isinstance(exc, contracts.CustomerTaskAssigneeCannotViewAccount):
+ error = CustomerTaskAssigneeErrorSerializer(
+ instance={
+ "assigned_to_id": "This person can"
+ + chr(39)
+ + "t access the selected account. Choose another assignee or remove the account link."
+ }
+ )
+ return Response(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}."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ if isinstance(exc, contracts.CustomerTaskAccessDenied):
+ return Response(
+ {"detail": "You do not have editor access to this customer task."}, status=status.HTTP_403_FORBIDDEN
+ )
+ if isinstance(exc, contracts.CustomerTaskArchived):
+ return Response({"detail": "Restore this task before editing it."}, status=status.HTTP_409_CONFLICT)
+ return super().handle_exception(exc)
diff --git a/products/customer_analytics/backend/routes.py b/products/customer_analytics/backend/routes.py
index f0cdbfcbc918..6feff06c5b7e 100644
--- a/products/customer_analytics/backend/routes.py
+++ b/products/customer_analytics/backend/routes.py
@@ -2,6 +2,7 @@ from posthog.api.routing import RouterRegistry
from products.customer_analytics.backend.presentation.views.accounts_table_query import AccountsTableQueryViewSet
from products.customer_analytics.backend.presentation.views.announcements import AnnouncementViewSet
+from products.customer_analytics.backend.presentation.views.customer_tasks import CustomerTaskViewSet
from products.customer_analytics.backend.presentation.views.organization_members import (
OrganizationMembersForAccountViewSet,
)
@@ -120,3 +121,4 @@ def register_routes(routers: RouterRegistry) -> None:
"project_account_relationships",
["team_id", "account_id"],
)
+ routers.projects.register(r"customer_tasks", CustomerTaskViewSet, "project_customer_tasks", ["team_id"])
diff --git a/products/customer_analytics/backend/test/test_customer_tasks.py b/products/customer_analytics/backend/test/test_customer_tasks.py
new file mode 100644
index 000000000000..7236ad654def
--- /dev/null
+++ b/products/customer_analytics/backend/test/test_customer_tasks.py
@@ -0,0 +1,830 @@
+from datetime import UTC, datetime
+from uuid import UUID
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+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.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.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 (
+ CustomerTaskActivityQuerySerializer,
+ CustomerTaskCreateSerializer,
+ CustomerTaskListQuerySerializer,
+ CustomerTaskUpdateSerializer,
+)
+
+
+class CustomerTaskSerializerTest(SimpleTestCase):
+ def test_public_writes_reject_internal_properties_and_blank_names(self) -> None:
+ create_serializer = CustomerTaskCreateSerializer(data={"name": " "})
+ assert not create_serializer.is_valid()
+ assert create_serializer.errors["name"][0] == "Enter a task name."
+
+ properties_serializer = CustomerTaskCreateSerializer(data={"name": "Task", "properties": {"source": "sync"}})
+ assert not properties_serializer.is_valid()
+ assert "properties" in properties_serializer.errors
+
+ update_serializer = CustomerTaskUpdateSerializer(data={"properties": {"source": "sync"}}, partial=True)
+ assert not update_serializer.is_valid()
+ assert "properties" in update_serializer.errors
+
+ @parameterized.expand(
+ [
+ # str.isdigit() accepts this one, but the filter's int() cast does not.
+ ("a superscript digit", "²", None),
+ ("an unparseable name", "someone", None),
+ ("a zero id", "0", None),
+ ("an id past int4", "99999999999999999999", None),
+ ("a member id", "7", "7"),
+ ("a non-decimal digit", "٢", "2"),
+ ("the me shorthand", "me", "me"),
+ ]
+ )
+ def test_assigned_to_filter_only_accepts_a_usable_member_id(
+ self, _name: str, value: str, expected: str | None
+ ) -> None:
+ serializer = CustomerTaskListQuerySerializer(data={"assigned_to": value})
+
+ if expected is None:
+ assert not serializer.is_valid()
+ assert "assigned_to" in serializer.errors
+ return
+ assert serializer.is_valid(), serializer.errors
+ assert serializer.validated_data["assigned_to"] == expected
+
+ @parameterized.expand(
+ [
+ ("list", CustomerTaskListQuerySerializer),
+ ("activities", CustomerTaskActivityQuerySerializer),
+ ]
+ )
+ def test_page_limit_rejects_zero(self, _name: str, serializer_class: type[serializers.Serializer]) -> None:
+ # A zero limit would leave the paginator's next link pointing at the same offset.
+ zero_limit = serializer_class(data={"limit": 0})
+ assert not zero_limit.is_valid()
+ assert "limit" in zero_limit.errors
+
+ smallest_limit = serializer_class(data={"limit": 1})
+ assert smallest_limit.is_valid(), smallest_limit.errors
+ assert smallest_limit.validated_data["limit"] == 1
+
+
+class CustomerTaskAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.available_product_features = [
+ {"name": AvailableFeature.ACCESS_CONTROL, "key": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save(update_fields=["available_product_features"])
+ self.url = f"/api/projects/{self.team.id}/customer_tasks/"
+ self.flag_patcher = patch("posthog.permissions.posthog_feature_flag_enabled", return_value=True)
+ self.flag_patcher.start()
+ self.addCleanup(self.flag_patcher.stop)
+
+ def test_accountless_create_omits_properties_and_records_activity(self) -> None:
+ response = self.client.post(self.url, {"name": "Follow up", "description": None}, format="json")
+
+ assert response.status_code == status.HTTP_201_CREATED
+ assert response.json()["account"] is None
+ assert "properties" not in response.json()
+ task = CustomerTask.objects.unscoped().get(id=response.json()["id"])
+ activities_response = self.client.get(f"{self.url}{task.id}/activities/?limit=1&offset=0")
+ assert activities_response.status_code == status.HTTP_200_OK
+ assert activities_response.json()["count"] == 1
+ result = activities_response.json()["results"][0]
+ assert result["activity_type"] == "created"
+ name_change = next(change for change in result["changes"] if change["field"] == "name")
+ assert name_change == {"field": "name", "before": None, "after": "Follow up"}
+ activity = CustomerTaskActivity.objects.unscoped().get(task=task)
+ assert activity.activity_type == "created"
+
+ def test_put_requires_name_while_patch_accepts_partial_fields(self) -> None:
+ created = self.client.post(self.url, {"name": "Original task"}, format="json")
+ task_url = f"{self.url}{created.json()['id']}/"
+
+ put_response = self.client.put(task_url, {"description": "PUT description"}, format="json")
+ patch_response = self.client.patch(task_url, {"description": "PATCH description"}, format="json")
+
+ assert put_response.status_code == status.HTTP_400_BAD_REQUEST
+ assert put_response.json()["attr"] == "name"
+ assert patch_response.status_code == status.HTTP_200_OK
+ assert patch_response.json()["description"] == "PATCH description"
+
+ def test_noop_status_completion_archive_and_restore_lifecycle(self) -> None:
+ created = self.client.post(self.url, {"name": "Follow up"}, format="json")
+ task_id = created.json()["id"]
+ activity_count = CustomerTaskActivity.objects.unscoped().filter(task_id=task_id).count()
+ updated_at_before = CustomerTask.objects.unscoped().get(id=task_id).updated_at
+
+ noop = self.client.patch(f"{self.url}{task_id}/", {"name": "Follow up"}, format="json")
+ assert noop.status_code == status.HTTP_200_OK
+ assert CustomerTaskActivity.objects.unscoped().filter(task_id=task_id).count() == activity_count
+ assert CustomerTask.objects.unscoped().get(id=task_id).updated_at == updated_at_before
+
+ empty = self.client.patch(f"{self.url}{task_id}/", {}, format="json")
+ assert empty.status_code == status.HTTP_400_BAD_REQUEST
+ assert empty.json()["detail"] == "Change at least one task field."
+ completed = self.client.patch(f"{self.url}{task_id}/", {"status": "completed"}, format="json")
+ assert completed.status_code == status.HTTP_200_OK
+ assert completed.json()["completed_at"] is not None
+ assert completed.json()["completed_by"]["id"] == self.user.id
+
+ invalid_transition = self.client.patch(f"{self.url}{task_id}/", {"status": "canceled"}, format="json")
+ assert invalid_transition.status_code == status.HTTP_400_BAD_REQUEST
+ assert invalid_transition.json()["status"] == "This task can't move from completed to canceled."
+ archived = self.client.post(f"{self.url}{task_id}/archive/", {}, format="json")
+ activities_before_repeat = CustomerTaskActivity.objects.unscoped().filter(task_id=task_id).count()
+ repeated_archive = self.client.post(f"{self.url}{task_id}/archive/", {}, format="json")
+ assert repeated_archive.status_code == status.HTTP_200_OK
+ assert CustomerTaskActivity.objects.unscoped().filter(task_id=task_id).count() == activities_before_repeat
+ assert archived.status_code == status.HTTP_200_OK
+ blocked = self.client.patch(f"{self.url}{task_id}/", {"name": "Changed"}, format="json")
+ assert blocked.status_code == status.HTTP_409_CONFLICT
+ assert blocked.json()["detail"] == "Restore this task before editing it."
+
+ restored = self.client.post(f"{self.url}{task_id}/restore/", {}, format="json")
+ assert restored.status_code == status.HTTP_200_OK
+ assert restored.json()["archived_at"] is None
+ reopened = self.client.patch(f"{self.url}{task_id}/", {"status": "open"}, format="json")
+ assert reopened.status_code == status.HTTP_200_OK
+ assert reopened.json()["completed_at"] is None
+ canceled = self.client.patch(f"{self.url}{task_id}/", {"status": "canceled"}, format="json")
+ assert canceled.status_code == status.HTTP_200_OK
+ assert (
+ self.client.patch(f"{self.url}{task_id}/", {"status": "open"}, format="json").status_code
+ == status.HTTP_200_OK
+ )
+
+ def test_customer_tasks_do_not_expose_object_access_control_actions(self) -> None:
+ created = self.client.post(self.url, {"name": "Restricted task"}, format="json")
+ task_id = created.json()["id"]
+
+ response = self.client.put(
+ f"{self.url}{task_id}/access_controls/",
+ {"organization_member": str(self.organization_membership.id), "access_level": "none"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_feature_flag_denies_customer_tasks(self) -> None:
+ with patch("posthog.permissions.posthog_feature_flag_enabled", return_value=False):
+ response = self.client.get(self.url)
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_scopes_allow_reads_and_require_write_for_mutations(self) -> None:
+ created = self.client.post(self.url, {"name": "Scoped task"}, format="json")
+ task_id = created.json()["id"]
+
+ read_key = self.create_personal_api_key_with_scopes(["customer_task:read"])
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {read_key}")
+ assert self.client.get(f"{self.url}{task_id}/").status_code == status.HTTP_200_OK
+ assert (
+ self.client.patch(f"{self.url}{task_id}/", {"name": "Denied"}, format="json").status_code
+ == status.HTTP_403_FORBIDDEN
+ )
+
+ write_key = self.create_personal_api_key_with_scopes(["customer_task:write"])
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {write_key}")
+ assert (
+ self.client.patch(f"{self.url}{task_id}/", {"name": "Updated"}, format="json").status_code
+ == status.HTTP_200_OK
+ )
+
+ def test_child_only_member_cannot_access_parent_tasks(self) -> None:
+ environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="Environment")
+ member = User.objects.create_and_join(self.organization, "[email protected]", "testpassword")
+ membership = OrganizationMembership.objects.get(user=member, organization=self.organization)
+ AccessControl.objects.create(
+ team=self.team,
+ resource="project",
+ resource_id=str(self.team.id),
+ access_level="none",
+ organization_member=membership,
+ )
+ AccessControl.objects.create(
+ team=environment,
+ resource="project",
+ resource_id=str(environment.id),
+ access_level="member",
+ organization_member=membership,
+ )
+ CustomerTask.objects.for_team(self.team.id).create(team=self.team, name="Parent task")
+ self.client.force_login(member)
+
+ response = self.client.get(f"/api/projects/{environment.id}/customer_tasks/")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_child_scoped_api_key_cannot_access_parent_tasks(self) -> None:
+ environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="Environment")
+ CustomerTask.objects.for_team(self.team.id).create(team=self.team, name="Parent task")
+ key_value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="Child-scoped key",
+ user=self.user,
+ secure_value=hash_key_value(key_value),
+ scopes=["customer_task:read"],
+ scoped_teams=[environment.id],
+ )
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {key_value}")
+
+ response = self.client.get(f"/api/projects/{environment.id}/customer_tasks/")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_child_customer_task_access_does_not_grant_parent_task_access(self) -> None:
+ environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="Environment")
+ member = User.objects.create_and_join(self.organization, "[email protected]", "testpassword")
+ membership = OrganizationMembership.objects.get(user=member, organization=self.organization)
+ AccessControl.objects.create(
+ team=self.team,
+ resource="customer_analytics",
+ resource_id=None,
+ access_level="none",
+ organization_member=membership,
+ )
+ AccessControl.objects.create(
+ team=environment,
+ resource="customer_analytics",
+ resource_id=None,
+ access_level="editor",
+ organization_member=membership,
+ )
+ self.client.force_login(member)
+
+ response = self.client.post(
+ f"/api/projects/{environment.id}/customer_tasks/",
+ {"name": "Parent task"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert not CustomerTask.objects.for_team(self.team.id).exists()
+
+ def test_assignee_can_only_read_and_update_assigned_tasks_and_loses_access_on_reassignment(self) -> None:
+ assignee = User.objects.create_and_join(self.organization, "[email protected]", "testpassword")
+ other_assignee = User.objects.create_and_join(self.organization, "[email protected]", "testpassword")
+ assignee_membership = OrganizationMembership.objects.get(user=assignee, organization=self.organization)
+ AccessControl.objects.create(
+ team=self.team,
+ resource="customer_analytics",
+ resource_id=None,
+ access_level="none",
+ organization_member=assignee_membership,
+ )
+ assigned = self.client.post(
+ self.url,
+ {"name": "Assigned", "assigned_to_id": assignee.id},
+ format="json",
+ )
+ unassigned = self.client.post(self.url, {"name": "Unassigned"}, format="json")
+ assigned_id = assigned.json()["id"]
+ assert AccessControl.objects.filter(
+ team=self.team,
+ resource="customer_task",
+ resource_id=assigned_id,
+ organization_member=assignee_membership,
+ access_level="editor",
+ ).exists()
+
+ self.client.force_login(assignee)
+ listed_tasks = self.client.get(self.url).json()["results"]
+ assert assigned_id in {task["id"] for task in listed_tasks}
+ assert unassigned.json()["id"] not in {task["id"] for task in listed_tasks}
+ assert all(task["assigned_to"]["id"] == assignee.id for task in listed_tasks)
+ assert self.client.get(f"{self.url}{unassigned.json()['id']}/").status_code == status.HTTP_404_NOT_FOUND
+ assert (
+ self.client.patch(f"{self.url}{assigned_id}/", {"name": "Changed"}, format="json").status_code
+ == status.HTTP_200_OK
+ )
+
+ reassigned = self.client.patch(
+ f"{self.url}{assigned_id}/",
+ {"assigned_to_id": other_assignee.id},
+ format="json",
+ )
+ assert reassigned.status_code == status.HTTP_200_OK
+ assert reassigned.json()["can_edit"] is False
+ assert not AccessControl.objects.filter(
+ team=self.team,
+ resource="customer_task",
+ resource_id=assigned_id,
+ organization_member=assignee_membership,
+ ).exists()
+ other_membership = OrganizationMembership.objects.get(user=other_assignee, organization=self.organization)
+ assert AccessControl.objects.filter(
+ team=self.team,
+ resource="customer_task",
+ resource_id=assigned_id,
+ organization_member=other_membership,
+ access_level="editor",
+ ).exists()
+ assert self.client.get(f"{self.url}{assigned_id}/").status_code == status.HTTP_403_FORBIDDEN
+
+ def test_assignee_cannot_cross_account_visibility(self) -> None:
+ assignee = User.objects.create_and_join(self.organization, "[email protected]", "testpassword")
+ account = Account.objects.unscoped().create(team=self.team, name="Hidden account")
+ created = self.client.post(
+ self.url,
+ {"name": "Account task", "account_id": str(account.id), "assigned_to_id": assignee.id},
+ format="json",
+ )
+ membership = OrganizationMembership.objects.get(user=assignee, organization=self.organization)
+ AccessControl.objects.create(
+ team=self.team,
+ resource="account",
+ resource_id=str(account.id),
+ access_level="none",
+ organization_member=membership,
+ )
+
+ self.client.force_login(assignee)
+ assert self.client.get(self.url).json()["results"] == []
+ assert self.client.get(f"{self.url}{created.json()['id']}/").status_code == status.HTTP_404_NOT_FOUND
+
+ def test_activities_redact_inaccessible_and_malformed_historical_accounts(self) -> None:
+ viewer = User.objects.create_and_join(self.organization, "[email protected]", "testpassword")
+ membership = OrganizationMembership.objects.get(user=viewer, organization=self.organization)
+ visible_account = Account.objects.unscoped().create(team=self.team, name="Visible account")
+ context_only_visible_account = Account.objects.unscoped().create(team=self.team, name="Context account")
+ hidden_account = Account.objects.unscoped().create(team=self.team, name="Hidden account")
+ AccessControl.objects.create(
+ team=self.team,
+ resource="account",
+ resource_id=str(hidden_account.id),
+ access_level="none",
+ organization_member=membership,
+ )
+ task = CustomerTask.objects.for_team(self.team.id).create(team=self.team, name="Account history")
+ stored_changes = [
+ {
+ "field": "account",
+ "before": {"id": str(hidden_account.id), "name": hidden_account.name},
+ "after": {"id": str(visible_account.id), "name": visible_account.name},
+ },
+ {
+ "field": "account",
+ "before": {"id": "not-an-account-id", "name": "Malformed account"},
+ "after": ["malformed"],
+ },
+ {
+ "field": "name",
+ "before": "Hidden before",
+ "after": "Hidden after",
+ "before_account_id": str(hidden_account.id),
+ "after_account_id": str(hidden_account.id),
+ },
+ {
+ "field": "description",
+ "before": "Visible before",
+ "after": "Visible after",
+ "before_account_id": str(context_only_visible_account.id),
+ "after_account_id": str(context_only_visible_account.id),
+ },
+ {
+ "field": "status",
+ "before": "open",
+ "after": "in_progress",
+ "before_account_id": None,
+ "after_account_id": None,
+ },
+ ]
+ activity = CustomerTaskActivity.objects.for_team(self.team.id).create(
+ team=self.team,
+ task=task,
+ actor=self.user,
+ activity_type="updated",
+ changes=stored_changes,
+ )
+ self.client.force_login(viewer)
+
+ response = self.client.get(f"{self.url}{task.id}/activities/")
+
+ assert response.status_code == status.HTTP_200_OK
+ changes = response.json()["results"][0]["changes"]
+ assert changes[0] == {
+ "field": "account",
+ "before": {"id": None, "name": "Restricted account"},
+ "after": {"id": str(visible_account.id), "name": visible_account.name},
+ }
+ assert changes[1] == {
+ "field": "account",
+ "before": {"id": None, "name": "Restricted account"},
+ "after": {"id": None, "name": "Restricted account"},
+ }
+ assert changes[2] == {"field": "name", "before": None, "after": None}
+ assert changes[3] == {
+ "field": "description",
+ "before": "Visible before",
+ "after": "Visible after",
+ }
+ assert changes[4] == {"field": "status", "before": "open", "after": "in_progress"}
+ activity.refresh_from_db()
+ assert activity.changes == stored_changes
+
+ def test_cross_team_tasks_are_not_listed(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="Other project")
+ CustomerTask.objects.unscoped().create(team=other_team, name="Other team task")
+
+ response = self.client.get(self.url)
+
+ assert response.status_code == status.HTTP_200_OK
+ assert all(task["name"] != "Other team task" for task in response.json()["results"])
+
+ def test_archived_tasks_are_retrievable_but_not_active_or_editable(self) -> None:
+ created = self.client.post(self.url, {"name": "Archived task"}, format="json")
+ task_id = created.json()["id"]
+ assert created.json()["can_edit"] is True
+ assert created.json()["can_restore"] is False
+
+ archived = self.client.post(f"{self.url}{task_id}/archive/", {}, format="json")
+ assert archived.status_code == status.HTTP_200_OK
+ assert archived.json()["can_edit"] is False
+ assert archived.json()["can_restore"] is True
+
+ assert self.client.get(f"{self.url}{task_id}/").status_code == status.HTTP_200_OK
+ assert all(task["id"] != task_id for task in self.client.get(self.url).json()["results"])
+ assert self.client.get(f"{self.url}?archive_state=archived").json()["results"][0]["id"] == task_id
+ assert (
+ self.client.patch(f"{self.url}{task_id}/", {"name": "No edit"}, format="json").status_code
+ == status.HTTP_409_CONFLICT
+ )
+
+ viewer = User.objects.create_and_join(self.organization, "[email protected]", "testpassword")
+ viewer_membership = OrganizationMembership.objects.get(user=viewer, organization=self.organization)
+ AccessControl.objects.create(
+ team=self.team,
+ resource="customer_analytics",
+ resource_id=None,
+ access_level="viewer",
+ organization_member=viewer_membership,
+ )
+ self.client.force_login(viewer)
+ viewer_response = self.client.get(f"{self.url}{task_id}/")
+ assert viewer_response.status_code == status.HTTP_200_OK
+ assert viewer_response.json()["can_edit"] is False
+ assert viewer_response.json()["can_restore"] is False
+
+ def _create_filtering_dataset(self) -> tuple[Account, User]:
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save(update_fields=["level"])
+ alpha_account = Account.objects.for_team(self.team.id).create(
+ team=self.team, name="Alpha account", created_by=self.user
+ )
+ beta_account = Account.objects.for_team(self.team.id).create(
+ team=self.team, name="Beta account", created_by=self.user
+ )
+ other_assignee = User.objects.create_and_join(self.organization, "[email protected]", "testpassword")
+ timestamp = {day: datetime(2026, 1, day, tzinfo=UTC) for day in range(1, 6)}
+ self._create_ordering_task(
+ identifier=10,
+ name="Alpha",
+ description="Contains the search needle",
+ status_value="open",
+ account=alpha_account,
+ assigned_to=self.user,
+ due_at=timestamp[3],
+ created_at=timestamp[1],
+ updated_at=timestamp[1],
+ )
+ self._create_ordering_task(
+ identifier=11,
+ name="Bravo",
+ status_value="in_progress",
+ account=alpha_account,
+ assigned_to=other_assignee,
+ due_at=timestamp[1],
+ created_at=timestamp[2],
+ updated_at=timestamp[2],
+ )
+ self._create_ordering_task(
+ identifier=12,
+ name="Charlie",
+ status_value="completed",
+ account=beta_account,
+ assigned_to=None,
+ due_at=None,
+ created_at=timestamp[3],
+ updated_at=timestamp[3],
+ )
+ self._create_ordering_task(
+ identifier=13,
+ name="Delta",
+ status_value="canceled",
+ account=beta_account,
+ assigned_to=other_assignee,
+ due_at=timestamp[2],
+ created_at=timestamp[4],
+ updated_at=timestamp[4],
+ )
+ archived = self._create_ordering_task(
+ identifier=14,
+ name="Archived",
+ status_value="canceled",
+ account=beta_account,
+ assigned_to=other_assignee,
+ due_at=timestamp[4],
+ created_at=timestamp[5],
+ updated_at=timestamp[5],
+ )
+ CustomerTask.objects.for_team(self.team.id).filter(id=archived.id).update(archived_at=timestamp[5])
+ return alpha_account, other_assignee
+
+ @parameterized.expand(
+ [
+ ("search", "search", "needle", ("Alpha",)),
+ ("account", "account_id", "alpha_account", ("Alpha", "Bravo")),
+ ("status", "statuses", "canceled", ("Delta",)),
+ ]
+ )
+ def test_list_applies_scalar_filters(
+ self, _name: str, parameter: str, value: str, expected_names: tuple[str, ...]
+ ) -> None:
+ alpha_account, _ = self._create_filtering_dataset()
+ query_value = str(alpha_account.id) if value == "alpha_account" else value
+
+ response = self.client.get(self.url, {parameter: query_value})
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["count"] == len(expected_names)
+ assert {task["name"] for task in response.json()["results"]} == set(expected_names)
+
+ @parameterized.expand(
+ [
+ ("me", "me", ("Alpha",)),
+ ("unassigned", "unassigned", ("Charlie",)),
+ ("member_id", "member_id", ("Bravo", "Delta")),
+ ]
+ )
+ def test_list_applies_assignee_filters(self, _name: str, assigned_to: str, expected_names: tuple[str, ...]) -> None:
+ _, other_assignee = self._create_filtering_dataset()
+ query_value = str(other_assignee.id) if assigned_to == "member_id" else assigned_to
+
+ response = self.client.get(self.url, {"assigned_to": query_value})
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["count"] == len(expected_names)
+ assert {task["name"] for task in response.json()["results"]} == set(expected_names)
+
+ @parameterized.expand(
+ [
+ ("due_after", "due_after", "2026-01-02T00:00:00Z", ("Alpha", "Delta")),
+ ("due_before", "due_before", "2026-01-02T00:00:00Z", ("Bravo",)),
+ ("without_due_at", "has_due_at", "false", ("Charlie",)),
+ ]
+ )
+ def test_list_applies_due_filters(
+ self, _name: str, parameter: str, value: str, expected_names: tuple[str, ...]
+ ) -> None:
+ self._create_filtering_dataset()
+
+ response = self.client.get(self.url, {parameter: value})
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["count"] == len(expected_names)
+ assert {task["name"] for task in response.json()["results"]} == set(expected_names)
+
+ def test_list_archive_state_all_includes_active_and_archived_tasks(self) -> None:
+ self._create_filtering_dataset()
+
+ response = self.client.get(self.url, {"archive_state": "all"})
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["count"] == 5
+ assert {task["name"] for task in response.json()["results"]} == {
+ "Alpha",
+ "Archived",
+ "Bravo",
+ "Charlie",
+ "Delta",
+ }
+
+ def test_list_applies_ordering_limit_and_offset(self) -> None:
+ self._create_filtering_dataset()
+
+ response = self.client.get(self.url, {"ordering": "-name", "limit": "2", "offset": "1"})
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["count"] == 4
+ assert [task["name"] for task in response.json()["results"]] == ["Charlie", "Bravo"]
+
+ @parameterized.expand(
+ [
+ ("list",),
+ ("activities",),
+ ]
+ )
+ def test_page_limit_below_one_is_rejected(self, endpoint: str) -> None:
+ created = self.client.post(self.url, {"name": "Paged task"}, format="json")
+ url = self.url if endpoint == "list" else f"{self.url}{created.json()['id']}/activities/"
+
+ response = self.client.get(url, {"limit": "0"})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def _create_ordering_task(
+ self,
+ *,
+ identifier: int,
+ name: str,
+ status_value: str,
+ account: Account | None,
+ assigned_to: User | None,
+ due_at: datetime | None,
+ description: str | None = None,
+ created_at: datetime,
+ updated_at: datetime,
+ ) -> CustomerTask:
+ task = CustomerTask.objects.for_team(self.team.id).create(
+ id=UUID(int=identifier),
+ team=self.team,
+ name=name,
+ description=description,
+ status=status_value,
+ account=account,
+ assigned_to=assigned_to,
+ due_at=due_at,
+ completed_at=created_at if status_value == "completed" else None,
+ )
+ CustomerTask.objects.for_team(self.team.id).filter(id=task.id).update(
+ created_at=created_at, updated_at=updated_at
+ )
+ return task
+
+ def _create_ordering_dataset(self) -> None:
+ alpha_account = Account.objects.for_team(self.team.id).create(team=self.team, name="alpha account")
+ bravo_account = Account.objects.for_team(self.team.id).create(team=self.team, name="Bravo account")
+ alice = User.objects.create_and_join(self.organization, "[email protected]", "testpassword")
+ User.objects.filter(id=alice.id).update(first_name="aLiCe", last_name="Able")
+ zoe = User.objects.create_and_join(self.organization, "[email protected]", "testpassword")
+ User.objects.filter(id=zoe.id).update(first_name="ZoE", last_name="Zed")
+ timestamp = {day: datetime(2026, 1, day, tzinfo=UTC) for day in range(1, 5)}
+ self._create_ordering_task(
+ identifier=1,
+ name="bravo",
+ status_value="canceled",
+ account=bravo_account,
+ assigned_to=zoe,
+ due_at=timestamp[2],
+ created_at=timestamp[3],
+ updated_at=timestamp[3],
+ )
+ self._create_ordering_task(
+ identifier=2,
+ name="Alpha",
+ status_value="open",
+ account=alpha_account,
+ assigned_to=alice,
+ due_at=timestamp[1],
+ created_at=timestamp[1],
+ updated_at=timestamp[4],
+ )
+ self._create_ordering_task(
+ identifier=3,
+ name="charlie",
+ status_value="in_progress",
+ account=bravo_account,
+ assigned_to=zoe,
+ due_at=timestamp[2],
+ created_at=timestamp[4],
+ updated_at=timestamp[1],
+ )
+ self._create_ordering_task(
+ identifier=4,
+ name="Delta",
+ status_value="completed",
+ account=None,
+ assigned_to=None,
+ due_at=None,
+ created_at=timestamp[2],
+ updated_at=timestamp[2],
+ )
+
+ @parameterized.expand(
+ [
+ ("name", ("Alpha", "bravo", "charlie", "Delta"), ("Delta", "charlie", "bravo", "Alpha")),
+ ("status", ("Alpha", "charlie", "Delta", "bravo"), ("bravo", "Delta", "charlie", "Alpha")),
+ ("assigned_to", ("Alpha", "bravo", "charlie", "Delta"), ("bravo", "charlie", "Alpha", "Delta")),
+ ("due_at", ("Alpha", "bravo", "charlie", "Delta"), ("bravo", "charlie", "Alpha", "Delta")),
+ ("updated_at", ("charlie", "Delta", "bravo", "Alpha"), ("Alpha", "bravo", "Delta", "charlie")),
+ ("account", ("Alpha", "bravo", "charlie", "Delta"), ("bravo", "charlie", "Alpha", "Delta")),
+ ("created_at", ("Alpha", "Delta", "bravo", "charlie"), ("charlie", "bravo", "Delta", "Alpha")),
+ ]
+ )
+ def test_logic_orders_task_columns(
+ self, ordering: str, ascending: tuple[str, ...], descending: tuple[str, ...]
+ ) -> None:
+ self._create_ordering_dataset()
+
+ ascending_tasks = customer_tasks._apply_ordering(CustomerTask.objects.for_team(self.team.id), ordering)
+ descending_tasks = customer_tasks._apply_ordering(CustomerTask.objects.for_team(self.team.id), f"-{ordering}")
+
+ assert list(ascending_tasks.values_list("name", flat=True)) == list(ascending)
+ assert list(descending_tasks.values_list("name", flat=True)) == list(descending)
+
+ @parameterized.expand(
+ [
+ ("name",),
+ ("-name",),
+ ("status",),
+ ("-status",),
+ ("assigned_to",),
+ ("-assigned_to",),
+ ("due_at",),
+ ("-due_at",),
+ ("updated_at",),
+ ("-updated_at",),
+ ("account",),
+ ("-account",),
+ ("created_at",),
+ ("-created_at",),
+ ]
+ )
+ def test_logic_ordering_uses_id_tie_breaker(self, ordering: str) -> None:
+ timestamp = datetime(2026, 1, 1, tzinfo=UTC)
+ self._create_ordering_task(
+ identifier=1,
+ name="Task",
+ description="Zulu",
+ status_value="open",
+ account=None,
+ assigned_to=None,
+ due_at=timestamp,
+ created_at=timestamp,
+ updated_at=timestamp,
+ )
+ self._create_ordering_task(
+ identifier=2,
+ name="Task",
+ description="Alpha",
+ status_value="open",
+ account=None,
+ assigned_to=None,
+ due_at=timestamp,
+ created_at=timestamp,
+ updated_at=timestamp,
+ )
+
+ queryset = customer_tasks._apply_ordering(CustomerTask.objects.for_team(self.team.id), ordering)
+
+ assert list(queryset.values_list("description", flat=True)) == ["Zulu", "Alpha"]
+
+ @parameterized.expand(
+ [
+ ("name",),
+ ("-name",),
+ ("status",),
+ ("-status",),
+ ("assigned_to",),
+ ("-assigned_to",),
+ ("due_at",),
+ ("-due_at",),
+ ("updated_at",),
+ ("-updated_at",),
+ ("account",),
+ ("-account",),
+ ("created_at",),
+ ("-created_at",),
+ ]
+ )
+ def test_list_accepts_task_ordering(self, ordering: str) -> None:
+ response = self.client.get(self.url, {"ordering": ordering})
+
+ assert response.status_code == status.HTTP_200_OK
+
+ def test_update_validates_the_final_account_and_assignee_together(self) -> None:
+ assignee = User.objects.create_and_join(self.organization, "[email protected]", "testpassword")
+ account = Account.objects.unscoped().create(team=self.team, name="Final-state account")
+ membership = OrganizationMembership.objects.get(user=assignee, organization=self.organization)
+ AccessControl.objects.create(
+ team=self.team,
+ resource="account",
+ resource_id=str(account.id),
+ access_level="none",
+ organization_member=membership,
+ )
+ created = self.client.post(self.url, {"name": "Final-state task"}, format="json")
+
+ response = self.client.patch(
+ f"{self.url}{created.json()['id']}/",
+ {"account_id": str(account.id), "assigned_to_id": assignee.id},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["assigned_to_id"] == (
+ "This person can't access the selected account. Choose another assignee or remove the account link."
+ )
diff --git a/products/customer_analytics/backend/test/test_facade.py b/products/customer_analytics/backend/test/test_facade.py
index 40b0fe164164..c535b2b787bf 100644
--- a/products/customer_analytics/backend/test/test_facade.py
+++ b/products/customer_analytics/backend/test/test_facade.py
@@ -12,12 +12,13 @@ from django.utils import timezone
from parameterized import parameterized
-from posthog.models import Organization, Team, User
+from posthog.models import Organization, OrganizationMembership, Team, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.tag import Tag
from posthog.models.tagged_item import TaggedItem
from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.access_control.backend.models.access_control import AccessControl
from products.customer_analytics.backend.facade import (
api as facade,
contracts,
@@ -28,6 +29,7 @@ from products.customer_analytics.backend.models import (
Account,
AccountRelationship,
AccountRelationshipDefinition,
+ CustomerTask,
CustomPropertyDefinition,
CustomPropertySource,
CustomPropertyValue,
@@ -492,6 +494,21 @@ class TestCustomerAnalyticsCRUDFacade(BaseTest):
def test_delete_account_removes_row(self):
view = self._create(name="Doomed")
+ task = CustomerTask.objects.for_team(self.team.id).create(
+ team=self.team,
+ account_id=view.id,
+ name="Delete with account",
+ assigned_to=self.user,
+ created_by=self.user,
+ )
+ membership = OrganizationMembership.objects.get(organization=self.organization, user=self.user)
+ AccessControl.objects.create(
+ team=self.team,
+ resource="customer_task",
+ resource_id=str(task.id),
+ access_level="editor",
+ organization_member=membership,
+ )
facade.delete_account_for_view(
team_id=self.team.id,
account_id=str(view.id),
@@ -502,6 +519,7 @@ class TestCustomerAnalyticsCRUDFacade(BaseTest):
was_impersonated=False,
)
assert not Account.objects.unscoped().filter(id=str(view.id)).exists()
+ assert not AccessControl.objects.filter(resource="customer_task", resource_id=str(task.id)).exists()
def test_get_account_for_view_unknown_raises(self):
with self.assertRaises(facade.Account_DoesNotExist):
diff --git a/products/customer_analytics/frontend/CustomerAnalyticsScene.stories.tsx b/products/customer_analytics/frontend/CustomerAnalyticsScene.stories.tsx
index b6ec4ab4acaa..a3fcfa880ae2 100644
--- a/products/customer_analytics/frontend/CustomerAnalyticsScene.stories.tsx
+++ b/products/customer_analytics/frontend/CustomerAnalyticsScene.stories.tsx
@@ -10,6 +10,8 @@ import { mswDecorator, useStorybookMocks } from '~/mocks/browser'
import { useAvailableFeatures } from '~/mocks/features'
import { AvailableFeature } from '~/types'
+import type { CustomerTaskApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+
import { BusinessType, customerAnalyticsSceneLogic } from './customerAnalyticsSceneLogic'
function setBusinessTypeOnMountedLogic(businessType: BusinessType): void {
@@ -98,6 +100,94 @@ export const B2BModeWithoutGroups: Story = {
},
}
+const customerTaskStoryItems: CustomerTaskApi[] = [
+ {
+ id: '018f47de-7e12-7000-8000-000000000041',
+ account: { id: '018f47de-7e12-7000-8000-000000000051', name: 'Acme Inc' },
+ name: 'Review renewal feedback',
+ description:
+ 'Summarize recent feedback, confirm the renewal risks, and prepare the account review notes before the customer meeting next week.',
+ status: 'open',
+ assigned_to: {
+ id: 178,
+ email: '[email protected]',
+ first_name: 'Alex',
+ last_name: 'Morgan',
+ },
+ due_at: '2024-01-12T16:00:00Z',
+ completed_at: null,
+ completed_by: null,
+ created_by: null,
+ archived_at: null,
+ created_at: '2024-01-08T10:00:00Z',
+ updated_at: '2024-01-14T14:30:00Z',
+ can_edit: true,
+ can_restore: false,
+ },
+ {
+ id: '018f47de-7e12-7000-8000-000000000042',
+ account: { id: '018f47de-7e12-7000-8000-000000000052', name: 'Globex' },
+ name: 'Confirm implementation timeline',
+ description: 'Check the rollout dates with the engineering team.',
+ status: 'open',
+ assigned_to: {
+ id: 202,
+ email: '[email protected]',
+ first_name: 'Taylor',
+ last_name: 'Rivera',
+ },
+ due_at: '2024-01-18T11:00:00Z',
+ completed_at: null,
+ completed_by: null,
+ created_by: null,
+ archived_at: null,
+ created_at: '2024-01-09T09:00:00Z',
+ updated_at: '2024-01-13T16:15:00Z',
+ can_edit: true,
+ can_restore: false,
+ },
+ {
+ id: '018f47de-7e12-7000-8000-000000000043',
+ account: null,
+ name: 'Share adoption report',
+ description: null,
+ status: 'open',
+ assigned_to: null,
+ due_at: null,
+ completed_at: null,
+ completed_by: null,
+ created_by: null,
+ archived_at: null,
+ created_at: '2024-01-10T13:00:00Z',
+ updated_at: '2024-01-12T09:45:00Z',
+ can_edit: true,
+ can_restore: false,
+ },
+]
+
+export const CustomerTasks: Story = {
+ render: () => {
+ useStorybookMocks({
+ get: {
+ 'api/projects/:team_id/customer_tasks/': {
+ count: customerTaskStoryItems.length,
+ next: null,
+ previous: null,
+ results: customerTaskStoryItems,
+ },
+ },
+ })
+ return <App />
+ },
+ parameters: {
+ featureFlags: [FEATURE_FLAGS.CUSTOMER_ANALYTICS, FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS],
+ pageUrl: urls.customerAnalyticsTasks(),
+ testOptions: {
+ waitForSelector: '[data-attr="customer-task-name"]',
+ },
+ },
+}
+
const featureRequestStoryItem = {
id: '018f47de-7e12-7000-8000-000000000001',
title: 'Export account-level retention data',
diff --git a/products/customer_analytics/frontend/CustomerAnalyticsScene.test.tsx b/products/customer_analytics/frontend/CustomerAnalyticsScene.test.tsx
new file mode 100644
index 000000000000..64b91c5860c5
--- /dev/null
+++ b/products/customer_analytics/frontend/CustomerAnalyticsScene.test.tsx
@@ -0,0 +1,97 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { Provider } from 'kea'
+import type { ReactNode } from 'react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { sceneLogic } from 'scenes/sceneLogic'
+import { emptySceneParams } from 'scenes/scenes'
+import { Scene } from 'scenes/sceneTypes'
+
+import { initKeaTests } from '~/test/init'
+
+import { CustomerAnalyticsScene } from './CustomerAnalyticsScene'
+import { customerAnalyticsSceneLogic } from './customerAnalyticsSceneLogic'
+
+jest.mock('~/layout/scenes/components/FeaturePreviewSceneGate', () => ({
+ FeaturePreviewSceneGate: ({ children }: { children: ReactNode }) => <>{children}</>,
+}))
+jest.mock('~/layout/scenes/components/SceneContent', () => ({
+ SceneContent: ({ children }: { children: ReactNode }) => <>{children}</>,
+}))
+jest.mock('~/layout/scenes/components/SceneTitleSection', () => ({
+ SceneTitleSection: ({ name, description }: { name: string; description?: string }) => (
+ <>
+ <h1>{name}</h1>
+ {description && <p>{description}</p>}
+ </>
+ ),
+}))
+jest.mock('lib/components/NotFound', () => ({
+ NotFound: () => <div data-attr="page-not-found" />,
+}))
+jest.mock('./CustomerAnalyticsFilters', () => ({ CustomerAnalyticsFilters: () => null }))
+jest.mock('./components/AccountNotes/AccountNotesTabContent', () => ({ AccountNotesTabContent: () => null }))
+jest.mock('./components/Accounts/AccountsTabContent', () => ({ AccountsTabContent: () => null }))
+jest.mock('./components/Announcements/AnnouncementsTabContent', () => ({ AnnouncementsTabContent: () => null }))
+jest.mock('./components/CustomerJourneys/CustomerJourneys', () => ({ CustomerJourneys: () => null }))
+jest.mock('./components/CustomerJourneys/CustomerJourneySelect', () => ({ CustomerJourneySelect: () => null }))
+jest.mock('./components/CustomerJourneys/DeleteJourneyButton', () => ({ DeleteJourneyButton: () => null }))
+jest.mock('./components/CustomerTasks/CustomerTasksInbox', () => ({
+ CustomerTasksInbox: () => <div data-attr="tasks-inbox" />,
+}))
+jest.mock('./components/FeatureRequests/FeatureRequestsTabContent', () => ({ FeatureRequestsTabContent: () => null }))
+jest.mock('./components/Feed/FeedTabContent', () => ({ FeedTabContent: () => null }))
+jest.mock('./components/FeedbackButton', () => ({ FeedbackButton: () => null }))
+jest.mock('./components/Insights/ActiveUsersInsights', () => ({ ActiveUsersInsights: () => null }))
+jest.mock('./components/Insights/SessionInsights', () => ({ SessionInsights: () => null }))
+jest.mock('./components/Insights/SignupInsights', () => ({ SignupInsights: () => null }))
+
+describe('CustomerAnalyticsScene', () => {
+ beforeEach(() => {
+ initKeaTests()
+ featureFlagLogic.mount()
+ sceneLogic.mount()
+ customerAnalyticsSceneLogic.mount()
+ sceneLogic.actions.setScene(Scene.CustomerAnalytics, 'customerAnalyticsTasks', emptySceneParams)
+ })
+
+ afterEach(() => {
+ cleanup()
+ customerAnalyticsSceneLogic.unmount()
+ sceneLogic.unmount()
+ featureFlagLogic.unmount()
+ })
+
+ it('shows the Tasks tab and inbox only when the tasks flag is enabled', () => {
+ featureFlagLogic.actions.setFeatureFlags(
+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS, FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS],
+ {
+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS]: true,
+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS]: true,
+ }
+ )
+
+ const { rerender } = render(
+ <Provider>
+ <CustomerAnalyticsScene />
+ </Provider>
+ )
+
+ expect(screen.getAllByText('Tasks')).toHaveLength(2)
+ expect(document.querySelector('[data-attr="tasks-inbox"]')).toBeInTheDocument()
+
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.CUSTOMER_ANALYTICS], {
+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS]: true,
+ })
+ rerender(
+ <Provider>
+ <CustomerAnalyticsScene />
+ </Provider>
+ )
+
+ expect(document.querySelector('[data-attr="page-not-found"]')).toBeInTheDocument()
+ })
+})
diff --git a/products/customer_analytics/frontend/CustomerAnalyticsScene.tsx b/products/customer_analytics/frontend/CustomerAnalyticsScene.tsx
index 941c33bcef65..7bb052166904 100644
--- a/products/customer_analytics/frontend/CustomerAnalyticsScene.tsx
+++ b/products/customer_analytics/frontend/CustomerAnalyticsScene.tsx
@@ -11,7 +11,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { groupsAccessLogic } from 'lib/introductions/groupsAccessLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
+import { getAccessControlDisabledReason, userHasAccess } from 'lib/utils/accessControlUtils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { GroupsIntroduction } from 'scenes/groups/GroupsIntroduction'
import { sceneConfigurations } from 'scenes/scenes'
@@ -36,6 +36,7 @@ import { CustomerJourneySelect } from './components/CustomerJourneys/CustomerJou
import { customerJourneysLogic } from './components/CustomerJourneys/customerJourneysLogic'
import { DeleteJourneyButton } from './components/CustomerJourneys/DeleteJourneyButton'
import { journeyEditorLogic } from './components/CustomerJourneys/journeyEditorLogic'
+import { CustomerTasksInbox } from './components/CustomerTasks/CustomerTasksInbox'
import { FeatureRequestsTabContent } from './components/FeatureRequests/FeatureRequestsTabContent'
import { FeedTabContent } from './components/Feed/FeedTabContent'
import { FeedbackButton } from './components/FeedbackButton'
@@ -78,6 +79,11 @@ function CustomerAnalyticsSceneContent(): JSX.Element {
AccessControlResourceType.CustomerAnalytics,
AccessControlLevel.Editor
)
+ const canViewAllCustomerTasks = userHasAccess(
+ AccessControlResourceType.CustomerAnalytics,
+ AccessControlLevel.Viewer
+ )
+ const canCreateCustomerTasks = userHasAccess(AccessControlResourceType.CustomerAnalytics, AccessControlLevel.Editor)
useOnMountEffect(() => {
reportCustomerAnalyticsViewed()
@@ -97,6 +103,10 @@ function CustomerAnalyticsSceneContent(): JSX.Element {
return <NotFound object="page" />
}
+ if (activeTab === 'tasks' && !featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS]) {
+ return <NotFound object="page" />
+ }
+
const dashboardContent =
businessType === 'b2b' && shouldShowGroupsIntroduction ? (
<>
@@ -152,6 +162,15 @@ function CustomerAnalyticsSceneContent(): JSX.Element {
})
}
+ if (featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS]) {
+ tabs.push({
+ key: 'tasks',
+ label: 'Tasks',
+ content: <CustomerTasksInbox canCreate={canCreateCustomerTasks} canViewAll={canViewAllCustomerTasks} />,
+ link: combineUrl(urls.customerAnalyticsTasks(), searchParams).url,
+ })
+ }
+
tabs.push({
key: 'dashboard',
label: 'Dashboard',
@@ -187,8 +206,12 @@ function CustomerAnalyticsSceneContent(): JSX.Element {
) : (
<>
<SceneTitleSection
- name={sceneConfigurations[Scene.CustomerAnalytics].name}
- description={sceneConfigurations[Scene.CustomerAnalytics].description}
+ name={activeTab === 'tasks' ? 'Tasks' : sceneConfigurations[Scene.CustomerAnalytics].name}
+ description={
+ activeTab === 'tasks'
+ ? 'Work assigned to you across customer accounts.'
+ : sceneConfigurations[Scene.CustomerAnalytics].description
+ }
resourceType={{
type: sceneConfigurations[Scene.CustomerAnalytics].iconType || 'default_icon_type',
}}
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index 6033bb8488dd..5f02ea043bf6 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -158,9 +158,9 @@ When `CUSTOMER_ANALYTICS_ACCOUNT_SCENE` is off, the scene renders `CustomerAnaly
## The expanded row
-`AccountsTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. The body is `AccountNotebooksExpansion`: the Useful links and active-relationships sidebar plus the shared `AccountDetailTabs` over `notes` / `users` / `relationships` / `feature_requests` / `usage` / `spend` / `opportunities` / `conversations` / `meetings` / `event_stream` (`AccountExpansionTab`; the `event_stream` tab is gated by the `CUSTOMER_ANALYTICS_CSP` flag). `AccountNotesExpansion` owns the shared Notes body. Active tab comes from `activeTabFor(accountId)` (defaults to `notes`). Pagination inside these tabs keeps its page state out of the URL so changing pages does not rerun deep-link restoration and replace the active tab.
+`AccountsTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. The body is `AccountNotebooksExpansion`: the Useful links and active-relationships sidebar plus the shared `AccountDetailTabs` over `notes` / `tasks` / `users` / `relationships` / `feature_requests` / `usage` / `spend` / `opportunities` / `conversations` / `meetings` / `event_stream` (`AccountExpansionTab`; the `tasks` tab is gated by the `CUSTOMER_ANALYTICS_CUSTOMER_TASKS` flag and the `event_stream` tab is gated by the `CUSTOMER_ANALYTICS_CSP` flag). `AccountNotesExpansion` owns the shared Notes body. Active tab comes from `activeTabFor(accountId)` (defaults to `notes`). Pagination inside these tabs keeps its page state out of the URL so changing pages does not rerun deep-link restoration and replace the active tab.
-**Tab data is cached for the row's expanded lifetime, not refetched per tab switch.** `AccountDetailTabs` only renders the active tab's content (keyed by `activeKey`), so a tab's logic would normally unmount the moment you switch away and refetch on return. To avoid that, `AccountNotebooksExpansion` holds a mount reference to each per-tab logic via `useMountedLogic` — `accountNotebooksLogic({ accountId })`, `accountRelatedUsersLogic({ externalId })`, `accountRelationshipsLogic({ accountId })`, `accountBillingLogic` for both `kind: 'usage'` and `kind: 'spend'`, `accountOpportunitiesLogic({ accountId })`, `accountSummariesLogic({ accountId })`, `accountConversationsLogic({ accountId })`, `accountEmailThreadsLogic({ accountId })`, and `accountMeetingsLogic({ accountId })`. Since `AccountNotebooksExpansion` stays mounted for as long as the row is expanded (it's the `expandedRowRender` body), those keyed instances survive tab switches and only tear down when the row collapses. The `useMountedLogic` props must stay identical to the `useValues` props in the tab components so both resolve to the same keyed instance. `accountLinksLogic` mounts through the always-rendered sidebar. Data is loaded once on mount and not auto-refreshed while the row stays open — acceptable since this data needn't be live. The flag-gated Feature requests tab loads when opened instead of mounting its logic while the flag is off.
+**Tab data is cached for the row's expanded lifetime, not refetched per tab switch.** `AccountDetailTabs` only renders the active tab's content (keyed by `activeKey`), so a tab's logic would normally unmount the moment you switch away and refetch on return. To avoid that, `AccountNotebooksExpansion` holds a mount reference to each per-tab logic via `useMountedLogic` — `accountNotebooksLogic({ accountId })`, `accountRelatedUsersLogic({ externalId })`, `accountRelationshipsLogic({ accountId })`, `accountBillingLogic` for both `kind: 'usage'` and `kind: 'spend'`, `accountOpportunitiesLogic({ accountId })`, `accountSummariesLogic({ accountId })`, `accountConversationsLogic({ accountId })`, `accountEmailThreadsLogic({ accountId })`, and `accountMeetingsLogic({ accountId })`. Since `AccountNotebooksExpansion` stays mounted for as long as the row is expanded (it's the `expandedRowRender` body), those keyed instances survive tab switches and only tear down when the row collapses. The `useMountedLogic` props must stay identical to the `useValues` props in the tab components so both resolve to the same keyed instance. `accountLinksLogic` mounts through the always-rendered sidebar. `CustomerTasksMount` keeps the account task logic mounted only when `CUSTOMER_ANALYTICS_CUSTOMER_TASKS` is enabled. Data is loaded once on mount and not auto-refreshed while the row stays open — acceptable since this data needn't be live. Flag-gated tabs load only when their flag is enabled.
The Users tab reads its loaded data straight off `accountRelatedUsersLogic`, so the root mount above keeps it cached. Staff also see an "Impersonate" action that opens the user's Django admin detail page in the member's US or EU cloud. Outside PostHog Cloud, the action stays on the current origin so local and self-hosted users can test their own admin. The **Usage/Spend** tabs are different: their insight results live in `dataNodeLogic`/`dataVisualizationLogic`. After each `accountBillingLogic` loads its saved-insight metadata, it mounts those result logics immediately. Because the expanded-row root mounts both billing kinds, all Usage and Spend queries start when the account expands instead of waiting for a tab click. The result logics stay mounted until the row collapses. Changing the date range replaces each insight's preload and aborts work under the previous query key. The tab body reuses the same keyed logics and attaches them to `accountBillingLogic` via `useAttachedLogic` — `AccountBillingChart` does this directly, and the fallback `<Query>` path uses `attachTo={accountBillingLogic-instance}` plus matching insight context. This prevents duplicate loads and keeps results across tab switches. (The Opportunities tab loads its data in `accountOpportunitiesLogic` directly, not via an embedded query, so the root `useMountedLogic` above is enough — it needs no attachment.)
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountDetailTabs.tsx b/products/customer_analytics/frontend/components/Accounts/AccountDetailTabs.tsx
index 2b8bc475ad66..ebf240787933 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountDetailTabs.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountDetailTabs.tsx
@@ -5,7 +5,11 @@ import { LemonTabs } from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { userHasAccess } from 'lib/utils/accessControlUtils'
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
+import { CustomerTasksTabContent } from '../CustomerTasks/CustomerTasksTabContent'
import { AccountEventStreamToggle } from '../EventStream/AccountEventStreamToggle'
import { AccountBillingExpansion } from './AccountBillingExpansion'
import { AccountConversationsExpansion } from './AccountConversationsExpansion'
@@ -36,6 +40,8 @@ export function AccountDetailTabs({
}: AccountDetailTabsProps): JSX.Element {
const { featureFlags } = useValues(featureFlagLogic)
const visibleActiveTab = getVisibleAccountExpansionTab(activeTab, featureFlags)
+ const canCreateTasks = userHasAccess(AccessControlResourceType.CustomerAnalytics, AccessControlLevel.Editor)
+ const canViewAllTasks = userHasAccess(AccessControlResourceType.CustomerAnalytics, AccessControlLevel.Viewer)
return (
<LemonTabs
@@ -49,6 +55,18 @@ export function AccountDetailTabs({
label: 'Notes',
content: <AccountNotesExpansion accountId={accountId} embedded={embedded} />,
},
+ !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS] && {
+ key: 'tasks' as const,
+ label: 'Tasks',
+ content: (
+ <CustomerTasksTabContent
+ accountId={accountId}
+ canCreate={canCreateTasks}
+ canViewAll={canViewAllTasks}
+ embedded={embedded}
+ />
+ ),
+ },
{
key: 'users',
label: 'Users',
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.test.tsx b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.test.tsx
new file mode 100644
index 000000000000..c90ed3b02a48
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.test.tsx
@@ -0,0 +1,109 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { useActions, useMountedLogic, useValues } from 'kea'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+
+import { AccountNotebooksExpansion } from './AccountNotebooksExpansion'
+
+jest.mock('kea', () => ({
+ ...jest.requireActual('kea'),
+ useActions: jest.fn(),
+ useMountedLogic: jest.fn(),
+ useValues: jest.fn(),
+}))
+
+jest.mock('lib/logic/featureFlagLogic', () => ({ featureFlagLogic: { kind: 'featureFlags' } }))
+jest.mock('lib/utils/accessControlUtils', () => ({ userHasAccess: jest.fn(() => true) }))
+jest.mock('scenes/notebooks/NotebookPanel/notebookPanelLogic', () => ({
+ notebookPanelLogic: { kind: 'notebookPanel' },
+}))
+jest.mock('../EventStream/AccountEventStreamToggle', () => ({ AccountEventStreamToggle: () => null }))
+jest.mock('../CustomerTasks/CustomerTasksTabContent', () => ({ CustomerTasksTabContent: () => null }))
+jest.mock('../CustomerTasks/customerTasksLogic', () => ({ customerTasksLogic: () => ({ kind: 'tasks' }) }))
+jest.mock('./AccountBillingExpansion', () => ({ AccountBillingExpansion: () => null }))
+jest.mock('./AccountConversationsExpansion', () => ({ AccountConversationsExpansion: () => null }))
+jest.mock('./AccountFeatureRequestsExpansion', () => ({ AccountFeatureRequestsExpansion: () => null }))
+jest.mock('./AccountMeetingsExpansion', () => ({ AccountMeetingsExpansion: () => null }))
+jest.mock('./AccountOpportunitiesExpansion', () => ({ AccountOpportunitiesExpansion: () => null }))
+jest.mock('./AccountRelatedUsersExpansion', () => ({ AccountRelatedUsersExpansion: () => null }))
+jest.mock('./AccountRelationshipsExpansion', () => ({ AccountRelationshipsExpansion: () => null }))
+jest.mock('./accountBillingLogic', () => ({ accountBillingLogic: () => ({ kind: 'billing' }) }))
+jest.mock('./accountConversationsLogic', () => ({ accountConversationsLogic: () => ({ kind: 'conversations' }) }))
+jest.mock('./accountEmailThreadsLogic', () => ({ accountEmailThreadsLogic: () => ({ kind: 'emailThreads' }) }))
+jest.mock('./accountLinksLogic', () => ({ accountLinksLogic: () => ({ kind: 'links' }) }))
+jest.mock('./accountMeetingsLogic', () => ({ accountMeetingsLogic: () => ({ kind: 'meetings' }) }))
+jest.mock('./accountNotebooksLogic', () => ({ accountNotebooksLogic: () => ({ kind: 'notebooks' }) }))
+jest.mock('./accountOpportunitiesLogic', () => ({ accountOpportunitiesLogic: () => ({ kind: 'opportunities' }) }))
+jest.mock('./accountRelatedUsersLogic', () => ({ accountRelatedUsersLogic: () => ({ kind: 'users' }) }))
+jest.mock('./accountRelationshipsLogic', () => ({ accountRelationshipsLogic: () => ({ kind: 'relationships' }) }))
+jest.mock('./accountSummariesLogic', () => ({ accountSummariesLogic: () => ({ kind: 'summaries' }) }))
+jest.mock('./accountsExpansionLogic', () => ({
+ ...jest.requireActual('./accountsExpansionLogic'),
+ accountsExpansionLogic: { kind: 'expansion' },
+}))
+jest.mock('./constants', () => ({ AccountsEvents: { LinkClicked: 'link clicked', NoteClicked: 'note clicked' } }))
+jest.mock('./EditAccountLinksButton', () => ({ EditAccountLinksButton: () => null }))
+
+describe('AccountNotebooksExpansion', () => {
+ let customerTasksEnabled = false
+
+ beforeEach(() => {
+ ;(useMountedLogic as jest.Mock).mockImplementation(() => undefined)
+ ;(useActions as jest.Mock).mockImplementation(() => ({
+ createNote: jest.fn(),
+ selectNotebook: jest.fn(),
+ setActiveTab: jest.fn(),
+ setSearchTerm: jest.fn(),
+ setSorting: jest.fn(),
+ }))
+ ;(useValues as jest.Mock).mockImplementation((logic: { kind?: string }) => {
+ switch (logic.kind) {
+ case 'featureFlags':
+ return { featureFlags: { [FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS]: customerTasksEnabled } }
+ case 'expansion':
+ return { activeTabFor: () => 'notes' }
+ case 'links':
+ return { accountLoading: false, links: [] }
+ case 'relationships':
+ return { activeRelationships: [] }
+ case 'notebooks':
+ return {
+ createdNoteLoading: false,
+ notebooks: [],
+ notebooksResponseLoading: false,
+ pagination: undefined,
+ searchTerm: '',
+ sorting: undefined,
+ }
+ default:
+ return {}
+ }
+ })
+ })
+
+ afterEach(() => {
+ cleanup()
+ jest.clearAllMocks()
+ })
+
+ test.each([
+ [true, true],
+ [false, false],
+ ])('shows the Tasks tab only when the customer tasks flag is %s', (enabled, visible) => {
+ customerTasksEnabled = enabled
+ render(<AccountNotebooksExpansion accountId="account-1" externalId="external-1" />)
+
+ if (visible) {
+ expect(screen.getByText('Tasks')).toBeInTheDocument()
+ } else {
+ expect(screen.queryByText('Tasks')).not.toBeInTheDocument()
+ }
+ // Mounting the tasks logic loads tasks, so an expanded row must not mount it without the tab.
+ const mountedTasksLogic = (useMountedLogic as jest.Mock).mock.calls.some(
+ ([logic]: [{ kind?: string }]) => logic?.kind === 'tasks'
+ )
+ expect(mountedTasksLogic).toBe(visible)
+ })
+})
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx
index b88b9dd92064..96ae9efd3a2e 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx
@@ -14,10 +14,13 @@ import {
} from '@posthog/icons'
import { LemonButton, LemonLabel, LemonSkeleton, ProfilePicture } from '@posthog/lemon-ui'
+import { FEATURE_FLAGS } from 'lib/constants'
import { IconSlack } from 'lib/lemon-ui/icons'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { urls } from 'scenes/urls'
+import { customerTasksLogic } from '../CustomerTasks/customerTasksLogic'
import { accountBillingLogic } from './accountBillingLogic'
import { accountConversationsLogic } from './accountConversationsLogic'
import { AccountDetailTabs } from './AccountDetailTabs'
@@ -130,6 +133,11 @@ function UsefulLinks({ accountId }: { accountId: string }): JSX.Element {
)
}
+function CustomerTasksMount({ accountId }: { accountId: string }): null {
+ useMountedLogic(customerTasksLogic({ context: 'account', accountId }))
+ return null
+}
+
export function AccountNotebooksExpansion({
accountId,
externalId,
@@ -148,6 +156,7 @@ export function AccountNotebooksExpansion({
useMountedLogic(accountConversationsLogic({ accountId }))
useMountedLogic(accountEmailThreadsLogic({ accountId }))
useMountedLogic(accountMeetingsLogic({ accountId }))
+ const { featureFlags } = useValues(featureFlagLogic)
const { activeTabFor } = useValues(accountsExpansionLogic)
const { setActiveTab } = useActions(accountsExpansionLogic)
const activeTab = activeTabFor(accountId)
@@ -157,6 +166,9 @@ export function AccountNotebooksExpansion({
className="sticky left-0 w-[100cqw] max-w-full overflow-x-hidden p-3 bg-bg-light"
data-attr="account-expansion"
>
+ {!!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS] && (
+ <CustomerTasksMount accountId={accountId} />
+ )}
<div className="flex gap-4">
<div className="w-fit shrink-0 flex flex-col gap-4">
<UsefulLinks accountId={accountId} />
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts
index fbcf179aff47..855228a20cde 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts
@@ -8,6 +8,7 @@ import { AccountsEvents } from './constants'
export type AccountExpansionTab =
| 'notes'
+ | 'tasks'
| 'users'
| 'relationships'
| 'feature_requests'
@@ -20,6 +21,7 @@ export type AccountExpansionTab =
export const ACCOUNT_EXPANSION_TABS: AccountExpansionTab[] = [
'notes',
+ 'tasks',
'users',
'relationships',
'feature_requests',
@@ -43,6 +45,9 @@ export function getVisibleAccountExpansionTab(
if (tab === 'feature_requests' && !featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_FEATURE_REQUESTS]) {
return DEFAULT_ACCOUNT_TAB
}
+ if (tab === 'tasks' && !featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS]) {
+ return DEFAULT_ACCOUNT_TAB
+ }
if ((tab === 'meetings' || tab === 'event_stream') && !featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]) {
return DEFAULT_ACCOUNT_TAB
}
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
index 769298fadaa6..42c1f6d4df4d 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
@@ -743,6 +743,14 @@ describe('accountsLogic', () => {
expect(expansion?.values.activeTabByAccount[ACCOUNT_ID]).toBe(DEFAULT_ACCOUNT_TAB)
})
+ it('accepts the tasks tab from an account deep link', async () => {
+ router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID, 'tasks'))
+ await expectLogic(logic).toFinishAllListeners()
+
+ const expansion = accountsExpansionLogic.findMounted()
+ expect(expansion?.values.activeTabByAccount[ACCOUNT_ID]).toBe('tasks')
+ })
+
it('falls back to the default tab for an unknown tab', async () => {
router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID, 'bogus'))
await expectLogic(logic).toFinishAllListeners()
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTaskActionsMenu.tsx b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTaskActionsMenu.tsx
new file mode 100644
index 000000000000..b31bccfba698
--- /dev/null
+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTaskActionsMenu.tsx
@@ -0,0 +1,43 @@
+import { useActions, useValues } from 'kea'
+
+import { IconArchive, IconEllipsis, IconUndo } from '@posthog/icons'
+import { LemonButton, LemonMenu, type LemonMenuItems } from '@posthog/lemon-ui'
+
+import type { CustomerTaskApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+
+import type { customerTasksLogicType } from './customerTasksLogic'
+export interface CustomerTaskActionsMenuProps {
+ task: CustomerTaskApi
+ logic: import('kea').BuiltLogic<customerTasksLogicType>
+}
+export function CustomerTaskActionsMenu({ task, logic }: CustomerTaskActionsMenuProps): JSX.Element {
+ const { mutationKeys } = useValues(logic)
+ const { archiveTask, restoreTask } = useActions(logic)
+ const saving = Boolean(mutationKeys[task.id])
+ const archived = Boolean(task.archived_at)
+ const canMutate = archived ? task.can_restore : task.can_edit
+ const items: LemonMenuItems = [
+ {
+ items: [
+ {
+ label: archived ? 'Restore task' : 'Archive task',
+ icon: archived ? <IconUndo /> : <IconArchive />,
+ onClick: () => (archived ? restoreTask(task.id) : archiveTask(task.id)),
+ },
+ ],
+ },
+ ]
+ return (
+ <LemonMenu items={items}>
+ <LemonButton
+ type="tertiary"
+ size="small"
+ icon={<IconEllipsis />}
+ loading={saving}
+ disabledReason={!canMutate ? 'You cannot edit this task' : saving ? 'Saving' : undefined}
+ aria-label="Task actions"
+ data-attr="customer-task-actions"
+ />
+ </LemonMenu>
+ )
+}
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTaskAssigneeSelect.tsx b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTaskAssigneeSelect.tsx
new file mode 100644
index 000000000000..81abbdefe400
--- /dev/null
+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTaskAssigneeSelect.tsx
@@ -0,0 +1,47 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, ProfilePicture } from '@posthog/lemon-ui'
+
+import { MemberSelect } from 'lib/components/MemberSelect'
+import { fullName } from 'lib/utils/strings'
+
+import type { CustomerTaskApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+
+import { customerTaskEditDisabledReason } from './customerTaskFilters'
+import type { customerTasksLogicType } from './customerTasksLogic'
+export interface CustomerTaskAssigneeSelectProps {
+ task: CustomerTaskApi
+ logic: import('kea').BuiltLogic<customerTasksLogicType>
+}
+export function CustomerTaskAssigneeSelect({ task, logic }: CustomerTaskAssigneeSelectProps): JSX.Element {
+ const { mutationKeys } = useValues(logic)
+ const { updateTask } = useActions(logic)
+ const saving = Boolean(mutationKeys[task.id])
+ return (
+ <MemberSelect
+ value={task.assigned_to?.id ?? null}
+ defaultLabel="Unassigned"
+ allowNone
+ type="tertiary"
+ size="small"
+ onChange={(user) => updateTask(task.id, { assigned_to_id: user?.id ?? null })}
+ >
+ {(selected) => {
+ // MemberSelect resolves selected from the member list, which loads only after the picker opens.
+ const assignee = selected ?? task.assigned_to
+ return (
+ <LemonButton
+ type="tertiary"
+ size="small"
+ loading={saving}
+ disabledReason={customerTaskEditDisabledReason(task) ?? (saving ? 'Saving' : undefined)}
+ icon={assignee ? <ProfilePicture user={{ email: assignee.email }} size="sm" /> : undefined}
+ data-attr="customer-task-assignee"
+ >
+ {assignee ? fullName(assignee) || assignee.email : 'Unassigned'}
+ </LemonButton>
+ )
+ }}
+ </MemberSelect>
+ )
+}
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTaskDueAtInput.tsx b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTaskDueAtInput.tsx
new file mode 100644
index 000000000000..eeedbf1b3423
--- /dev/null
+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTaskDueAtInput.tsx
@@ -0,0 +1,63 @@
+import { useActions, useValues } from 'kea'
+
+import { IconX } from '@posthog/icons'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { dayjs, dayjsLocalToTimezone, dayjsUtcToTimezone } from 'lib/dayjs'
+import { LemonCalendarSelectInput } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'
+
+import type { CustomerTaskApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+
+import { customerTaskEditDisabledReason } from './customerTaskFilters'
+import type { customerTasksLogicType } from './customerTasksLogic'
+export interface CustomerTaskDueAtInputProps {
+ task: CustomerTaskApi
+ logic: import('kea').BuiltLogic<customerTasksLogicType>
+ timezone: string
+}
+export function CustomerTaskDueAtInput({ task, logic, timezone }: CustomerTaskDueAtInputProps): JSX.Element {
+ const { mutationKeys } = useValues(logic)
+ const { updateTask } = useActions(logic)
+ const saving = Boolean(mutationKeys[task.id])
+ const overdue = Boolean(
+ task.due_at && task.status !== 'completed' && task.status !== 'canceled' && dayjs(task.due_at).isBefore(dayjs())
+ )
+ const disabledReason = customerTaskEditDisabledReason(task) ?? (saving ? 'Saving' : undefined)
+ return (
+ <LemonCalendarSelectInput
+ value={task.due_at ? dayjsUtcToTimezone(task.due_at, timezone) : null}
+ onChange={(value) =>
+ updateTask(task.id, {
+ due_at: value
+ ? dayjsLocalToTimezone(value.format('YYYY-MM-DDTHH:mm'), timezone).toISOString()
+ : null,
+ })
+ }
+ granularity="minute"
+ format="MMM D, YYYY HH:mm"
+ use24HourFormat
+ placeholder="No due date"
+ buttonProps={{
+ type: 'tertiary',
+ size: 'small',
+ loading: saving,
+ disabledReason,
+ sideAction: task.due_at
+ ? {
+ icon: <IconX />,
+ onClick: () => updateTask(task.id, { due_at: null }),
+ disabledReason,
+ 'aria-label': 'Clear date',
+ }
+ : undefined,
+ className: overdue ? 'text-danger' : undefined,
+ 'data-attr': 'customer-task-due',
+ children: task.due_at ? (
+ <TZLabel time={task.due_at} noStyles className={overdue ? 'text-danger' : undefined} />
+ ) : (
+ 'No due date'
+ ),
+ }}
+ />
+ )
+}
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTaskModal.tsx b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTaskModal.tsx
new file mode 100644
index 000000000000..1db81688e1a1
--- /dev/null
+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTaskModal.tsx
@@ -0,0 +1,230 @@
+import { useActions, useValues } from 'kea'
+
+import { IconX } from '@posthog/icons'
+import {
+ LemonButton,
+ LemonInput,
+ LemonInputSelect,
+ LemonLabel,
+ LemonModal,
+ LemonTextArea,
+ ProfilePicture,
+} from '@posthog/lemon-ui'
+
+import { MemberSelect } from 'lib/components/MemberSelect'
+import { dayjsLocalToTimezone, dayjsUtcToTimezone } from 'lib/dayjs'
+import { LemonCalendarSelectInput } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'
+import { fullName } from 'lib/utils/strings'
+
+import { customerTaskEditDisabledReason, type CustomerTasksContext } from './customerTaskFilters'
+import type { customerTasksLogicType } from './customerTasksLogic'
+
+export interface CustomerTaskModalProps {
+ logic: import('kea').BuiltLogic<customerTasksLogicType>
+ context: CustomerTasksContext
+}
+
+export function CustomerTaskModal({ logic, context }: CustomerTaskModalProps): JSX.Element {
+ const {
+ modalOpen,
+ modalTask,
+ accountOptions,
+ accountOptionsResponseLoading,
+ draftName,
+ draftDescription,
+ draftAccount,
+ draftAssignedTo,
+ draftDueAt,
+ mutationKeys,
+ timezone,
+ } = useValues(logic)
+ const {
+ closeModal,
+ loadAccountOptions,
+ setDraftName,
+ setDraftDescription,
+ setDraftAccount,
+ setDraftAssignedTo,
+ setDraftDueAt,
+ submitModal,
+ } = useActions(logic)
+ const saving = Boolean(mutationKeys[modalTask?.id ?? 'create'])
+ const create = modalTask === null
+ const editDisabledReason = modalTask ? customerTaskEditDisabledReason(modalTask) : undefined
+ const editable = !editDisabledReason
+ const disabledReason = editDisabledReason ?? (saving ? 'Saving' : undefined)
+ const accountOptionsForSelect = accountOptions.map((account) => ({ key: account.id, label: account.name }))
+ if (draftAccount && !accountOptionsForSelect.some((option) => option.key === draftAccount.id)) {
+ accountOptionsForSelect.unshift({ key: draftAccount.id, label: draftAccount.name })
+ }
+ const close = (): void => {
+ if (!saving) {
+ closeModal()
+ }
+ }
+
+ return (
+ <LemonModal
+ isOpen={modalOpen}
+ onClose={close}
+ closable={!saving}
+ title={create ? 'New task' : editable ? 'Edit task' : 'Task details'}
+ width={640}
+ footer={
+ <>
+ <LemonButton type="secondary" onClick={close} disabledReason={saving ? 'Saving' : undefined}>
+ {editable ? 'Cancel' : 'Close'}
+ </LemonButton>
+ {editable && (
+ <LemonButton
+ type="primary"
+ onClick={submitModal}
+ loading={saving}
+ disabledReason={!draftName.trim() ? 'Enter a task name' : undefined}
+ >
+ {create ? 'Create task' : 'Save changes'}
+ </LemonButton>
+ )}
+ </>
+ }
+ >
+ <div className="flex flex-col gap-4">
+ <div className="flex flex-col gap-1">
+ <LemonLabel>Task name</LemonLabel>
+ <LemonInput
+ value={draftName}
+ onChange={setDraftName}
+ maxLength={400}
+ autoFocus={editable}
+ fullWidth
+ disabledReason={disabledReason}
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <LemonLabel>Description (optional)</LemonLabel>
+ <LemonTextArea
+ value={draftDescription}
+ onChange={setDraftDescription}
+ minRows={4}
+ disabled={Boolean(disabledReason)}
+ />
+ </div>
+ {context === 'inbox' && (
+ <div className="flex flex-col gap-1">
+ <LemonLabel>Account (optional)</LemonLabel>
+ {editable ? (
+ <div className="flex flex-wrap items-center gap-2">
+ <div className="min-w-64 flex-1">
+ <LemonInputSelect
+ mode="single"
+ value={draftAccount ? [draftAccount.id] : []}
+ options={accountOptionsForSelect}
+ loading={accountOptionsResponseLoading}
+ onInputChange={(query) => loadAccountOptions({ query })}
+ onChange={(values) => {
+ const accountId = values[0]
+ if (!accountId) {
+ setDraftAccount(null)
+ return
+ }
+ const account = accountOptions.find((option) => option.id === accountId)
+ setDraftAccount(
+ account
+ ? { id: account.id, name: account.name }
+ : (draftAccount ?? null)
+ )
+ }}
+ placeholder="No account"
+ disabledReason={disabledReason}
+ fullWidth
+ data-attr="customer-task-account"
+ />
+ </div>
+ {draftAccount && (
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconX />}
+ onClick={() => setDraftAccount(null)}
+ disabledReason={disabledReason}
+ >
+ Remove account
+ </LemonButton>
+ )}
+ </div>
+ ) : (
+ <LemonInput value={draftAccount?.name ?? 'No account'} disabledReason={disabledReason} />
+ )}
+ </div>
+ )}
+ <div className="flex flex-col gap-1">
+ <LemonLabel>Assignee (optional)</LemonLabel>
+ <MemberSelect
+ value={draftAssignedTo?.id ?? null}
+ defaultLabel="Unassigned"
+ type="secondary"
+ size="small"
+ onChange={(user) =>
+ setDraftAssignedTo(
+ user
+ ? {
+ id: user.id,
+ email: user.email,
+ first_name: user.first_name,
+ last_name: user.last_name ?? '',
+ }
+ : null
+ )
+ }
+ >
+ {(selected) => {
+ const assignee = selected ?? draftAssignedTo
+ return (
+ <LemonButton
+ type="secondary"
+ size="small"
+ disabledReason={disabledReason}
+ icon={
+ assignee ? (
+ <ProfilePicture user={{ email: assignee.email }} size="sm" />
+ ) : undefined
+ }
+ >
+ {assignee ? fullName(assignee) || assignee.email : 'Unassigned'}
+ </LemonButton>
+ )
+ }}
+ </MemberSelect>
+ </div>
+ <div className="flex flex-col gap-1">
+ <LemonLabel>Due date (optional)</LemonLabel>
+ <LemonCalendarSelectInput
+ value={draftDueAt ? dayjsUtcToTimezone(draftDueAt, timezone) : null}
+ onChange={(value) =>
+ setDraftDueAt(
+ value
+ ? dayjsLocalToTimezone(value.format('YYYY-MM-DDTHH:mm'), timezone).toISOString()
+ : null
+ )
+ }
+ granularity="minute"
+ format="MMM D, YYYY HH:mm"
+ use24HourFormat
+ placeholder="No due date"
+ buttonProps={{
+ disabledReason,
+ sideAction: draftDueAt
+ ? {
+ icon: <IconX />,
+ onClick: () => setDraftDueAt(null),
+ disabledReason,
+ 'aria-label': 'Clear date',
+ }
+ : undefined,
+ }}
+ />
+ </div>
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTaskStatusSelect.tsx b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTaskStatusSelect.tsx
new file mode 100644
index 000000000000..f082d1d15a02
--- /dev/null
+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTaskStatusSelect.tsx
@@ -0,0 +1,46 @@
+import { useActions, useValues } from 'kea'
+
+import { IconChevronDown } from '@posthog/icons'
+import { LemonButton, LemonMenu, type LemonMenuItems } from '@posthog/lemon-ui'
+
+import type {
+ CustomerTaskApi,
+ CustomerTaskStatusEnumApi,
+} from 'products/customer_analytics/frontend/generated/api.schemas'
+
+import { CUSTOMER_TASK_STATUS_TRANSITIONS, customerTaskEditDisabledReason } from './customerTaskFilters'
+import type { customerTasksLogicType } from './customerTasksLogic'
+export interface CustomerTaskStatusSelectProps {
+ task: CustomerTaskApi
+ logic: import('kea').BuiltLogic<customerTasksLogicType>
+}
+export function CustomerTaskStatusSelect({ task, logic }: CustomerTaskStatusSelectProps): JSX.Element {
+ const { mutationKeys } = useValues(logic)
+ const { updateTask } = useActions(logic)
+ const saving = Boolean(mutationKeys[task.id])
+ const items: LemonMenuItems = [
+ {
+ items: CUSTOMER_TASK_STATUS_TRANSITIONS[task.status].map((status) => ({
+ label: statusLabel(status),
+ onClick: () => updateTask(task.id, { status }),
+ })),
+ },
+ ]
+ return (
+ <LemonMenu items={items}>
+ <LemonButton
+ type="tertiary"
+ size="small"
+ sideIcon={<IconChevronDown />}
+ loading={saving}
+ disabledReason={customerTaskEditDisabledReason(task) ?? (saving ? 'Saving' : undefined)}
+ data-attr="customer-task-status"
+ >
+ {statusLabel(task.status)}
+ </LemonButton>
+ </LemonMenu>
+ )
+}
+function statusLabel(status: CustomerTaskStatusEnumApi): string {
+ return status === 'in_progress' ? 'In progress' : status.charAt(0).toUpperCase() + status.slice(1)
+}
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksFilters.tsx b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksFilters.tsx
new file mode 100644
index 000000000000..bb04821a3728
--- /dev/null
+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksFilters.tsx
@@ -0,0 +1,167 @@
+import { useActions, useValues } from 'kea'
+
+import { IconChevronDown, IconFilter, IconX } from '@posthog/icons'
+import {
+ LemonButton,
+ LemonDropdown,
+ LemonInput,
+ LemonInputSelect,
+ LemonMenu,
+ type LemonMenuItems,
+} from '@posthog/lemon-ui'
+
+import { MemberSelect } from 'lib/components/MemberSelect'
+
+import type { CustomerTaskAssigneeFilter, CustomerTasksContext } from './customerTaskFilters'
+import {
+ CUSTOMER_TASK_ARCHIVE_OPTIONS,
+ CUSTOMER_TASK_DUE_OPTIONS,
+ CUSTOMER_TASK_STATUS_OPTIONS,
+} from './customerTaskFilters'
+import type { customerTasksLogicType } from './customerTasksLogic'
+export interface CustomerTasksFiltersProps {
+ logic: import('kea').BuiltLogic<customerTasksLogicType>
+ context: CustomerTasksContext
+ canViewAll?: boolean
+}
+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 status: LemonMenuItems = [
+ {
+ items: CUSTOMER_TASK_STATUS_OPTIONS.map((o) => ({
+ label: o.label,
+ active: filters.status === o.value,
+ onClick: () => setFilters({ status: o.value }),
+ })),
+ },
+ ]
+ const archive: LemonMenuItems = [
+ {
+ items: CUSTOMER_TASK_ARCHIVE_OPTIONS.map((o) => ({
+ label: o.label,
+ active: filters.archiveState === o.value,
+ onClick: () => setFilters({ archiveState: o.value }),
+ })),
+ },
+ ]
+ const due: LemonMenuItems = [
+ {
+ items: CUSTOMER_TASK_DUE_OPTIONS.map((o) => ({
+ label: o.label,
+ active: filters.due === o.value,
+ onClick: () => setFilters({ due: o.value }),
+ })),
+ },
+ ]
+ 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'
+ const options = accountOptions.map((a) => ({ key: a.id, label: a.name }))
+ if (filters.account && !options.some((o) => o.key === filters.account?.id)) {
+ options.unshift({ key: filters.account.id, label: filters.account.name })
+ }
+ return (
+ <div className="flex flex-wrap items-center gap-2" data-attr="customer-tasks-filters">
+ <LemonInput
+ type="search"
+ value={filters.search}
+ onChange={setSearch}
+ placeholder="Search tasks"
+ size="small"
+ className="min-w-64"
+ data-attr="customer-tasks-search"
+ />
+ <LemonMenu items={status}>
+ <LemonButton type="secondary" size="small" icon={<IconFilter />} sideIcon={<IconChevronDown />}>
+ {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' })}
+ />
+ )}{' '}
+ {context === 'inbox' && (
+ <LemonMenu items={due}>
+ <LemonButton type="secondary" size="small" sideIcon={<IconChevronDown />}>
+ {CUSTOMER_TASK_DUE_OPTIONS.find((o) => o.value === filters.due)?.label}
+ </LemonButton>
+ </LemonMenu>
+ )}
+ {context === 'inbox' && (
+ <LemonDropdown
+ visible={accountFilterOpen}
+ onVisibilityChange={setAccountFilterOpen}
+ closeOnClickInside={false}
+ placement="bottom-start"
+ overlay={
+ <div className="p-2 min-w-64">
+ <LemonInputSelect
+ mode="single"
+ value={filters.account ? [filters.account.id] : []}
+ options={options}
+ loading={accountOptionsResponseLoading}
+ onInputChange={(query) => loadAccountOptions({ query })}
+ onChange={(values) => {
+ const id = values[0]
+ const account = accountOptions.find((a) => a.id === id)
+ setAccountFilter(account ? { id: account.id, name: account.name } : null)
+ setAccountFilterOpen(false)
+ }}
+ placeholder="Search accounts"
+ />
+ </div>
+ }
+ >
+ <LemonButton type="secondary" size="small" sideIcon={<IconChevronDown />}>
+ {filters.account?.name ?? 'Account'}
+ </LemonButton>
+ </LemonDropdown>
+ )}
+ <LemonMenu items={archive}>
+ <LemonButton type="secondary" size="small" sideIcon={<IconChevronDown />}>
+ {CUSTOMER_TASK_ARCHIVE_OPTIONS.find((o) => o.value === filters.archiveState)?.label}
+ </LemonButton>
+ </LemonMenu>
+ {hasActiveFilters && (
+ <LemonButton type="tertiary" size="small" icon={<IconX />} onClick={resetFilters}>
+ Reset filters
+ </LemonButton>
+ )}
+ </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/CustomerTasksInbox.tsx b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksInbox.tsx
new file mode 100644
index 000000000000..e86a9ab9572e
--- /dev/null
+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksInbox.tsx
@@ -0,0 +1,27 @@
+import { useMountedLogic, useValues } from 'kea'
+
+import { teamLogic } from 'scenes/teamLogic'
+import { userLogic } from 'scenes/userLogic'
+
+import { customerTasksPersistencePrefix } from './customerTaskFilters'
+import { customerTasksLogic } from './customerTasksLogic'
+import { CustomerTasksTable } from './CustomerTasksTable'
+export interface CustomerTasksInboxProps {
+ canCreate?: boolean
+ canViewAll?: boolean
+}
+export function CustomerTasksInbox({ canCreate = false, canViewAll = false }: CustomerTasksInboxProps): JSX.Element {
+ const { currentTeamId } = useValues(teamLogic)
+ const { user } = useValues(userLogic)
+ const persistPrefix =
+ currentTeamId !== null && user?.id !== undefined
+ ? customerTasksPersistencePrefix(currentTeamId, user.id)
+ : undefined
+ const logic = customerTasksLogic({
+ context: 'inbox',
+ canViewAll,
+ persistPrefix,
+ })
+ useMountedLogic(logic)
+ return <CustomerTasksTable logic={logic} context="inbox" canCreate={canCreate} canViewAll={canViewAll} />
+}
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTabContent.tsx b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTabContent.tsx
new file mode 100644
index 000000000000..b52d53813f72
--- /dev/null
+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTabContent.tsx
@@ -0,0 +1,28 @@
+import { useMountedLogic } from 'kea'
+
+import { customerTasksLogic } from './customerTasksLogic'
+import { CustomerTasksTable } from './CustomerTasksTable'
+export interface CustomerTasksTabContentProps {
+ accountId: string
+ canCreate?: boolean
+ canViewAll?: boolean
+ embedded?: boolean
+}
+export function CustomerTasksTabContent({
+ accountId,
+ canCreate = false,
+ canViewAll = false,
+ embedded = true,
+}: CustomerTasksTabContentProps): JSX.Element {
+ const logic = customerTasksLogic({ context: 'account', accountId })
+ useMountedLogic(logic)
+ return (
+ <CustomerTasksTable
+ logic={logic}
+ context="account"
+ canCreate={canCreate}
+ canViewAll={canViewAll}
+ embedded={embedded}
+ />
+ )
+}
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.scss b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.scss
new file mode 100644
index 000000000000..9ed2f869c9b2
--- /dev/null
+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.scss
@@ -0,0 +1,19 @@
+.CustomerTasksTable {
+ container-type: inline-size;
+}
+
+// Source order makes this container override take precedence over the base rule.
+.CustomerTasksTable__narrow-assignee {
+ display: none;
+}
+
+@container (max-width: 720px) {
+ .CustomerTasksTable__updated,
+ .CustomerTasksTable__assignee {
+ display: none;
+ }
+
+ .CustomerTasksTable__narrow-assignee {
+ display: block;
+ }
+}
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.test.tsx b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.test.tsx
new file mode 100644
index 000000000000..2dc77605ba7d
--- /dev/null
+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.test.tsx
@@ -0,0 +1,196 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'
+import { Provider } from 'kea'
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import { accountsList, customerTasksList } from 'products/customer_analytics/frontend/generated/api'
+import type { CustomerTaskApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+
+import { customerTasksLogic } from './customerTasksLogic'
+import { CustomerTasksTable } from './CustomerTasksTable'
+
+jest.mock('products/customer_analytics/frontend/generated/api', () => ({
+ accountsList: jest.fn(),
+ customerTasksArchiveCreate: jest.fn(),
+ customerTasksCreate: jest.fn(),
+ customerTasksList: jest.fn(),
+ customerTasksPartialUpdate: jest.fn(),
+ customerTasksRestoreCreate: jest.fn(),
+}))
+
+const mockList = customerTasksList as jest.MockedFunction<typeof customerTasksList>
+const mockAccounts = accountsList as jest.MockedFunction<typeof accountsList>
+
+const accountlessTask: CustomerTaskApi = {
+ id: 'task-1',
+ account: null,
+ name: 'Follow up',
+ description: 'First line\nSecond line\nThird line',
+ status: 'open',
+ assigned_to: { id: 7, email: '[email protected]', first_name: 'Casey', last_name: 'Kim' },
+ due_at: null,
+ completed_at: null,
+ completed_by: null,
+ created_by: null,
+ archived_at: null,
+ created_at: '2026-09-02T10:00:00Z',
+ updated_at: '2026-09-02T10:00:00Z',
+ can_edit: false,
+ can_restore: false,
+}
+
+function tableHeaders(table: HTMLElement): HTMLTableCellElement[] {
+ return Array.from(table.querySelectorAll('thead th'))
+}
+
+function findTableHeader(table: HTMLElement, title: string): HTMLTableCellElement | undefined {
+ return tableHeaders(table).find((header) => header.textContent?.trim() === title)
+}
+
+function filterBar(container: HTMLElement): HTMLElement {
+ return container.querySelector('[data-attr="customer-tasks-filters"]') as HTMLElement
+}
+
+describe('CustomerTasksTable', () => {
+ let logic: ReturnType<typeof customerTasksLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ mockList.mockResolvedValue({ count: 1, next: null, previous: null, results: [accountlessTask] })
+ mockAccounts.mockResolvedValue({ count: 0, next: null, previous: null, results: [] })
+ logic = customerTasksLogic({ context: 'inbox' })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ cleanup()
+ logic.unmount()
+ })
+
+ test('renders task details and opens the read-only modal', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ render(
+ <Provider>
+ <CustomerTasksTable logic={logic} context="inbox" />
+ </Provider>
+ )
+
+ const table = screen.getByRole('table')
+ expect(tableHeaders(table)[0]).toHaveTextContent('Task')
+ const taskName = within(table).getByText('Follow up')
+ const taskRow = taskName.closest('tr')
+ expect(taskRow).not.toBeNull()
+ expect(within(taskRow!).getByText('First line Second line Third line')).toBeInTheDocument()
+ // The member list loads only once a picker opens, so the row has to name the assignee itself.
+ expect(taskRow!.querySelector('[data-attr="customer-task-assignee"]')).toHaveTextContent('Casey Kim')
+
+ fireEvent.click(taskName)
+ const dialog = screen.getByRole('dialog')
+ expect(within(dialog).getByText('Task details')).toBeInTheDocument()
+ expect(within(dialog).getByText('Account (optional)')).toBeInTheDocument()
+ expect(within(dialog).getByDisplayValue('No account')).toBeDisabled()
+ expect(within(dialog).getByDisplayValue('Follow up')).toBeDisabled()
+ expect(within(dialog).queryByText('Save changes')).not.toBeInTheDocument()
+ expect(within(dialog).getByText('Close')).toBeInTheDocument()
+
+ mockList.mockResolvedValueOnce({
+ count: 1,
+ next: null,
+ previous: null,
+ results: [{ ...accountlessTask, description: ' ' }],
+ })
+ logic.actions.loadTaskPage()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(within(table).queryByText('First line Second line Third line')).not.toBeInTheDocument()
+ })
+
+ test('shows the task assignee before project members load', async () => {
+ mockList.mockResolvedValueOnce({
+ count: 1,
+ next: null,
+ previous: null,
+ results: [
+ {
+ ...accountlessTask,
+ assigned_to: {
+ id: 178,
+ email: '[email protected]',
+ first_name: 'Alex',
+ last_name: 'Morgan',
+ },
+ },
+ ],
+ })
+ await expectLogic(logic).toFinishAllListeners()
+
+ render(
+ <Provider>
+ <CustomerTasksTable logic={logic} context="inbox" />
+ </Provider>
+ )
+
+ expect(screen.getAllByText('Alex Morgan').length).toBeGreaterThan(0)
+ fireEvent.click(screen.getByText('Follow up'))
+ expect(within(screen.getByRole('dialog')).getByText('Alex Morgan')).toBeInTheDocument()
+ })
+
+ test.each([
+ ['Task', 'name'],
+ ['Status', 'status'],
+ ['Assignee', 'assigned_to'],
+ ['Due', '-due_at'],
+ ['Updated', 'updated_at'],
+ ['Account', 'account'],
+ ])('orders by %s on the server and resets pagination', async (header, ordering) => {
+ await expectLogic(logic).toFinishAllListeners()
+ render(
+ <Provider>
+ <CustomerTasksTable logic={logic} context="inbox" />
+ </Provider>
+ )
+ const table = screen.getByRole('table')
+
+ logic.actions.setPage(2)
+ await expectLogic(logic).toFinishAllListeners()
+ mockList.mockClear()
+
+ const tableHeader = findTableHeader(table, header)
+ if (!tableHeader) {
+ throw new Error(`Missing ${header} table header`)
+ }
+ fireEvent.click(within(tableHeader).getByText(header))
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.page).toBe(1)
+ expect(mockList).toHaveBeenLastCalledWith(expect.any(String), expect.objectContaining({ ordering, offset: 0 }))
+ })
+
+ test('shows Account ordering and assignee filters only in the inbox', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ const inbox = render(
+ <Provider>
+ <CustomerTasksTable logic={logic} context="inbox" canViewAll />
+ </Provider>
+ )
+ expect(findTableHeader(screen.getByRole('table'), 'Account')).not.toBeUndefined()
+ expect(within(filterBar(inbox.container)).queryByText('Choose member')).not.toBeNull()
+
+ cleanup()
+ logic.unmount()
+ logic = customerTasksLogic({ context: 'account', accountId: 'account-1' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ const accountTable = render(
+ <Provider>
+ <CustomerTasksTable logic={logic} context="account" canViewAll />
+ </Provider>
+ )
+
+ expect(findTableHeader(accountTable.getByRole('table'), 'Account')).toBeUndefined()
+ expect(within(filterBar(accountTable.container)).queryByText('Choose member')).toBeNull()
+ })
+})
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.tsx b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.tsx
new file mode 100644
index 000000000000..e3f5342d83a4
--- /dev/null
+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.tsx
@@ -0,0 +1,176 @@
+import './CustomerTasksTable.scss'
+
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonButton, LemonSkeleton } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { LemonTable, type LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { Link } from 'lib/lemon-ui/Link'
+import { urls } from 'scenes/urls'
+
+import type { CustomerTaskApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+
+import { CustomerTaskActionsMenu } from './CustomerTaskActionsMenu'
+import { CustomerTaskAssigneeSelect } from './CustomerTaskAssigneeSelect'
+import { CustomerTaskDueAtInput } from './CustomerTaskDueAtInput'
+import type { CustomerTasksContext } from './customerTaskFilters'
+import { CustomerTaskModal } from './CustomerTaskModal'
+import { CustomerTasksFilters } from './CustomerTasksFilters'
+import type { customerTasksLogicType } from './customerTasksLogic'
+import { CustomerTaskStatusSelect } from './CustomerTaskStatusSelect'
+
+export interface CustomerTasksTableProps {
+ logic: import('kea').BuiltLogic<customerTasksLogicType>
+ context: CustomerTasksContext
+ canCreate?: boolean
+ canViewAll?: boolean
+ embedded?: boolean
+}
+export function CustomerTasksTable({
+ logic,
+ context,
+ canCreate = false,
+ canViewAll = false,
+ embedded = true,
+}: CustomerTasksTableProps): JSX.Element {
+ const { taskPage, taskPageError, taskPageLoading, tasks, pagination, hasActiveFilters, taskSorting, timezone } =
+ useValues(logic)
+ const { loadTaskPage, openCreateModal, openEditModal, setTaskSorting } = useActions(logic)
+ if (taskPage === null && taskPageLoading) {
+ return <LemonSkeleton className="h-64 w-full" />
+ }
+ if (taskPageError && taskPage === null) {
+ return (
+ <LemonBanner type="error" action={{ children: 'Try again', onClick: loadTaskPage }}>
+ Couldn't load tasks. Try again.
+ </LemonBanner>
+ )
+ }
+ const columns: LemonTableColumns<CustomerTaskApi> = [
+ {
+ title: 'Task',
+ key: 'name',
+ width: '35%',
+ sorter: true,
+ render: (_, task) => (
+ <div className="flex min-w-0 flex-col gap-1 py-1">
+ <Link
+ subtle
+ className="font-semibold"
+ onClick={() => openEditModal(task)}
+ data-attr="customer-task-name"
+ >
+ {task.name}
+ </Link>
+ {task.description?.trim() && (
+ <span className="text-xs text-muted line-clamp-2">{task.description}</span>
+ )}
+ <div className="CustomerTasksTable__narrow-assignee">
+ <CustomerTaskAssigneeSelect task={task} logic={logic} />
+ </div>
+ </div>
+ ),
+ },
+ {
+ title: 'Status',
+ key: 'status',
+ width: 130,
+ sorter: true,
+ render: (_, task) => <CustomerTaskStatusSelect task={task} logic={logic} />,
+ },
+ ...(context === 'inbox'
+ ? [
+ {
+ title: 'Account',
+ key: 'account',
+ sorter: true as const,
+ render: (_: unknown, task: CustomerTaskApi) =>
+ task.account ? (
+ <Link to={urls.customerAnalyticsAccount(task.account.id, 'tasks')}>
+ {task.account.name}
+ </Link>
+ ) : (
+ <span className="text-muted">No account</span>
+ ),
+ },
+ ]
+ : []),
+ {
+ title: 'Assignee',
+ key: 'assigned_to',
+ className: 'CustomerTasksTable__assignee',
+ sorter: true,
+ render: (_, task) => <CustomerTaskAssigneeSelect task={task} logic={logic} />,
+ },
+ {
+ title: 'Due',
+ key: 'due_at',
+ width: 170,
+ sorter: true,
+ render: (_, task) => <CustomerTaskDueAtInput task={task} logic={logic} timezone={timezone} />,
+ },
+ {
+ title: 'Updated',
+ key: 'updated_at',
+ className: 'CustomerTasksTable__updated',
+ sorter: true,
+ render: (_, task) => <TZLabel time={task.updated_at} />,
+ },
+ {
+ title: '',
+ key: 'actions',
+ width: 48,
+ render: (_, task) => <CustomerTaskActionsMenu task={task} logic={logic} />,
+ },
+ ]
+ const empty = (
+ <div className="flex flex-col items-center gap-2 py-6">
+ <span>
+ {hasActiveFilters
+ ? 'No tasks match these filters.'
+ : context === 'account'
+ ? 'No open tasks for this account.'
+ : 'No open tasks are assigned to you.'}
+ </span>
+ {canCreate && !hasActiveFilters && (
+ <LemonButton type="primary" size="small" onClick={openCreateModal}>
+ Create task
+ </LemonButton>
+ )}
+ </div>
+ )
+ return (
+ <div className="CustomerTasksTable" data-attr="customer-tasks-table">
+ <div className="mb-4 flex items-center justify-between gap-2">
+ <CustomerTasksFilters logic={logic} context={context} canViewAll={canViewAll} />
+ {canCreate && (
+ <LemonButton type="primary" size="small" onClick={openCreateModal}>
+ New task
+ </LemonButton>
+ )}
+ </div>
+ {Boolean(taskPageError) && (
+ <LemonBanner className="mb-3" type="error" action={{ children: 'Try again', onClick: loadTaskPage }}>
+ Couldn't load tasks. Try again.
+ </LemonBanner>
+ )}
+ <LemonTable<CustomerTaskApi>
+ embedded={embedded}
+ dataSource={tasks}
+ columns={columns}
+ rowKey="id"
+ sorting={taskSorting}
+ onSort={setTaskSorting}
+ useURLForSorting={false}
+ noSortingCancellation
+ loading={taskPageLoading}
+ pagination={pagination}
+ emptyState={empty}
+ nouns={['task', 'tasks']}
+ tableLayout="fixed"
+ />
+ <CustomerTaskModal logic={logic} context={context} />
+ </div>
+ )
+}
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.test.ts b/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.test.ts
new file mode 100644
index 000000000000..ced1f3d5aa2c
--- /dev/null
+++ b/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.test.ts
@@ -0,0 +1,118 @@
+import type { CustomerTaskApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+
+import {
+ customerTaskDueBounds,
+ customerTaskEditDisabledReason,
+ customerTasksQuery,
+ defaultCustomerTaskFilters,
+ hasCustomerTaskFilters,
+} from './customerTaskFilters'
+import type { CustomerTaskDueFilter, CustomerTasksContext } from './customerTaskFilters'
+
+describe('customer task filter helpers', () => {
+ test.each([
+ [
+ 'account',
+ 20,
+ {
+ account_id: 'account-1',
+ statuses: 'open,in_progress',
+ archive_state: 'active',
+ ordering: 'due_at',
+ limit: 20,
+ offset: 0,
+ },
+ ],
+ [
+ 'inbox',
+ 50,
+ {
+ assigned_to: 'me',
+ statuses: 'open,in_progress',
+ archive_state: 'active',
+ ordering: 'due_at',
+ limit: 50,
+ offset: 0,
+ },
+ ],
+ ])('builds the documented %s defaults', (context, pageSize, expected) => {
+ const accountId = context === 'account' ? 'account-1' : undefined
+ expect(
+ customerTasksQuery(
+ defaultCustomerTaskFilters(context as CustomerTasksContext),
+ context as CustomerTasksContext,
+ accountId,
+ 1,
+ pageSize,
+ 'UTC'
+ )
+ ).toEqual(expected)
+ })
+
+ test('resets the active state to the context defaults', () => {
+ const filters = { ...defaultCustomerTaskFilters('inbox'), search: 'follow up', status: 'completed' as const }
+ expect(hasCustomerTaskFilters(filters, 'inbox')).toBe(true)
+ expect(hasCustomerTaskFilters(defaultCustomerTaskFilters('inbox'), 'inbox')).toBe(false)
+ })
+
+ test.each([
+ ['overdue', { due_before: '2026-09-02T10:00:00.000Z' }],
+ ['upcoming', { due_after: '2026-09-02T10:00:00.000Z' }],
+ ['no_due_date', { has_due_at: false }],
+ ])('translates the %s due filter', (due, expected) => {
+ expect(customerTaskDueBounds(due as CustomerTaskDueFilter, 'UTC', '2026-09-02T10:00:00.000Z')).toEqual(expected)
+ })
+
+ test('uses project timezone boundaries for Today', () => {
+ expect(customerTaskDueBounds('today', 'America/Los_Angeles', '2026-09-02T10:00:00.000Z')).toEqual({
+ due_after: '2026-09-02T07:00:00.000Z',
+ due_before: '2026-09-03T07:00:00.000Z',
+ })
+ })
+
+ test('keeps an assignee and omits due filters in account context', () => {
+ const query = customerTasksQuery(
+ { ...defaultCustomerTaskFilters('account'), assignee: 42, due: 'overdue' },
+ 'account',
+ 'account-1',
+ 1,
+ 20,
+ 'UTC'
+ )
+
+ expect(query).toMatchObject({ account_id: 'account-1', assigned_to: '42' })
+ expect(query).not.toHaveProperty('due_after')
+ expect(query).not.toHaveProperty('due_before')
+ expect(query).not.toHaveProperty('has_due_at')
+ })
+
+ test.each([
+ ['an archived task', { archived_at: '2026-09-02T11:00:00Z' }, 'Restore this task to edit it'],
+ ['a task the user cannot edit', { can_edit: false }, 'You cannot edit this task'],
+ ['an editable task', {}, undefined],
+ ])('resolves the edit blocker for %s', (_, overrides, expected) => {
+ const task = {
+ archived_at: null,
+ can_edit: true,
+ ...(overrides as Partial<CustomerTaskApi>),
+ } as CustomerTaskApi
+ expect(customerTaskEditDisabledReason(task)).toBe(expected)
+ })
+
+ test.each([
+ ['a resource viewer', true, 'unassigned'],
+ ['an assignment-only user', false, 'me'],
+ ])('keeps %s within their allowed assignee scope', (_, canViewAll, assignedTo) => {
+ expect(
+ customerTasksQuery(
+ { ...defaultCustomerTaskFilters('inbox'), assignee: 'unassigned' },
+ 'inbox',
+ undefined,
+ 1,
+ 50,
+ 'UTC',
+ canViewAll
+ )
+ ).toMatchObject({ assigned_to: assignedTo })
+ })
+})
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.ts b/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.ts
new file mode 100644
index 000000000000..a6456bb035f6
--- /dev/null
+++ b/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.ts
@@ -0,0 +1,205 @@
+import type { Sorting } from '@posthog/lemon-ui'
+
+import { dayjs, dayjsLocalToTimezone, dayjsNowInTimezone } from 'lib/dayjs'
+
+import type {
+ CustomerTaskApi,
+ CustomerTaskStatusEnumApi,
+ CustomerTasksListArchiveState,
+ CustomerTasksListParams,
+} from 'products/customer_analytics/frontend/generated/api.schemas'
+
+export type CustomerTasksContext = 'account' | 'inbox'
+export type CustomerTaskStatusFilter = 'open' | 'completed' | 'canceled' | 'all'
+export type CustomerTaskAssigneeFilter = 'any' | 'me' | 'unassigned' | number
+export type CustomerTaskDueFilter = 'any' | 'overdue' | 'today' | 'upcoming' | 'no_due_date'
+export type CustomerTaskAccountFilter = { id: string; name: string }
+const CUSTOMER_TASK_ORDERINGS = [
+ 'name',
+ '-name',
+ 'status',
+ '-status',
+ 'assigned_to',
+ '-assigned_to',
+ 'due_at',
+ '-due_at',
+ 'updated_at',
+ '-updated_at',
+ 'account',
+ '-account',
+] as const satisfies readonly NonNullable<CustomerTasksListParams['ordering']>[]
+
+export type CustomerTaskOrdering = (typeof CUSTOMER_TASK_ORDERINGS)[number]
+
+export const DEFAULT_CUSTOMER_TASK_ORDERING: CustomerTaskOrdering = 'due_at'
+
+export type CustomerTaskFilters = {
+ search: string
+ status: CustomerTaskStatusFilter
+ assignee: CustomerTaskAssigneeFilter
+ archiveState: CustomerTasksListArchiveState
+ account: CustomerTaskAccountFilter | null
+ due: CustomerTaskDueFilter
+}
+
+const CUSTOMER_TASK_SORTING: Record<CustomerTaskOrdering, Sorting> = {
+ name: { columnKey: 'name', order: 1 },
+ '-name': { columnKey: 'name', order: -1 },
+ status: { columnKey: 'status', order: 1 },
+ '-status': { columnKey: 'status', order: -1 },
+ assigned_to: { columnKey: 'assigned_to', order: 1 },
+ '-assigned_to': { columnKey: 'assigned_to', order: -1 },
+ due_at: { columnKey: 'due_at', order: 1 },
+ '-due_at': { columnKey: 'due_at', order: -1 },
+ updated_at: { columnKey: 'updated_at', order: 1 },
+ '-updated_at': { columnKey: 'updated_at', order: -1 },
+ account: { columnKey: 'account', order: 1 },
+ '-account': { columnKey: 'account', order: -1 },
+}
+
+export const CUSTOMER_TASK_STATUS_OPTIONS: readonly { value: CustomerTaskStatusFilter; label: string }[] = [
+ { value: 'open', label: 'Open' },
+ { value: 'completed', label: 'Completed' },
+ { value: 'canceled', label: 'Canceled' },
+ { value: 'all', label: 'All' },
+]
+export const CUSTOMER_TASK_ARCHIVE_OPTIONS: readonly { value: CustomerTasksListArchiveState; label: string }[] = [
+ { value: 'active', label: 'Active' },
+ { value: 'archived', label: 'Archived' },
+ { value: 'all', label: 'All' },
+]
+export const CUSTOMER_TASK_DUE_OPTIONS: readonly { value: CustomerTaskDueFilter; label: string }[] = [
+ { value: 'any', label: 'Any time' },
+ { value: 'overdue', label: 'Overdue' },
+ { value: 'today', label: 'Today' },
+ { value: 'upcoming', label: 'Upcoming' },
+ { value: 'no_due_date', label: 'No due date' },
+]
+export const CUSTOMER_TASK_STATUS_TRANSITIONS: Readonly<
+ Record<CustomerTaskStatusEnumApi, readonly CustomerTaskStatusEnumApi[]>
+> = {
+ open: ['in_progress', 'completed', 'canceled'],
+ in_progress: ['open', 'completed', 'canceled'],
+ completed: ['open'],
+ canceled: ['open'],
+}
+
+// The API refuses to update an archived task, so every write control shares this reason.
+export function customerTaskEditDisabledReason(task: CustomerTaskApi): string | undefined {
+ if (task.archived_at) {
+ return 'Restore this task to edit it'
+ }
+ if (!task.can_edit) {
+ return 'You cannot edit this task'
+ }
+ return undefined
+}
+
+export function customerTaskOrderingToSorting(ordering: CustomerTaskOrdering): Sorting {
+ return CUSTOMER_TASK_SORTING[ordering]
+}
+
+export function customerTaskSortingToOrdering(sorting: Sorting | null): CustomerTaskOrdering | null {
+ if (!sorting) {
+ return null
+ }
+ switch (sorting.columnKey) {
+ case 'name':
+ return sorting.order === -1 ? '-name' : 'name'
+ case 'status':
+ return sorting.order === -1 ? '-status' : 'status'
+ case 'assigned_to':
+ return sorting.order === -1 ? '-assigned_to' : 'assigned_to'
+ case 'due_at':
+ return sorting.order === -1 ? '-due_at' : 'due_at'
+ case 'updated_at':
+ return sorting.order === -1 ? '-updated_at' : 'updated_at'
+ case 'account':
+ return sorting.order === -1 ? '-account' : 'account'
+ default:
+ return null
+ }
+}
+
+export function defaultCustomerTaskFilters(context: CustomerTasksContext): CustomerTaskFilters {
+ return {
+ search: '',
+ status: 'open',
+ assignee: context === 'inbox' ? 'me' : 'any',
+ archiveState: 'active',
+ account: null,
+ due: 'any',
+ }
+}
+export function hasCustomerTaskFilters(filters: CustomerTaskFilters, context: CustomerTasksContext): boolean {
+ const defaults = defaultCustomerTaskFilters(context)
+ return JSON.stringify(filters) !== JSON.stringify(defaults)
+}
+export function customerTaskDueBounds(
+ due: CustomerTaskDueFilter,
+ timezone: string,
+ now?: string
+): Pick<CustomerTasksListParams, 'due_after' | 'due_before' | 'has_due_at'> {
+ if (due === 'any') {
+ return {}
+ }
+ if (due === 'no_due_date') {
+ return { has_due_at: false }
+ }
+ const current = now ? dayjs(now).tz(timezone) : dayjsNowInTimezone(timezone)
+ const currentInstant = now ? dayjs(now) : dayjsNowInTimezone(timezone).tz(timezone, true)
+ if (due === 'overdue') {
+ return { due_before: currentInstant.toISOString() }
+ }
+ if (due === 'upcoming') {
+ return { due_after: currentInstant.toISOString() }
+ }
+ const start = current.startOf('day').format('YYYY-MM-DDTHH:mm:ss.SSS')
+ const end = current.add(1, 'day').startOf('day').format('YYYY-MM-DDTHH:mm:ss.SSS')
+ return {
+ due_after: dayjsLocalToTimezone(start, timezone).toISOString(),
+ due_before: dayjsLocalToTimezone(end, timezone).toISOString(),
+ }
+}
+export function customerTasksQuery(
+ filters: CustomerTaskFilters,
+ context: CustomerTasksContext,
+ accountId: string | undefined,
+ page: number,
+ pageSize: number,
+ timezone: string,
+ canViewAll = true,
+ ordering: CustomerTaskOrdering = DEFAULT_CUSTOMER_TASK_ORDERING
+): CustomerTasksListParams {
+ 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),
+ statuses:
+ filters.status === 'all' ? undefined : filters.status === 'open' ? 'open,in_progress' : filters.status,
+ archive_state: filters.archiveState,
+ ordering,
+ limit: pageSize,
+ offset: (page - 1) * pageSize,
+ ...customerTaskDueBounds(filters.due, timezone),
+ }
+ if (context === 'account') {
+ delete query.due_after
+ delete query.due_before
+ delete query.has_due_at
+ }
+ return query
+}
+
+export function customerTasksPersistencePrefix(teamId: number, userId: number): string {
+ return `${teamId}_${userId}_customer_analytics_tasks__`
+}
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.test.ts b/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.test.ts
new file mode 100644
index 000000000000..c92f3ef09b0f
--- /dev/null
+++ b/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.test.ts
@@ -0,0 +1,266 @@
+import { MOCK_DEFAULT_USER } from 'lib/api.mock'
+
+import { expectLogic } from 'kea-test-utils'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { ApiError } from 'lib/api-error'
+import { userLogic } from 'scenes/userLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import {
+ accountsList,
+ customerTasksCreate,
+ customerTasksList,
+ customerTasksPartialUpdate,
+} from 'products/customer_analytics/frontend/generated/api'
+import type { CustomerTaskApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+
+import { customerTasksPersistencePrefix } from './customerTaskFilters'
+import { customerTasksLogic } from './customerTasksLogic'
+
+jest.mock('products/customer_analytics/frontend/generated/api', () => ({
+ accountsList: jest.fn(),
+ customerTasksArchiveCreate: jest.fn(),
+ customerTasksCreate: jest.fn(),
+ customerTasksList: jest.fn(),
+ customerTasksPartialUpdate: jest.fn(),
+ customerTasksRestoreCreate: jest.fn(),
+}))
+
+const mockCreate = customerTasksCreate as jest.MockedFunction<typeof customerTasksCreate>
+const mockList = customerTasksList as jest.MockedFunction<typeof customerTasksList>
+const mockAccounts = accountsList as jest.MockedFunction<typeof accountsList>
+const mockUpdate = customerTasksPartialUpdate as jest.MockedFunction<typeof customerTasksPartialUpdate>
+
+function task(canEdit = true): CustomerTaskApi {
+ return {
+ id: 'task-1',
+ account: null,
+ name: 'Follow up',
+ description: null,
+ status: 'open',
+ assigned_to: null,
+ due_at: null,
+ completed_at: null,
+ completed_by: null,
+ created_by: null,
+ archived_at: null,
+ created_at: '2026-09-02T10:00:00Z',
+ updated_at: '2026-09-02T10:00:00Z',
+ can_edit: canEdit,
+ can_restore: false,
+ }
+}
+
+describe('customerTasksLogic', () => {
+ let logic: ReturnType<typeof customerTasksLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ localStorage.clear()
+ mockCreate.mockResolvedValue(task())
+ mockList.mockResolvedValue({ count: 0, next: null, previous: null, results: [] })
+ mockAccounts.mockResolvedValue({ count: 0, next: null, previous: null, results: [] })
+ mockUpdate.mockResolvedValue(task())
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ localStorage.clear()
+ })
+
+ test.each([
+ ['account', 'account-1', 20, { account_id: 'account-1' }],
+ ['inbox', undefined, 50, { assigned_to: 'me' }],
+ ])('loads %s with its page size and default filters', async (context, accountId, pageSize, filter) => {
+ logic = customerTasksLogic({ context: context as 'account' | 'inbox', accountId })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(mockList).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ ...filter,
+ statuses: 'open,in_progress',
+ archive_state: 'active',
+ ordering: 'due_at',
+ limit: pageSize,
+ offset: 0,
+ })
+ )
+ })
+
+ test('creates a task for the current account without exposing a different account', async () => {
+ logic = customerTasksLogic({ context: 'account', accountId: 'account-1' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.openCreateModal()
+ logic.actions.setDraftName('Follow up')
+ logic.actions.submitModal()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockCreate).toHaveBeenCalledWith(expect.any(String), {
+ account_id: 'account-1',
+ name: 'Follow up',
+ description: null,
+ assigned_to_id: null,
+ due_at: null,
+ })
+ })
+
+ test('keeps the create form and its drafts when the create fails', async () => {
+ const toast = jest.spyOn(lemonToast, 'error').mockImplementation(() => '' as never)
+ mockCreate.mockRejectedValueOnce(
+ new ApiError(undefined, 400, undefined, { assigned_to_id: 'Select a member of this project.' })
+ )
+ logic = customerTasksLogic({ context: 'account', accountId: 'account-1' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.openCreateModal()
+ logic.actions.setDraftName('Follow up')
+ logic.actions.setDraftDescription('Ask about the renewal')
+ logic.actions.submitModal()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.modalOpen).toBe(true)
+ expect(logic.values.draftName).toBe('Follow up')
+ expect(logic.values.draftDescription).toBe('Ask about the renewal')
+ expect(toast).toHaveBeenCalledWith('Select a member of this project.')
+ toast.mockRestore()
+ })
+
+ test.each([
+ ['assigns', null, 'account-1'],
+ ['removes', { id: 'account-1', name: 'Acme' }, null],
+ ])('%s an account while editing a task', async (_, account, selectedAccountId) => {
+ const originalTask = { ...task(), account }
+ mockList.mockResolvedValueOnce({ count: 1, next: null, previous: null, results: [originalTask] })
+ logic = customerTasksLogic({ context: 'inbox', canViewAll: true })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.openEditModal(originalTask)
+ expect(logic.values.draftAccount).toEqual(account)
+ logic.actions.setDraftAccount(selectedAccountId ? { id: selectedAccountId, name: 'Acme' } : null)
+ logic.actions.submitModal()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockUpdate).toHaveBeenCalledWith(expect.any(String), originalTask.id, {
+ account_id: selectedAccountId,
+ })
+ })
+
+ test('assigns an inbox draft to the current user under the default filter', async () => {
+ logic = customerTasksLogic({ context: 'inbox', canViewAll: true })
+ logic.mount()
+ userLogic.actions.loadUserSuccess(MOCK_DEFAULT_USER)
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.openCreateModal()
+
+ expect(logic.values.draftAssignedTo).toMatchObject({
+ id: MOCK_DEFAULT_USER.id,
+ email: MOCK_DEFAULT_USER.email,
+ })
+ logic.actions.setDraftAssignedTo(null)
+ expect(logic.values.draftAssignedTo).toBeNull()
+ })
+
+ test('persists inbox filters for one team and user, then resets them to defaults', async () => {
+ const prefix = customerTasksPersistencePrefix(1, 42)
+ logic = customerTasksLogic({ context: 'inbox', canViewAll: true, persistPrefix: prefix })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setFilters({ status: 'completed', assignee: 'unassigned' })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.filters).toMatchObject({ status: 'completed', assignee: 'unassigned' })
+ logic.unmount()
+
+ const otherUserLogic = customerTasksLogic({
+ context: 'inbox',
+ canViewAll: true,
+ persistPrefix: customerTasksPersistencePrefix(1, 7),
+ })
+ otherUserLogic.mount()
+ await expectLogic(otherUserLogic).toFinishAllListeners()
+ expect(otherUserLogic.values.filters).toMatchObject({ status: 'open', assignee: 'me' })
+ otherUserLogic.unmount()
+
+ logic = customerTasksLogic({ context: 'inbox', canViewAll: true, persistPrefix: prefix })
+ logic.mount()
+ expect(logic.values.filters).toMatchObject({ status: 'completed', assignee: 'unassigned' })
+ logic.actions.resetFilters()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.filters).toMatchObject({ status: 'open', assignee: 'me' })
+ expect(JSON.stringify(localStorage)).not.toContain('completed')
+ })
+
+ test('reloads the server-sorted page after setting a due date', async () => {
+ const originalTask = task()
+ const updatedTask = { ...originalTask, due_at: '2026-09-03T12:00:00Z' }
+ const otherTask = { ...task(), id: 'task-2', name: 'Other task' }
+ mockList.mockResolvedValueOnce({ count: 1, next: null, previous: null, results: [originalTask] })
+ mockUpdate.mockResolvedValueOnce(updatedTask)
+ logic = customerTasksLogic({ context: 'account', accountId: 'account-1' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ mockList.mockClear()
+ mockList.mockResolvedValueOnce({ count: 2, next: null, previous: null, results: [updatedTask, otherTask] })
+
+ logic.actions.updateTask(originalTask.id, { due_at: updatedTask.due_at })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockList).toHaveBeenCalledTimes(1)
+ expect(logic.values.tasks).toEqual([updatedTask, otherTask])
+ })
+
+ test.each([
+ ['the field the server rejected', { assigned_to_id: 'Select a member of this project.' }, 400],
+ ['the detail the server sent', { detail: 'Restore this task before editing it.' }, 409],
+ ])('reports %s instead of asking for a retry', async (_name, body, status) => {
+ const toast = jest.spyOn(lemonToast, 'error').mockImplementation(() => '' as never)
+ mockList.mockResolvedValueOnce({ count: 1, next: null, previous: null, results: [task()] })
+ mockUpdate.mockRejectedValueOnce(new ApiError(undefined, status, undefined, body))
+ logic = customerTasksLogic({ context: 'account', accountId: 'account-1' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.updateTask('task-1', { assigned_to_id: 9 })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(toast).toHaveBeenCalledWith(Object.values(body)[0])
+ toast.mockRestore()
+ })
+
+ test('does not submit an unchanged modal, an uneditable task, or an archived task', async () => {
+ const accountTask = { ...task(), account: { id: 'account-1', name: 'Acme' } }
+ mockList.mockResolvedValueOnce({ count: 1, next: null, previous: null, results: [accountTask] })
+ logic = customerTasksLogic({ context: 'account', accountId: 'account-1' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.openEditModal(logic.values.tasks[0])
+ logic.actions.submitModal()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(mockUpdate).not.toHaveBeenCalled()
+ expect(logic.values.modalOpen).toBe(false)
+
+ mockList.mockResolvedValueOnce({ count: 1, next: null, previous: null, results: [task(false)] })
+ logic.actions.loadTaskPage()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.updateTask('task-1', { name: 'Changed' })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(mockUpdate).not.toHaveBeenCalled()
+
+ const archivedTask = { ...task(), archived_at: '2026-09-02T11:00:00Z' }
+ mockList.mockResolvedValueOnce({ count: 1, next: null, previous: null, results: [archivedTask] })
+ logic.actions.loadTaskPage()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.updateTask('task-1', { name: 'Changed' })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(mockUpdate).not.toHaveBeenCalled()
+ })
+})
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.ts b/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.ts
new file mode 100644
index 000000000000..08b6464caee2
--- /dev/null
+++ b/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.ts
@@ -0,0 +1,511 @@
+import {
+ MakeLogicType,
+ LogicWrapper,
+ actions,
+ afterMount,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ reducers,
+ selectors,
+} from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { lemonToast, type PaginationManual, type Sorting } from '@posthog/lemon-ui'
+
+import { ApiError } from 'lib/api-error'
+import { teamLogic } from 'scenes/teamLogic'
+import { userLogic } from 'scenes/userLogic'
+
+import type { UserType } from '~/types'
+
+import {
+ accountsList,
+ customerTasksArchiveCreate,
+ customerTasksCreate,
+ customerTasksList,
+ customerTasksPartialUpdate,
+ customerTasksRestoreCreate,
+} from 'products/customer_analytics/frontend/generated/api'
+import type {
+ AccountApi,
+ CustomerTaskApi,
+ CustomerTaskCreateApi,
+ CustomerTaskPageApi,
+ CustomerTaskUserApi,
+ PaginatedAccountListApi,
+ PatchedCustomerTaskUpdateApi,
+} from 'products/customer_analytics/frontend/generated/api.schemas'
+
+import {
+ customerTasksQuery,
+ DEFAULT_CUSTOMER_TASK_ORDERING,
+ defaultCustomerTaskFilters,
+ hasCustomerTaskFilters,
+ type CustomerTaskAccountFilter,
+ type CustomerTaskFilters,
+ type CustomerTaskOrdering,
+ type CustomerTasksContext,
+ customerTaskOrderingToSorting,
+ customerTaskSortingToOrdering,
+} from './customerTaskFilters'
+
+const ACCOUNT_PAGE_SIZE = 20
+const INBOX_PAGE_SIZE = 50
+const ACCOUNT_OPTIONS_LIMIT = 50
+
+export interface CustomerTasksLogicProps {
+ context: CustomerTasksContext
+ accountId?: string
+ canViewAll?: boolean
+ persistPrefix?: string
+}
+export interface customerTasksLogicValues {
+ accountOptions: AccountApi[]
+ accountOptionsResponse: PaginatedAccountListApi | null
+ accountOptionsResponseLoading: boolean
+ accountFilterOpen: boolean
+ currentTeamId: number | null
+ filters: CustomerTaskFilters
+ hasActiveFilters: boolean
+ modalOpen: boolean
+ modalTask: CustomerTaskApi | null
+ mutationKeys: Record<string, boolean>
+ ordering: CustomerTaskOrdering
+ page: number
+ pageSize: number
+ pagination: PaginationManual
+ taskPage: CustomerTaskPageApi | null
+ taskPageError: unknown
+ taskPageLoading: boolean
+ taskSorting: Sorting
+ tasks: CustomerTaskApi[]
+ timezone: string
+ draftName: string
+ draftDescription: string
+ draftAccount: CustomerTaskAccountFilter | null
+ draftAssignedTo: CustomerTaskUserApi | null
+ draftDueAt: string | null
+ user: UserType | null
+}
+export interface customerTasksLogicActions {
+ closeModal: () => void
+ createTask: (task: CustomerTaskCreateApi) => { task: CustomerTaskCreateApi }
+ loadAccountOptions: (payload: { query: string }) => { query: string }
+ loadTaskPage: () => { value: true }
+ mutationFinished: (key: string) => { key: string }
+ mutationStarted: (key: string) => { key: string }
+ openCreateModal: () => void
+ openEditModal: (task: CustomerTaskApi) => { task: CustomerTaskApi }
+ resetFilters: () => void
+ restoreTask: (taskId: string) => { taskId: string }
+ archiveTask: (taskId: string) => { taskId: string }
+ setAccountFilter: (account: CustomerTaskAccountFilter | null) => { account: CustomerTaskAccountFilter | null }
+ setAccountFilterOpen: (open: boolean) => { open: boolean }
+ setFilters: (filters: Partial<CustomerTaskFilters>) => { filters: Partial<CustomerTaskFilters> }
+ setTaskOrdering: (ordering: CustomerTaskOrdering) => { ordering: CustomerTaskOrdering }
+ setTaskSorting: (sorting: Sorting | null) => { sorting: Sorting | null }
+ setPage: (page: number) => { page: number }
+ setSearch: (search: string) => { search: string }
+ setDraftAccount: (account: CustomerTaskAccountFilter | null) => { account: CustomerTaskAccountFilter | null }
+ setDraftAssignedTo: (assignedTo: CustomerTaskUserApi | null) => { assignedTo: CustomerTaskUserApi | null }
+ setDraftDescription: (description: string) => { description: string }
+ setDraftDueAt: (dueAt: string | null) => { dueAt: string | null }
+ setDraftName: (name: string) => { name: string }
+ submitModal: () => void
+ updateTask: (
+ taskId: string,
+ patch: PatchedCustomerTaskUpdateApi
+ ) => { taskId: string; patch: PatchedCustomerTaskUpdateApi }
+}
+export type customerTasksLogicType = MakeLogicType<
+ customerTasksLogicValues,
+ customerTasksLogicActions,
+ CustomerTasksLogicProps
+>
+
+// A rejected task write answers with the message a person needs, either as `detail` or against the
+// field at fault, so show that instead of asking for a retry the server will refuse again.
+function taskWriteFailureMessage(error: unknown, fallback: string): string {
+ if (error instanceof ApiError) {
+ const body = error.data as Record<string, unknown> | null | undefined
+ for (const candidate of [error.detail, body?.assigned_to_id, body?.status]) {
+ if (typeof candidate === 'string' && candidate.trim()) {
+ return candidate
+ }
+ }
+ }
+ return fallback
+}
+
+export const customerTasksLogic: LogicWrapper<customerTasksLogicType> = kea<customerTasksLogicType>([
+ props({} as CustomerTasksLogicProps),
+ key((p) => 'customer-tasks-' + p.context + '-' + (p.accountId ?? p.persistPrefix ?? 'all')),
+ path(['products', 'customer_analytics', 'frontend', 'components', 'CustomerTasks', 'customerTasksLogic']),
+ connect(() => ({ values: [teamLogic, ['currentTeamId', 'timezone'], userLogic, ['user']] })),
+ actions({
+ loadTaskPage: true,
+ loadAccountOptions: (payload: { query: string }) => payload,
+ setFilters: (filters: Partial<CustomerTaskFilters>) => ({ filters }),
+ setTaskOrdering: (ordering: CustomerTaskOrdering) => ({ ordering }),
+ setTaskSorting: (sorting: Sorting | null) => ({ sorting }),
+ setSearch: (search: string) => ({ search }),
+ setAccountFilter: (account: CustomerTaskAccountFilter | null) => ({ account }),
+ setAccountFilterOpen: (open: boolean) => ({ open }),
+ setPage: (page: number) => ({ page }),
+ resetFilters: () => ({}),
+ openCreateModal: () => ({}),
+ openEditModal: (task: CustomerTaskApi) => ({ task }),
+ closeModal: () => ({}),
+ setDraftName: (name: string) => ({ name }),
+ setDraftDescription: (description: string) => ({ description }),
+ setDraftAccount: (account: CustomerTaskAccountFilter | null) => ({ account }),
+ setDraftAssignedTo: (assignedTo: CustomerTaskUserApi | null) => ({ assignedTo }),
+ setDraftDueAt: (dueAt: string | null) => ({ dueAt }),
+ submitModal: () => ({}),
+ createTask: (task: CustomerTaskCreateApi) => ({ task }),
+ updateTask: (taskId: string, patch: PatchedCustomerTaskUpdateApi) => ({ taskId, patch }),
+ archiveTask: (taskId: string) => ({ taskId }),
+ restoreTask: (taskId: string) => ({ taskId }),
+ mutationStarted: (key: string) => ({ key }),
+ mutationFinished: (key: string) => ({ key }),
+ }),
+ loaders(({ props, values }) => ({
+ taskPage: [
+ null as CustomerTaskPageApi | null,
+ {
+ loadTaskPage: async (_, breakpoint) => {
+ await breakpoint(250)
+ 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
+ )
+ )
+ breakpoint()
+ return result
+ },
+ },
+ ],
+ accountOptionsResponse: [
+ null as PaginatedAccountListApi | null,
+ {
+ loadAccountOptions: async ({ query }: { query: string }, breakpoint) => {
+ await breakpoint(300)
+ if (values.currentTeamId === null) {
+ return null
+ }
+ const result = await accountsList(String(values.currentTeamId), {
+ search: query || undefined,
+ limit: ACCOUNT_OPTIONS_LIMIT,
+ })
+ breakpoint()
+ return result
+ },
+ },
+ ],
+ })),
+ reducers(({ props }) => {
+ const persist =
+ props.context === 'inbox' && props.persistPrefix ? { persist: true, prefix: props.persistPrefix } : {}
+ return {
+ filters: [
+ defaultCustomerTaskFilters(props.context),
+ persist,
+ {
+ setFilters: (s: CustomerTaskFilters, a: { filters: Partial<CustomerTaskFilters> }) => ({
+ ...s,
+ ...a.filters,
+ }),
+ setSearch: (s: CustomerTaskFilters, a: { search: string }) => ({ ...s, search: a.search }),
+ setAccountFilter: (s: CustomerTaskFilters, a: { account: CustomerTaskAccountFilter | null }) => ({
+ ...s,
+ account: a.account,
+ }),
+ resetFilters: () => defaultCustomerTaskFilters(props.context),
+ },
+ ],
+ ordering: [DEFAULT_CUSTOMER_TASK_ORDERING, { setTaskOrdering: (_, { ordering }) => ordering }],
+ page: [
+ 1,
+ {
+ setPage: (_: number, a: { page: number }) => a.page,
+ setFilters: () => 1,
+ setSearch: () => 1,
+ setAccountFilter: () => 1,
+ resetFilters: () => 1,
+ setTaskOrdering: () => 1,
+ },
+ ],
+ accountFilterOpen: [false, { setAccountFilterOpen: (_, { open }) => open }],
+ mutationKeys: [
+ {} as Record<string, boolean>,
+ {
+ mutationStarted: (s: Record<string, boolean>, a: { key: string }) => ({ ...s, [a.key]: true }),
+ mutationFinished: (s: Record<string, boolean>, a: { key: string }) => {
+ const n = { ...s }
+ delete n[a.key]
+ return n
+ },
+ },
+ ],
+ modalOpen: [
+ false,
+ {
+ openCreateModal: () => true,
+ openEditModal: () => true,
+ closeModal: () => false,
+ },
+ ],
+ modalTask: [
+ null as CustomerTaskApi | null,
+ {
+ openCreateModal: () => null,
+ openEditModal: (_: CustomerTaskApi | null, a: { task: CustomerTaskApi }) => a.task,
+ closeModal: () => null,
+ },
+ ],
+ draftName: [
+ '',
+ {
+ openCreateModal: () => '',
+ openEditModal: (_: string, a: { task: CustomerTaskApi }) => a.task.name,
+ setDraftName: (_: string, a: { name: string }) => a.name,
+ closeModal: () => '',
+ },
+ ],
+ draftDescription: [
+ '',
+ {
+ openCreateModal: () => '',
+ openEditModal: (_: string, a: { task: CustomerTaskApi }) => a.task.description ?? '',
+ setDraftDescription: (_: string, a: { description: string }) => a.description,
+ closeModal: () => '',
+ },
+ ],
+ draftAccount: [
+ null as CustomerTaskAccountFilter | null,
+ {
+ openCreateModal: () => null,
+ openEditModal: (_: CustomerTaskAccountFilter | null, a: { task: CustomerTaskApi }) =>
+ a.task.account,
+ setDraftAccount: (
+ _: CustomerTaskAccountFilter | null,
+ a: { account: CustomerTaskAccountFilter | null }
+ ) => a.account,
+ closeModal: () => null,
+ },
+ ],
+ draftAssignedTo: [
+ null as CustomerTaskUserApi | null,
+ {
+ openCreateModal: () => null,
+ openEditModal: (_: CustomerTaskUserApi | null, a: { task: CustomerTaskApi }) => a.task.assigned_to,
+ setDraftAssignedTo: (
+ _: CustomerTaskUserApi | null,
+ a: { assignedTo: CustomerTaskUserApi | null }
+ ) => a.assignedTo,
+ closeModal: () => null,
+ },
+ ],
+ draftDueAt: [
+ null as string | null,
+ {
+ openCreateModal: () => null,
+ openEditModal: (_: string | null, a: { task: CustomerTaskApi }) => a.task.due_at,
+ setDraftDueAt: (_: string | null, a: { dueAt: string | null }) => a.dueAt,
+ closeModal: () => null,
+ },
+ ],
+ }
+ }),
+ selectors(({ actions, props }) => ({
+ tasks: [
+ (s) => [s.taskPage],
+ (p: CustomerTaskPageApi | null): CustomerTaskApi[] => (p?.results ? [...p.results] : []),
+ ],
+ accountOptions: [
+ (s) => [s.accountOptionsResponse],
+ (p: PaginatedAccountListApi | null): AccountApi[] => p?.results ?? [],
+ ],
+ hasActiveFilters: [
+ (s) => [s.filters],
+ (f: CustomerTaskFilters): boolean => hasCustomerTaskFilters(f, props.context),
+ ],
+ taskSorting: [(s) => [s.ordering], (ordering: CustomerTaskOrdering) => customerTaskOrderingToSorting(ordering)],
+ pageSize: [() => [], (): number => (props.context === 'account' ? ACCOUNT_PAGE_SIZE : INBOX_PAGE_SIZE)],
+ pagination: [
+ (s) => [s.page, s.taskPage],
+ (page: number, p: CustomerTaskPageApi | null): PaginationManual => ({
+ controlled: true,
+ pageSize: props.context === 'account' ? ACCOUNT_PAGE_SIZE : INBOX_PAGE_SIZE,
+ currentPage: page,
+ entryCount: p?.count ?? 0,
+ onBackward: () => actions.setPage(page - 1),
+ onForward: () => actions.setPage(page + 1),
+ }),
+ ],
+ })),
+ listeners(({ actions, props, values }) => ({
+ setFilters: () => actions.loadTaskPage(),
+ setSearch: () => actions.loadTaskPage(),
+ setAccountFilter: () => actions.loadTaskPage(),
+ setPage: () => actions.loadTaskPage(),
+ setTaskOrdering: () => actions.loadTaskPage(),
+ setTaskSorting: ({ sorting }) => {
+ const ordering = customerTaskSortingToOrdering(sorting)
+ if (ordering) {
+ actions.setTaskOrdering(ordering)
+ }
+ },
+ resetFilters: () => actions.loadTaskPage(),
+ openCreateModal: () => {
+ if (props.context === 'inbox' && values.filters.assignee === 'me' && values.user) {
+ actions.setDraftAssignedTo({
+ id: values.user.id,
+ email: values.user.email,
+ first_name: values.user.first_name,
+ last_name: values.user.last_name ?? '',
+ })
+ }
+ },
+ submitModal: () => {
+ if (values.mutationKeys.create || (values.modalTask && values.mutationKeys[values.modalTask.id])) {
+ return
+ }
+ const accountId =
+ props.context === 'account' ? (props.accountId ?? null) : (values.draftAccount?.id ?? null)
+ const description = values.draftDescription || null
+ const assignedToId = values.draftAssignedTo?.id ?? null
+ if (values.modalTask) {
+ const patch: PatchedCustomerTaskUpdateApi = {}
+ if (accountId !== (values.modalTask.account?.id ?? null)) {
+ patch.account_id = accountId
+ }
+ if (values.draftName !== values.modalTask.name) {
+ patch.name = values.draftName
+ }
+ if (values.draftDescription !== (values.modalTask.description ?? '')) {
+ patch.description = description
+ }
+ if (assignedToId !== (values.modalTask.assigned_to?.id ?? null)) {
+ patch.assigned_to_id = assignedToId
+ }
+ if (values.draftDueAt !== values.modalTask.due_at) {
+ patch.due_at = values.draftDueAt
+ }
+ if (Object.keys(patch).length === 0) {
+ actions.closeModal()
+ return
+ }
+ actions.updateTask(values.modalTask.id, patch)
+ } else {
+ actions.createTask({
+ account_id: accountId,
+ name: values.draftName,
+ description,
+ assigned_to_id: assignedToId,
+ due_at: values.draftDueAt,
+ })
+ }
+ },
+ createTask: async ({ task }: { task: CustomerTaskCreateApi }) => {
+ if (values.mutationKeys.create || !task.name.trim() || values.currentTeamId === null) {
+ return
+ }
+ actions.mutationStarted('create')
+ try {
+ await customerTasksCreate(String(values.currentTeamId), { ...task, name: task.name.trim() })
+ actions.mutationFinished('create')
+ actions.closeModal()
+ actions.loadTaskPage()
+ } catch (error) {
+ actions.mutationFinished('create')
+ lemonToast.error(taskWriteFailureMessage(error, 'Could not create the task. Try again.'))
+ }
+ },
+ updateTask: async ({ taskId, patch }: { taskId: string; patch: PatchedCustomerTaskUpdateApi }) => {
+ const current = values.tasks.find((task) => task.id === taskId)
+ if (current && (!current.can_edit || current.archived_at)) {
+ return
+ }
+ const changed = current
+ ? Object.entries(patch).some(
+ ([key, value]) =>
+ (key === 'assigned_to_id'
+ ? (current.assigned_to?.id ?? null)
+ : key === 'account_id'
+ ? (current.account?.id ?? null)
+ : current[key as keyof CustomerTaskApi]) !== value
+ )
+ : true
+ if (!changed || values.mutationKeys[taskId] || values.currentTeamId === null) {
+ return
+ }
+ actions.mutationStarted(taskId)
+ try {
+ await customerTasksPartialUpdate(String(values.currentTeamId), taskId, patch)
+ actions.mutationFinished(taskId)
+ actions.closeModal()
+ actions.loadTaskPage()
+ } catch (error) {
+ actions.mutationFinished(taskId)
+ lemonToast.error(taskWriteFailureMessage(error, 'Could not save the task. Try again.'))
+ }
+ },
+ archiveTask: async ({ taskId }: { taskId: string }) => {
+ if (values.tasks.find((task) => task.id === taskId)?.can_edit === false) {
+ return
+ }
+ if (values.mutationKeys[taskId] || values.currentTeamId === null) {
+ return
+ }
+ actions.mutationStarted(taskId)
+ try {
+ await customerTasksArchiveCreate(String(values.currentTeamId), taskId)
+ actions.mutationFinished(taskId)
+ actions.loadTaskPage()
+ } catch {
+ actions.mutationFinished(taskId)
+ lemonToast.error('Could not archive the task. Try again.')
+ }
+ },
+ restoreTask: async ({ taskId }: { taskId: string }) => {
+ const current = values.tasks.find((task) => task.id === taskId)
+ if (current && !current.can_restore) {
+ return
+ }
+ if (values.mutationKeys[taskId] || values.currentTeamId === null) {
+ return
+ }
+ actions.mutationStarted(taskId)
+ try {
+ await customerTasksRestoreCreate(String(values.currentTeamId), taskId)
+ actions.mutationFinished(taskId)
+ actions.loadTaskPage()
+ } catch {
+ actions.mutationFinished(taskId)
+ lemonToast.error('Could not restore the task. Try again.')
+ }
+ },
+ })),
+ afterMount(({ actions, props }) => {
+ actions.loadTaskPage()
+ if (props.context === 'inbox') {
+ actions.loadAccountOptions({ query: '' })
+ }
+ }),
+])
diff --git a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.test.ts b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.test.ts
index 31ec26609478..550fd0131b46 100644
--- a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.test.ts
+++ b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.test.ts
@@ -60,6 +60,12 @@ describe('customerAnalyticsSceneLogic', () => {
expectLogic(logic).toMatchValues({ activeTab: 'feature_requests' })
})
+ it('activates the Tasks tab for its scene key', () => {
+ sceneLogic.actions.setScene(Scene.CustomerAnalytics, 'customerAnalyticsTasks', emptySceneParams)
+
+ expectLogic(logic).toMatchValues({ activeTab: 'tasks' })
+ })
+
it('activates the Accounts tab for the account detail scene key', () => {
sceneLogic.actions.setScene(Scene.CustomerAnalyticsAccount, 'customerAnalyticsAccount', emptySceneParams)
diff --git a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts
index 2153d5fb9c1d..82333de71b6d 100644
--- a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts
+++ b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts
@@ -43,7 +43,15 @@ import { customerAnalyticsConfigLogic } from './customerAnalyticsConfigLogic'
export type BusinessType = 'b2c' | 'b2b'
-type ActiveTab = 'dashboard' | 'journeys' | 'accounts' | 'notes' | 'announcements' | 'feed' | 'feature_requests'
+type ActiveTab =
+ | 'dashboard'
+ | 'journeys'
+ | 'accounts'
+ | 'notes'
+ | 'announcements'
+ | 'feed'
+ | 'tasks'
+ | 'feature_requests'
const SCENE_KEY_TO_TAB: Record<string, ActiveTab> = {
customerAnalyticsJourneys: 'journeys',
@@ -52,6 +60,7 @@ const SCENE_KEY_TO_TAB: Record<string, ActiveTab> = {
customerAnalyticsNotes: 'notes',
customerAnalyticsAnnouncements: 'announcements',
customerAnalyticsFeed: 'feed',
+ customerAnalyticsTasks: 'tasks',
customerAnalyticsFeatureRequests: 'feature_requests',
}
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index 7956f8d52720..7fe55b31223a 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -2848,6 +2848,281 @@ export interface PatchedCustomerProfileConfigApi {
readonly updated_at?: string | null
}
+export interface CustomerTaskAccountApi {
+ /** UUID of the linked account. */
+ readonly id: string
+ /** Name of the linked account. */
+ readonly name: string
+}
+
+/**
+ * * `open` - Open
+ * * `in_progress` - In progress
+ * * `completed` - Completed
+ * * `canceled` - Canceled
+ */
+export type CustomerTaskStatusEnumApi = (typeof CustomerTaskStatusEnumApi)[keyof typeof CustomerTaskStatusEnumApi]
+
+export const CustomerTaskStatusEnumApi = {
+ Open: 'open',
+ InProgress: 'in_progress',
+ Completed: 'completed',
+ Canceled: 'canceled',
+} as const
+
+export interface CustomerTaskUserApi {
+ /** PostHog user ID. */
+ readonly id: number
+ /** Email address of the user. */
+ readonly email: string
+ /** First name of the user. */
+ readonly first_name: string
+ /** Last name of the user. */
+ readonly last_name: string
+}
+
+export interface CustomerTaskApi {
+ /** UUID of the task. */
+ readonly id: string
+ /** Linked account, if any. */
+ readonly account: CustomerTaskAccountApi | null
+ /** Task name. */
+ readonly name: string
+ /**
+ * Task description, if any.
+ * @nullable
+ */
+ readonly description: string | null
+ /** Task lifecycle status.
+ *
+ * * `open` - Open
+ * * `in_progress` - In progress
+ * * `completed` - Completed
+ * * `canceled` - Canceled */
+ readonly status: CustomerTaskStatusEnumApi
+ /** Assigned project member, if any. */
+ readonly assigned_to: CustomerTaskUserApi | null
+ /**
+ * Task deadline, if any.
+ * @nullable
+ */
+ readonly due_at: string | null
+ /**
+ * When the task was completed, if applicable.
+ * @nullable
+ */
+ readonly completed_at: string | null
+ /** User credited with completion, if known. */
+ readonly completed_by: CustomerTaskUserApi | null
+ /** User who created the task, if known. */
+ readonly created_by: CustomerTaskUserApi | null
+ /**
+ * When the task was archived.
+ * @nullable
+ */
+ readonly archived_at: string | null
+ /** When the task was created. */
+ readonly created_at: string
+ /** When the task was last updated. */
+ readonly updated_at: string
+ /** Whether the current user can edit this task. */
+ readonly can_edit: boolean
+ /** Whether the current user can restore this task. */
+ readonly can_restore: boolean
+}
+
+export interface CustomerTaskPageApi {
+ /** Total number of matching tasks. */
+ readonly count: number
+ /**
+ * URL of the next page, if available.
+ * @nullable
+ */
+ readonly next: string | null
+ /**
+ * URL of the previous page, if available.
+ * @nullable
+ */
+ readonly previous: string | null
+ /** Tasks in this page. */
+ readonly results: readonly CustomerTaskApi[]
+}
+
+export interface CustomerTaskCreateApi {
+ /**
+ * UUID of a visible account, or null for an accountless task.
+ * @nullable
+ */
+ account_id?: string | null
+ /**
+ * Task name.
+ * @maxLength 400
+ */
+ name: string
+ /**
+ * Task description, or null to leave it empty.
+ * @nullable
+ */
+ description?: string | null
+ /**
+ * PostHog user ID to assign, or null to leave unassigned.
+ * @nullable
+ */
+ assigned_to_id?: number | null
+ /**
+ * ISO 8601 deadline, or null for no deadline.
+ * @nullable
+ */
+ due_at?: string | null
+ /** Initial task status.
+ *
+ * * `open` - Open
+ * * `in_progress` - In progress
+ * * `completed` - Completed
+ * * `canceled` - Canceled */
+ status?: CustomerTaskStatusEnumApi
+}
+
+export interface CustomerTaskUpdateApi {
+ /**
+ * UUID of a visible account, or null to remove the account link.
+ * @nullable
+ */
+ account_id?: string | null
+ /**
+ * Replacement task name.
+ * @maxLength 400
+ */
+ name: string
+ /**
+ * Replacement description, or null to clear it.
+ * @nullable
+ */
+ description?: string | null
+ /**
+ * Replacement assignee ID, or null to unassign.
+ * @nullable
+ */
+ assigned_to_id?: number | null
+ /**
+ * Replacement ISO 8601 deadline, or null to clear it.
+ * @nullable
+ */
+ due_at?: string | null
+ /** Replacement task status.
+ *
+ * * `open` - Open
+ * * `in_progress` - In progress
+ * * `completed` - Completed
+ * * `canceled` - Canceled */
+ status?: CustomerTaskStatusEnumApi
+}
+
+export interface PatchedCustomerTaskUpdateApi {
+ /**
+ * UUID of a visible account, or null to remove the account link.
+ * @nullable
+ */
+ account_id?: string | null
+ /**
+ * Replacement task name.
+ * @maxLength 400
+ */
+ name?: string
+ /**
+ * Replacement description, or null to clear it.
+ * @nullable
+ */
+ description?: string | null
+ /**
+ * Replacement assignee ID, or null to unassign.
+ * @nullable
+ */
+ assigned_to_id?: number | null
+ /**
+ * Replacement ISO 8601 deadline, or null to clear it.
+ * @nullable
+ */
+ due_at?: string | null
+ /** Replacement task status.
+ *
+ * * `open` - Open
+ * * `in_progress` - In progress
+ * * `completed` - Completed
+ * * `canceled` - Canceled */
+ status?: CustomerTaskStatusEnumApi
+}
+
+/**
+ * * `created` - Created
+ * * `updated` - Updated
+ * * `archived` - Archived
+ * * `restored` - Restored
+ */
+export type CustomerTaskActivityTypeEnumApi =
+ (typeof CustomerTaskActivityTypeEnumApi)[keyof typeof CustomerTaskActivityTypeEnumApi]
+
+export const CustomerTaskActivityTypeEnumApi = {
+ Created: 'created',
+ Updated: 'updated',
+ Archived: 'archived',
+ Restored: 'restored',
+} as const
+
+/**
+ * Value before the change.
+ */
+export type CustomerTaskChangeApiBefore = string | number | boolean | { [key: string]: unknown } | null
+
+/**
+ * Value after the change.
+ */
+export type CustomerTaskChangeApiAfter = string | number | boolean | { [key: string]: unknown } | null
+
+export interface CustomerTaskChangeApi {
+ /** Semantic task field that changed. */
+ readonly field: string
+ /** Value before the change. */
+ readonly before: CustomerTaskChangeApiBefore
+ /** Value after the change. */
+ readonly after: CustomerTaskChangeApiAfter
+}
+
+export interface CustomerTaskActivityApi {
+ /** UUID of the activity. */
+ readonly id: string
+ /** Action that produced the activity.
+ *
+ * * `created` - Created
+ * * `updated` - Updated
+ * * `archived` - Archived
+ * * `restored` - Restored */
+ readonly activity_type: CustomerTaskActivityTypeEnumApi
+ /** Semantic field changes in this action. */
+ readonly changes: readonly CustomerTaskChangeApi[]
+ /** User who made the change, if known. */
+ readonly actor: CustomerTaskUserApi | null
+ /** When the activity was recorded. */
+ readonly created_at: string
+}
+
+export interface CustomerTaskActivityPageApi {
+ /** Total number of matching activities. */
+ readonly count: number
+ /**
+ * URL of the next page, if available.
+ * @nullable
+ */
+ readonly next: string | null
+ /**
+ * URL of the previous page, if available.
+ * @nullable
+ */
+ readonly previous: string | null
+ /** Activities in this page. */
+ readonly results: readonly CustomerTaskActivityApi[]
+}
+
/**
* The caller's event stream — a live feed of selected accounts' events posted to a
* Slack channel of their choice. One stream per user per project.
@@ -3922,6 +4197,102 @@ export type CustomerProfileConfigsListParams = {
offset?: number
}
+export type CustomerTasksListParams = {
+ /**
+ * Filter by account UUID.
+ */
+ account_id?: string
+ /**
+ * Which archive state to include.
+ *
+ * * `active` - active
+ * * `archived` - archived
+ * * `all` - all
+ * @minLength 1
+ */
+ archive_state?: CustomerTasksListArchiveState
+ /**
+ * Filter by me, unassigned, or one user ID.
+ * @minLength 1
+ */
+ assigned_to?: string
+ /**
+ * Inclusive lower deadline bound.
+ */
+ due_after?: string
+ /**
+ * Exclusive upper deadline bound.
+ */
+ due_before?: string
+ /**
+ * Filter tasks by whether a deadline exists.
+ */
+ has_due_at?: boolean
+ /**
+ * Page size, from 1 to 100.
+ * @minimum 1
+ * @maximum 100
+ */
+ limit?: number
+ /**
+ * Number of rows to skip.
+ * @minimum 0
+ */
+ offset?: number
+ /**
+ * Sort by task name, status, assignee, deadline, last update, account, or creation time. Prefix with - for descending order.
+ *
+ * * `name` - name
+ * * `-name` - -name
+ * * `status` - status
+ * * `-status` - -status
+ * * `assigned_to` - assigned_to
+ * * `-assigned_to` - -assigned_to
+ * * `due_at` - due_at
+ * * `-due_at` - -due_at
+ * * `updated_at` - updated_at
+ * * `-updated_at` - -updated_at
+ * * `account` - account
+ * * `-account` - -account
+ * * `created_at` - created_at
+ * * `-created_at` - -created_at
+ * @minLength 1
+ */
+ ordering?: string
+ /**
+ * Search task name and description.
+ */
+ search?: string
+ /**
+ * Comma-separated task statuses.
+ * @minLength 1
+ */
+ statuses?: string
+}
+
+export type CustomerTasksListArchiveState =
+ (typeof CustomerTasksListArchiveState)[keyof typeof CustomerTasksListArchiveState]
+
+export const CustomerTasksListArchiveState = {
+ Active: 'active',
+ Archived: 'archived',
+ All: 'all',
+} as const
+
+export type CustomerTasksActivitiesListParams = {
+ /**
+ * Page size, from 1 to 100.
+ * @minimum 1
+ * @maximum 100
+ */
+ limit?: number
+ /**
+ * Number of rows to skip.
+ * @minimum 0
+ */
+ offset?: number
+}
+
export type FeatureRequestProductAreasListParams = {
/**
* Include inactive product areas. Defaults to false.
diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.ts
index bb69d1fa737e..6d4e390d261d 100644
--- a/products/customer_analytics/frontend/generated/api.ts
+++ b/products/customer_analytics/frontend/generated/api.ts
@@ -53,6 +53,13 @@ import type {
CustomerJourneysListParams,
CustomerProfileConfigApi,
CustomerProfileConfigsListParams,
+ CustomerTaskActivityPageApi,
+ CustomerTaskApi,
+ CustomerTaskCreateApi,
+ CustomerTaskPageApi,
+ CustomerTaskUpdateApi,
+ CustomerTasksActivitiesListParams,
+ CustomerTasksListParams,
EventStreamApi,
EventStreamMemberWriteApi,
EventStreamTestMessageApi,
@@ -96,6 +103,7 @@ import type {
PatchedCustomPropertySourceUpdateApi,
PatchedCustomerJourneyApi,
PatchedCustomerProfileConfigApi,
+ PatchedCustomerTaskUpdateApi,
PatchedEventStreamApi,
PatchedFeatureRequestProductAreaApi,
PatchedFeatureRequestUpdateApi,
@@ -1556,6 +1564,163 @@ export const customerProfileConfigsDestroy = async (
})
}
+export const getCustomerTasksListUrl = (projectId: string, params?: CustomerTasksListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/customer_tasks/?${stringifiedParams}`
+ : `/api/projects/${projectId}/customer_tasks/`
+}
+
+export const customerTasksList = async (
+ projectId: string,
+ params?: CustomerTasksListParams,
+ options?: RequestInit
+): Promise<CustomerTaskPageApi> => {
+ return apiMutator<CustomerTaskPageApi>(getCustomerTasksListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getCustomerTasksCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/customer_tasks/`
+}
+
+export const customerTasksCreate = async (
+ projectId: string,
+ customerTaskCreateApi: CustomerTaskCreateApi,
+ options?: RequestInit
+): Promise<CustomerTaskApi> => {
+ return apiMutator<CustomerTaskApi>(getCustomerTasksCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(customerTaskCreateApi),
+ })
+}
+
+export const getCustomerTasksRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/customer_tasks/${id}/`
+}
+
+export const customerTasksRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<CustomerTaskApi> => {
+ return apiMutator<CustomerTaskApi>(getCustomerTasksRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getCustomerTasksUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/customer_tasks/${id}/`
+}
+
+export const customerTasksUpdate = async (
+ projectId: string,
+ id: string,
+ customerTaskUpdateApi: CustomerTaskUpdateApi,
+ options?: RequestInit
+): Promise<CustomerTaskApi> => {
+ return apiMutator<CustomerTaskApi>(getCustomerTasksUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(customerTaskUpdateApi),
+ })
+}
+
+export const getCustomerTasksPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/customer_tasks/${id}/`
+}
+
+export const customerTasksPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedCustomerTaskUpdateApi?: PatchedCustomerTaskUpdateApi,
+ options?: RequestInit
+): Promise<CustomerTaskApi> => {
+ return apiMutator<CustomerTaskApi>(getCustomerTasksPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedCustomerTaskUpdateApi),
+ })
+}
+
+export const getCustomerTasksActivitiesListUrl = (
+ projectId: string,
+ id: string,
+ params?: CustomerTasksActivitiesListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/customer_tasks/${id}/activities/?${stringifiedParams}`
+ : `/api/projects/${projectId}/customer_tasks/${id}/activities/`
+}
+
+export const customerTasksActivitiesList = async (
+ projectId: string,
+ id: string,
+ params?: CustomerTasksActivitiesListParams,
+ options?: RequestInit
+): Promise<CustomerTaskActivityPageApi> => {
+ return apiMutator<CustomerTaskActivityPageApi>(getCustomerTasksActivitiesListUrl(projectId, id, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getCustomerTasksArchiveCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/customer_tasks/${id}/archive/`
+}
+
+export const customerTasksArchiveCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<CustomerTaskApi> => {
+ return apiMutator<CustomerTaskApi>(getCustomerTasksArchiveCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getCustomerTasksRestoreCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/customer_tasks/${id}/restore/`
+}
+
+export const customerTasksRestoreCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<CustomerTaskApi> => {
+ return apiMutator<CustomerTaskApi>(getCustomerTasksRestoreCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getEventStreamsListUrl = (projectId: string) => {
return `/api/projects/${projectId}/event_streams/`
}
diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.ts
index e421954bbaac..ec10daac189e 100644
--- a/products/customer_analytics/frontend/generated/api.zod.ts
+++ b/products/customer_analytics/frontend/generated/api.zod.ts
@@ -863,6 +863,71 @@ export const CustomerProfileConfigsPartialUpdateBody = /* @__PURE__ */ zod.objec
sidebar: zod.unknown().optional(),
})
+export const customerTasksCreateBodyNameMax = 400
+
+export const customerTasksCreateBodyStatusDefault = `open`
+
+export const CustomerTasksCreateBody = /* @__PURE__ */ zod.object({
+ account_id: zod.uuid().nullish().describe('UUID of a visible account, or null for an accountless task.'),
+ name: zod.string().max(customerTasksCreateBodyNameMax).describe('Task name.'),
+ description: zod.string().nullish().describe('Task description, or null to leave it empty.'),
+ assigned_to_id: zod.number().nullish().describe('PostHog user ID to assign, or null to leave unassigned.'),
+ due_at: zod.iso.datetime({ offset: true }).nullish().describe('ISO 8601 deadline, or null for no deadline.'),
+ status: zod
+ .enum(['open', 'in_progress', 'completed', 'canceled'])
+ .describe(
+ '\* `open` - Open\n\* `in_progress` - In progress\n\* `completed` - Completed\n\* `canceled` - Canceled'
+ )
+ .default(customerTasksCreateBodyStatusDefault)
+ .describe(
+ 'Initial task status.\n\n\* `open` - Open\n\* `in_progress` - In progress\n\* `completed` - Completed\n\* `canceled` - Canceled'
+ ),
+})
+
+export const customerTasksUpdateBodyNameMax = 400
+
+export const CustomerTasksUpdateBody = /* @__PURE__ */ zod.object({
+ account_id: zod.uuid().nullish().describe('UUID of a visible account, or null to remove the account link.'),
+ name: zod.string().max(customerTasksUpdateBodyNameMax).describe('Replacement task name.'),
+ description: zod.string().nullish().describe('Replacement description, or null to clear it.'),
+ assigned_to_id: zod.number().nullish().describe('Replacement assignee ID, or null to unassign.'),
+ due_at: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('Replacement ISO 8601 deadline, or null to clear it.'),
+ status: zod
+ .enum(['open', 'in_progress', 'completed', 'canceled'])
+ .describe(
+ '\* `open` - Open\n\* `in_progress` - In progress\n\* `completed` - Completed\n\* `canceled` - Canceled'
+ )
+ .optional()
+ .describe(
+ 'Replacement task status.\n\n\* `open` - Open\n\* `in_progress` - In progress\n\* `completed` - Completed\n\* `canceled` - Canceled'
+ ),
+})
+
+export const customerTasksPartialUpdateBodyNameMax = 400
+
+export const CustomerTasksPartialUpdateBody = /* @__PURE__ */ zod.object({
+ account_id: zod.uuid().nullish().describe('UUID of a visible account, or null to remove the account link.'),
+ name: zod.string().max(customerTasksPartialUpdateBodyNameMax).optional().describe('Replacement task name.'),
+ description: zod.string().nullish().describe('Replacement description, or null to clear it.'),
+ assigned_to_id: zod.number().nullish().describe('Replacement assignee ID, or null to unassign.'),
+ due_at: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('Replacement ISO 8601 deadline, or null to clear it.'),
+ status: zod
+ .enum(['open', 'in_progress', 'completed', 'canceled'])
+ .describe(
+ '\* `open` - Open\n\* `in_progress` - In progress\n\* `completed` - Completed\n\* `canceled` - Canceled'
+ )
+ .optional()
+ .describe(
+ 'Replacement task status.\n\n\* `open` - Open\n\* `in_progress` - In progress\n\* `completed` - Completed\n\* `canceled` - Canceled'
+ ),
+})
+
/**
* The caller's event stream: a live feed of selected accounts' events posted to a
* Slack channel of their choice. Per-user — each team member owns at most one stream, and
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
index 7838be37b75a..a4d9e051cca0 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
@@ -63,6 +63,7 @@ describe('customerAnalyticsAccountSceneLogic', () => {
featureFlagLogic.actions.setFeatureFlags([], {
[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]: true,
[FEATURE_FLAGS.CUSTOMER_ANALYTICS_FEATURE_REQUESTS]: true,
+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS]: true,
})
router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID))
})
@@ -226,7 +227,7 @@ describe('customerAnalyticsAccountSceneLogic', () => {
expect(logic.values.activeTab).toBe('notes')
})
- it.each(['users', 'usage', 'feature_requests'] as const)('selects the %s tab from the URL', (tab) => {
+ it.each(['users', 'usage', 'feature_requests', 'tasks'] as const)('selects the %s tab from the URL', (tab) => {
router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID, tab))
expect(logic.values.activeTab).toBe(tab)
@@ -245,6 +246,10 @@ describe('customerAnalyticsAccountSceneLogic', () => {
router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID, 'feature_requests'))
expect(logic.values.activeTab).toBe('notes')
+
+ router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID, 'tasks'))
+
+ expect(logic.values.activeTab).toBe('notes')
})
it('preserves URL state and captures only user tab changes', () => {
diff --git a/products/customer_analytics/manifest.tsx b/products/customer_analytics/manifest.tsx
index 39b2d2a90ae2..cb0633b6dd07 100644
--- a/products/customer_analytics/manifest.tsx
+++ b/products/customer_analytics/manifest.tsx
@@ -60,6 +60,7 @@ export const manifest: ProductManifest = {
'/customer_analytics/notes': ['CustomerAnalytics', 'customerAnalyticsNotes'],
'/customer_analytics/announcements': ['CustomerAnalytics', 'customerAnalyticsAnnouncements'],
'/customer_analytics/feed': ['CustomerAnalytics', 'customerAnalyticsFeed'],
+ '/customer_analytics/tasks': ['CustomerAnalytics', 'customerAnalyticsTasks'],
'/customer_analytics/feature-requests': ['CustomerAnalytics', 'customerAnalyticsFeatureRequests'],
'/customer_analytics/feature-requests/:requestId': ['CustomerAnalytics', 'customerAnalyticsFeatureRequests'],
'/customer_analytics/journeys/new': ['CustomerJourneyBuilder', 'customerJourneyBuilder'],
@@ -88,6 +89,7 @@ export const manifest: ProductManifest = {
customerAnalyticsNotes: (): string => '/customer_analytics/notes',
customerAnalyticsAnnouncements: (): string => '/customer_analytics/announcements',
customerAnalyticsFeed: (): string => '/customer_analytics/feed',
+ customerAnalyticsTasks: (): string => '/customer_analytics/tasks',
customerAnalyticsFeatureRequests: (requestId?: string): string =>
`/customer_analytics/feature-requests${requestId ? `/${requestId}` : ''}`,
customerAnalyticsJourneys: (): string => '/customer_analytics/journeys',
diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yaml
index f7b5d0fec99f..e97fc41b0ffd 100644
--- a/products/customer_analytics/mcp/tools.yaml
+++ b/products/customer_analytics/mcp/tools.yaml
@@ -826,6 +826,30 @@ tools:
customer-profile-configs-update:
operation: customer_profile_configs_update
enabled: false
+ customer-tasks-activities-list:
+ operation: customerTasksActivitiesList
+ enabled: false
+ customer-tasks-archive-create:
+ operation: customer_tasks_archive_create
+ enabled: false
+ customer-tasks-create:
+ operation: customer_tasks_create
+ enabled: false
+ customer-tasks-list:
+ operation: customer_tasks_list
+ enabled: false
+ customer-tasks-partial-update:
+ operation: customer_tasks_partial_update
+ enabled: false
+ customer-tasks-restore-create:
+ operation: customer_tasks_restore_create
+ enabled: false
+ customer-tasks-retrieve:
+ operation: customer_tasks_retrieve
+ enabled: false
+ customer-tasks-update:
+ operation: customer_tasks_update
+ enabled: false
event-streams-add-account:
operation: event_streams_add_account_create
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 13bc408c92e9..2568621779ee 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -20549,6 +20549,247 @@ export namespace Schemas {
readonly updated_at: string | null;
}
+ export interface CustomerTaskAccount {
+ /** UUID of the linked account. */
+ readonly id: string;
+ /** Name of the linked account. */
+ readonly name: string;
+ }
+
+ /**
+ * * `open` - Open
+ * * `in_progress` - In progress
+ * * `completed` - Completed
+ * * `canceled` - Canceled
+ */
+ export type CustomerTaskStatusEnum = typeof CustomerTaskStatusEnum[keyof typeof CustomerTaskStatusEnum];
+
+
+ export const CustomerTaskStatusEnum = {
+ Open: 'open',
+ InProgress: 'in_progress',
+ Completed: 'completed',
+ Canceled: 'canceled',
+ } as const;
+
+ export interface CustomerTaskUser {
+ /** PostHog user ID. */
+ readonly id: number;
+ /** Email address of the user. */
+ readonly email: string;
+ /** First name of the user. */
+ readonly first_name: string;
+ /** Last name of the user. */
+ readonly last_name: string;
+ }
+
+ export interface CustomerTask {
+ /** UUID of the task. */
+ readonly id: string;
+ /** Linked account, if any. */
+ readonly account: CustomerTaskAccount | null;
+ /** Task name. */
+ readonly name: string;
+ /**
+ * Task description, if any.
+ * @nullable
+ */
+ readonly description: string | null;
+ /** Task lifecycle status.
+ *
+ * * `open` - Open
+ * * `in_progress` - In progress
+ * * `completed` - Completed
+ * * `canceled` - Canceled */
+ readonly status: CustomerTaskStatusEnum;
+ /** Assigned project member, if any. */
+ readonly assigned_to: CustomerTaskUser | null;
+ /**
+ * Task deadline, if any.
+ * @nullable
+ */
+ readonly due_at: string | null;
+ /**
+ * When the task was completed, if applicable.
+ * @nullable
+ */
+ readonly completed_at: string | null;
+ /** User credited with completion, if known. */
+ readonly completed_by: CustomerTaskUser | null;
+ /** User who created the task, if known. */
+ readonly created_by: CustomerTaskUser | null;
+ /**
+ * When the task was archived.
+ * @nullable
+ */
+ readonly archived_at: string | null;
+ /** When the task was created. */
+ readonly created_at: string;
+ /** When the task was last updated. */
+ readonly updated_at: string;
+ /** Whether the current user can edit this task. */
+ readonly can_edit: boolean;
+ /** Whether the current user can restore this task. */
+ readonly can_restore: boolean;
+ }
+
+ /**
+ * * `created` - Created
+ * * `updated` - Updated
+ * * `archived` - Archived
+ * * `restored` - Restored
+ */
+ export type CustomerTaskActivityTypeEnum = typeof CustomerTaskActivityTypeEnum[keyof typeof CustomerTaskActivityTypeEnum];
+
+
+ export const CustomerTaskActivityTypeEnum = {
+ Created: 'created',
+ Updated: 'updated',
+ Archived: 'archived',
+ Restored: 'restored',
+ } as const;
+
+ /**
+ * Value before the change.
+ */
+ export type CustomerTaskChangeBefore = string | number | boolean | { [key: string]: unknown } | null;
+
+ /**
+ * Value after the change.
+ */
+ export type CustomerTaskChangeAfter = string | number | boolean | { [key: string]: unknown } | null;
+
+ export interface CustomerTaskChange {
+ /** Semantic task field that changed. */
+ readonly field: string;
+ /** Value before the change. */
+ readonly before: CustomerTaskChangeBefore;
+ /** Value after the change. */
+ readonly after: CustomerTaskChangeAfter;
+ }
+
+ export interface CustomerTaskActivity {
+ /** UUID of the activity. */
+ readonly id: string;
+ /** Action that produced the activity.
+ *
+ * * `created` - Created
+ * * `updated` - Updated
+ * * `archived` - Archived
+ * * `restored` - Restored */
+ readonly activity_type: CustomerTaskActivityTypeEnum;
+ /** Semantic field changes in this action. */
+ readonly changes: readonly CustomerTaskChange[];
+ /** User who made the change, if known. */
+ readonly actor: CustomerTaskUser | null;
+ /** When the activity was recorded. */
+ readonly created_at: string;
+ }
+
+ export interface CustomerTaskActivityPage {
+ /** Total number of matching activities. */
+ readonly count: number;
+ /**
+ * URL of the next page, if available.
+ * @nullable
+ */
+ readonly next: string | null;
+ /**
+ * URL of the previous page, if available.
+ * @nullable
+ */
+ readonly previous: string | null;
+ /** Activities in this page. */
+ readonly results: readonly CustomerTaskActivity[];
+ }
+
+ export interface CustomerTaskCreate {
+ /**
+ * UUID of a visible account, or null for an accountless task.
+ * @nullable
+ */
+ account_id?: string | null;
+ /**
+ * Task name.
+ * @maxLength 400
+ */
+ name: string;
+ /**
+ * Task description, or null to leave it empty.
+ * @nullable
+ */
+ description?: string | null;
+ /**
+ * PostHog user ID to assign, or null to leave unassigned.
+ * @nullable
+ */
+ assigned_to_id?: number | null;
+ /**
+ * ISO 8601 deadline, or null for no deadline.
+ * @nullable
+ */
+ due_at?: string | null;
+ /** Initial task status.
+ *
+ * * `open` - Open
+ * * `in_progress` - In progress
+ * * `completed` - Completed
+ * * `canceled` - Canceled */
+ status?: CustomerTaskStatusEnum;
+ }
+
+ export interface CustomerTaskPage {
+ /** Total number of matching tasks. */
+ readonly count: number;
+ /**
+ * URL of the next page, if available.
+ * @nullable
+ */
+ readonly next: string | null;
+ /**
+ * URL of the previous page, if available.
+ * @nullable
+ */
+ readonly previous: string | null;
+ /** Tasks in this page. */
+ readonly results: readonly CustomerTask[];
+ }
+
+ export interface CustomerTaskUpdate {
+ /**
+ * UUID of a visible account, or null to remove the account link.
+ * @nullable
+ */
+ account_id?: string | null;
+ /**
+ * Replacement task name.
+ * @maxLength 400
+ */
+ name: string;
+ /**
+ * Replacement description, or null to clear it.
+ * @nullable
+ */
+ description?: string | null;
+ /**
+ * Replacement assignee ID, or null to unassign.
+ * @nullable
+ */
+ assigned_to_id?: number | null;
+ /**
+ * Replacement ISO 8601 deadline, or null to clear it.
+ * @nullable
+ */
+ due_at?: string | null;
+ /** Replacement task status.
+ *
+ * * `open` - Open
+ * * `in_progress` - In progress
+ * * `completed` - Completed
+ * * `canceled` - Canceled */
+ status?: CustomerTaskStatusEnum;
+ }
+
export interface Dag {
readonly id: string;
/**
@@ -61398,6 +61639,41 @@ export namespace Schemas {
readonly updated_at?: string | null;
}
+ export interface PatchedCustomerTaskUpdate {
+ /**
+ * UUID of a visible account, or null to remove the account link.
+ * @nullable
+ */
+ account_id?: string | null;
+ /**
+ * Replacement task name.
+ * @maxLength 400
+ */
+ name?: string;
+ /**
+ * Replacement description, or null to clear it.
+ * @nullable
+ */
+ description?: string | null;
+ /**
+ * Replacement assignee ID, or null to unassign.
+ * @nullable
+ */
+ assigned_to_id?: number | null;
+ /**
+ * Replacement ISO 8601 deadline, or null to clear it.
+ * @nullable
+ */
+ due_at?: string | null;
+ /** Replacement task status.
+ *
+ * * `open` - Open
+ * * `in_progress` - In progress
+ * * `completed` - Completed
+ * * `canceled` - Canceled */
+ status?: CustomerTaskStatusEnum;
+ }
+
export interface PatchedDAG {
readonly id?: string;
/**
@@ -92964,6 +93240,102 @@ export namespace Schemas {
offset?: number;
};
+ export type CustomerTasksListParams = {
+ /**
+ * Filter by account UUID.
+ */
+ account_id?: string;
+ /**
+ * Which archive state to include.
+ *
+ * * `active` - active
+ * * `archived` - archived
+ * * `all` - all
+ * @minLength 1
+ */
+ archive_state?: CustomerTasksListArchiveState;
+ /**
+ * Filter by me, unassigned, or one user ID.
+ * @minLength 1
+ */
+ assigned_to?: string;
+ /**
+ * Inclusive lower deadline bound.
+ */
+ due_after?: string;
+ /**
+ * Exclusive upper deadline bound.
+ */
+ due_before?: string;
+ /**
+ * Filter tasks by whether a deadline exists.
+ */
+ has_due_at?: boolean;
+ /**
+ * Page size, from 1 to 100.
+ * @minimum 1
+ * @maximum 100
+ */
+ limit?: number;
+ /**
+ * Number of rows to skip.
+ * @minimum 0
+ */
+ offset?: number;
+ /**
+ * Sort by task name, status, assignee, deadline, last update, account, or creation time. Prefix with - for descending order.
+ *
+ * * `name` - name
+ * * `-name` - -name
+ * * `status` - status
+ * * `-status` - -status
+ * * `assigned_to` - assigned_to
+ * * `-assigned_to` - -assigned_to
+ * * `due_at` - due_at
+ * * `-due_at` - -due_at
+ * * `updated_at` - updated_at
+ * * `-updated_at` - -updated_at
+ * * `account` - account
+ * * `-account` - -account
+ * * `created_at` - created_at
+ * * `-created_at` - -created_at
+ * @minLength 1
+ */
+ ordering?: string;
+ /**
+ * Search task name and description.
+ */
+ search?: string;
+ /**
+ * Comma-separated task statuses.
+ * @minLength 1
+ */
+ statuses?: string;
+ };
+
+ export type CustomerTasksListArchiveState = typeof CustomerTasksListArchiveState[keyof typeof CustomerTasksListArchiveState];
+
+
+ export const CustomerTasksListArchiveState = {
+ Active: 'active',
+ Archived: 'archived',
+ All: 'all',
+ } as const;
+
+ export type CustomerTasksActivitiesListParams = {
+ /**
+ * Page size, from 1 to 100.
+ * @minimum 1
+ * @maximum 100
+ */
+ limit?: number;
+ /**
+ * Number of rows to skip.
+ * @minimum 0
+ */
+ offset?: number;
+ };
+
export type DashboardSavedViewsListParams = {
/**
* The pagination cursor value.
diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.ts
index b033cefc1185..17743b32310b 100644
--- a/services/mcp/src/lib/oauth-scopes.generated.ts
+++ b/services/mcp/src/lib/oauth-scopes.generated.ts
@@ -45,6 +45,8 @@ export const OAUTH_SCOPES_SUPPORTED = [
'conversation:write',
'customer_analytics:read',
'customer_analytics:write',
+ 'customer_task:read',
+ 'customer_task:write',
'customer_journey:read',
'customer_journey:write',
'customer_profile_config:read',
diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.json
index 43b328fa7be2..cf8d8cd1fca0 100644
--- a/services/mcp/src/tools/links/app-url-manifest.json
+++ b/services/mcp/src/tools/links/app-url-manifest.json
@@ -399,6 +399,11 @@
"params": [],
"scope": "project"
},
+ "customerAnalyticsTasks": {
+ "template": "/customer_analytics/tasks",
+ "params": [],
+ "scope": "project"
+ },
"customerJourneyBuilder": {
"template": "/customer_analytics/journeys/new",
"params": [],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
index 70d0af9d006b..5fe358461e4e 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
@@ -13,7 +13,7 @@
"type": "object"
},
"url": {
- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/comments\n/data-management/comments/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/health\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/test-health\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/error_tracking/{id}/fingerprints\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/comments\n/data-management/comments/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/health\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/test-health\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/error_tracking/{id}/fingerprints\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
"type": "string"
}
},