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): build task digest emails and links (#102648)

posthog[bot]15fa736124e6
diff --git a/docs/internal/customer-analytics-tasks-workflows.md b/docs/internal/customer-analytics-tasks-workflows.md
index b55ed6e95fd9..4a7c814169f4 100644
--- a/docs/internal/customer-analytics-tasks-workflows.md
+++ b/docs/internal/customer-analytics-tasks-workflows.md
@@ -44,3 +44,22 @@ That facade reads the workflow owner ID through `products/workflows/backend/faca
Only Workflows queries the workflow model.
The URL and basename stay unchanged.
The view pins its OpenAPI product attribution to `workflows` but remains excluded from generated API docs.
+
+## Task digest content and links
+
+Task digests read the assignee's current tasks, deadlines, and permissions when built.
+Only active, assigned tasks with open or in-progress status appear.
+Task and linked-account access restrictions apply to both the listed tasks and the overdue count.
+
+**Due today** covers the full current date in the project timezone.
+The email lists up to 10 tasks, shows the total beside the section heading, and shows the remaining count below the list.
+The remaining count links to active tasks assigned to the email recipient with the **Today** due-date filter.
+**Due this week** covers tomorrow through Friday of the current workweek; Friday and weekend digests do not include next week.
+An overdue task has a deadline before the current instant, so tasks due earlier today also contribute to the overdue count.
+Empty digests are skipped, but an overdue count alone is enough to send one.
+
+Task links open the task editor using `task_id`.
+The overdue link selects `status=open`, `assignee=me`, `archive=active`, and `due=overdue` on the Tasks tab.
+Explicit URL filters replace locally saved filters, and the overdue cutoff is evaluated when the view loads.
+The notification settings link opens the personal task digest settings.
+Content generation does not schedule or send email; delivery is controlled separately.
diff --git a/posthog/templates/email/customer_task_digest.html b/posthog/templates/email/customer_task_digest.html
new file mode 100644
index 000000000000..ba864d9d57f4
--- /dev/null
+++ b/posthog/templates/email/customer_task_digest.html
@@ -0,0 +1,43 @@
+{% extends "email/base.html" %}
+{% block heading %}Your customer tasks{% endblock %}
+{% block section %}
+ <p>Tasks assigned to you in <b>{{ digest.project_name }}</b>.</p>
+ {% if digest.due_today %}
+ <h2>Due today ({{ digest.due_today|length }})</h2>
+ <ul>
+ {% for task in digest.due_today|slice:":10" %}
+ <li>
+ <a href="{{ task.url }}">{{ task.name }}</a>
+ {% if task.account_name %}<br />{{ task.account_name }}{% endif %}
+ <br />
+ {{ task.due_label }}
+ </li>
+ {% endfor %}
+ </ul>
+ {% with remaining=digest.due_today|length|add:"-10" %}
+ {% if remaining > 0 %}
+ <p>
+ <a href="{{ digest.due_today_url }}">+{{ remaining }} more task{{ remaining|pluralize }} due today</a>
+ </p>
+ {% endif %}
+ {% endwith %}
+ {% endif %}
+ {% if digest.due_this_week %}
+ <h2>Due this week</h2>
+ <ul>
+ {% for task in digest.due_this_week %}
+ <li>
+ <a href="{{ task.url }}">{{ task.name }}</a>
+ {% if task.account_name %}<br />{{ task.account_name }}{% endif %}
+ <br />
+ {{ task.due_label }}
+ </li>
+ {% endfor %}
+ </ul>
+ {% endif %}
+ {% if digest.overdue_count %}
+ <h2>Overdue</h2>
+ <p><a href="{{ digest.overdue_url }}">{{ digest.overdue_count }} overdue task{{ digest.overdue_count|pluralize }}</a></p>
+ {% endif %}
+ <p><a href="{{ digest.settings_url }}">Notification settings</a></p>
+{% endblock %}
diff --git a/products/customer_analytics/backend/logic/customer_task_digest.py b/products/customer_analytics/backend/logic/customer_task_digest.py
new file mode 100644
index 000000000000..e80ce58d0631
--- /dev/null
+++ b/products/customer_analytics/backend/logic/customer_task_digest.py
@@ -0,0 +1,100 @@
+from __future__ import annotations
+
+from dataclasses import asdict
+from datetime import datetime, time, timedelta
+from urllib.parse import urlencode
+from zoneinfo import ZoneInfo
+
+from django.conf import settings
+from django.utils import timezone
+
+from posthog.dataclasses import frozen
+from posthog.email import EmailMessage
+from posthog.models import Team, User
+
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.customer_analytics.backend.logic.customer_tasks import _visible_task_queryset
+from products.customer_analytics.backend.models.customer_task import CustomerTaskStatus
+
+
+@frozen
+class CustomerTaskDigestItem:
+ name: str
+ url: str
+ due_label: str
+ account_name: str | None
+
+
+@frozen
+class CustomerTaskDigest:
+ project_name: str
+ due_today: tuple[CustomerTaskDigestItem, ...]
+ due_this_week: tuple[CustomerTaskDigestItem, ...]
+ overdue_count: int
+ overdue_url: str
+ due_today_url: str
+ settings_url: str
+
+
+def build_customer_task_digest(*, user: User, team: Team, reference_time: datetime) -> CustomerTaskDigest | None:
+ if timezone.is_naive(reference_time):
+ raise ValueError("reference_time must include a timezone")
+ access = UserAccessControl(user=user, team=team)
+ if not user.is_active or not access.check_access_level_for_object(team, required_level="member"):
+ return None
+
+ project_timezone = ZoneInfo(team.timezone)
+ today = reference_time.astimezone(project_timezone).date()
+ today_start = datetime.combine(today, time.min, tzinfo=project_timezone)
+ tomorrow_start = datetime.combine(today + timedelta(days=1), time.min, tzinfo=project_timezone)
+ weekend_start = datetime.combine(today + timedelta(days=5 - today.weekday()), time.min, tzinfo=project_timezone)
+ tasks = _visible_task_queryset(team.id, access).filter(
+ assigned_to_id=user.id,
+ status__in=[CustomerTaskStatus.OPEN, CustomerTaskStatus.IN_PROGRESS],
+ archived_at__isnull=True,
+ due_at__isnull=False,
+ )
+ overdue_count = tasks.filter(due_at__lt=reference_time).count()
+ tasks_url = f"{settings.SITE_URL}/project/{team.id}/customer_analytics/tasks"
+ due_today: list[CustomerTaskDigestItem] = []
+ due_this_week: list[CustomerTaskDigestItem] = []
+ period_end = max(tomorrow_start, weekend_start)
+ for task in tasks.filter(due_at__gte=today_start, due_at__lt=period_end).order_by("due_at", "id"):
+ assert task.due_at is not None
+ local_due = task.due_at.astimezone(project_timezone)
+ item = CustomerTaskDigestItem(
+ name=task.name,
+ url=f"{tasks_url}?{urlencode({'task_id': str(task.id)})}",
+ due_label=local_due.strftime("%a, %b %d at %H:%M %Z"),
+ account_name=task.account.name if task.account else None,
+ )
+ if local_due.date() == today:
+ due_today.append(item)
+ else:
+ due_this_week.append(item)
+
+ if not due_today and not due_this_week and not overdue_count:
+ return None
+ return CustomerTaskDigest(
+ project_name=team.name,
+ due_today=tuple(due_today),
+ due_this_week=tuple(due_this_week),
+ overdue_count=overdue_count,
+ overdue_url=f"{tasks_url}?{urlencode({'status': 'open', 'assignee': 'me', 'archive': 'active', 'due': 'overdue'})}",
+ due_today_url=f"{tasks_url}?{urlencode({'status': 'open', 'assignee': user.id, 'archive': 'active', 'due': 'today'})}",
+ settings_url=f"{settings.SITE_URL}/project/{team.id}/customer_analytics/configuration?tab=customer-analytics-event-stream",
+ )
+
+
+def build_customer_task_digest_email(*, digest: CustomerTaskDigest, user: User, campaign_key: str) -> EmailMessage:
+ context = asdict(digest)
+ context["due_today"] = list(context["due_today"])
+ context["due_this_week"] = list(context["due_this_week"])
+ message = EmailMessage(
+ campaign_key=campaign_key,
+ template_name="customer_task_digest",
+ subject="Your customer tasks",
+ template_context={"digest": context},
+ )
+ message.add_user_recipient(user)
+ return message
diff --git a/products/customer_analytics/backend/test/test_customer_task_digest.py b/products/customer_analytics/backend/test/test_customer_task_digest.py
new file mode 100644
index 000000000000..aa391adc1086
--- /dev/null
+++ b/products/customer_analytics/backend/test/test_customer_task_digest.py
@@ -0,0 +1,193 @@
+from datetime import UTC, datetime, time, timedelta
+from urllib.parse import parse_qs, urlsplit
+from zoneinfo import ZoneInfo
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.template.loader import render_to_string
+from django.test import SimpleTestCase
+
+from lxml import html
+from parameterized import parameterized
+
+from posthog.constants import AvailableFeature
+from posthog.models import OrganizationMembership, Team, User
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.customer_analytics.backend.logic.customer_task_digest import (
+ build_customer_task_digest,
+ build_customer_task_digest_email,
+)
+from products.customer_analytics.backend.models import Account, CustomerTask
+
+
+class TestCustomerTaskDigest(BaseTest):
+ @parameterized.expand(
+ [
+ ("midweek", "2026-09-16T12:00:00+00:00", "America/New_York", 2),
+ ("friday", "2026-09-18T12:00:00+00:00", "America/New_York", 0),
+ ("saturday", "2026-09-19T12:00:00+00:00", "America/New_York", 0),
+ ("spring_dst", "2026-03-08T08:00:00+00:00", "America/New_York", 0),
+ ("fall_dst", "2026-11-01T08:00:00+00:00", "America/New_York", 0),
+ ("next_local_day", "2026-09-15T23:30:00+00:00", "Asia/Tokyo", 2),
+ ]
+ )
+ def test_sections_follow_project_dates(self, _name: str, now: str, zone: str, upcoming_days: int) -> None:
+ self.team.timezone = zone
+ reference_time = datetime.fromisoformat(now)
+ local_day = reference_time.astimezone(ZoneInfo(zone)).date()
+ start = datetime.combine(local_day, time.min, tzinfo=ZoneInfo(zone))
+ tomorrow = datetime.combine(local_day + timedelta(days=1), time.min, tzinfo=ZoneInfo(zone))
+ for name, due in [
+ ("before", start - timedelta(seconds=1)),
+ ("start", start),
+ ("last", tomorrow - timedelta(seconds=1)),
+ ]:
+ CustomerTask.objects.for_team(self.team.id).create(
+ team=self.team, assigned_to=self.user, name=name, due_at=due
+ )
+ for offset in range(1, 9):
+ CustomerTask.objects.for_team(self.team.id).create(
+ team=self.team,
+ assigned_to=self.user,
+ name=f"day-{offset}",
+ due_at=tomorrow + timedelta(days=offset - 1),
+ )
+ digest = build_customer_task_digest(user=self.user, team=self.team, reference_time=reference_time)
+ assert digest is not None
+ assert [task.name for task in digest.due_today] == ["start", "last"]
+ assert [task.name for task in digest.due_this_week] == [
+ f"day-{offset}" for offset in range(1, upcoming_days + 1)
+ ]
+ assert digest.overdue_count == 2
+
+ def test_empty_overdue_only_and_current_task_state(self) -> None:
+ now = datetime(2026, 9, 16, 12, tzinfo=UTC)
+ assert build_customer_task_digest(user=self.user, team=self.team, reference_time=now) is None
+ task = CustomerTask.objects.for_team(self.team.id).create(
+ team=self.team, assigned_to=self.user, name="Follow up", due_at=now - timedelta(days=1)
+ )
+ digest = build_customer_task_digest(user=self.user, team=self.team, reference_time=now)
+ assert digest is not None
+ assert digest.overdue_count == 1
+ assert not digest.due_today and not digest.due_this_week
+ assert "due=overdue" in digest.overdue_url
+ assert "assignee=me" in digest.overdue_url
+ with patch("posthog.email.is_email_available", return_value=True):
+ message = build_customer_task_digest_email(digest=digest, user=self.user, campaign_key="test-digest")
+ assert "1 overdue task" in message.html_body
+ assert "Notification settings" in message.html_body
+ for field, value in [
+ ("status", "completed"),
+ ("status", "canceled"),
+ ("archived_at", now),
+ ("assigned_to", None),
+ ("due_at", None),
+ ]:
+ setattr(task, field, value)
+ task.completed_at = now if task.status == "completed" else None
+ task.save()
+ assert build_customer_task_digest(user=self.user, team=self.team, reference_time=now) is None
+ task.status = "open"
+ task.completed_at = None
+ task.archived_at = None
+ task.assigned_to = self.user
+ task.due_at = now - timedelta(days=1)
+ task.save()
+ task.due_at = now + timedelta(hours=1)
+ task.save(update_fields=["due_at"])
+ refreshed = build_customer_task_digest(user=self.user, team=self.team, reference_time=now)
+ assert refreshed is not None
+ assert refreshed.overdue_count == 0
+ assert len(refreshed.due_today) == 1
+ assert str(task.id) in refreshed.due_today[0].url
+ due_today_link = urlsplit(refreshed.due_today_url)
+ assert due_today_link.path == f"/project/{self.team.id}/customer_analytics/tasks"
+ assert parse_qs(due_today_link.query) == {
+ "status": ["open"],
+ "assignee": [str(self.user.id)],
+ "archive": ["active"],
+ "due": ["today"],
+ }
+
+ def test_access_filters_lists_and_counts_and_rechecks_membership(self) -> None:
+ self.organization.available_product_features = [
+ {"name": AvailableFeature.ACCESS_CONTROL, "key": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save(update_fields=["available_product_features"])
+ user = User.objects.create_and_join(self.organization, "[email protected]", "testpassword")
+ membership = OrganizationMembership.objects.get(user=user, organization=self.organization)
+ account = Account.objects.for_team(self.team.id).create(team=self.team, name="Hidden account")
+ now = datetime(2026, 9, 16, 12, tzinfo=UTC)
+ for due_at in [now - timedelta(days=1), now + timedelta(hours=1)]:
+ CustomerTask.objects.for_team(self.team.id).create(
+ team=self.team, account=account, assigned_to=user, name="Hidden account task", due_at=due_at
+ )
+ task = CustomerTask.objects.for_team(self.team.id).create(
+ team=self.team, assigned_to=user, name="Hidden task", due_at=due_at
+ )
+ AccessControl.objects.create(
+ team=self.team,
+ resource="customer_task",
+ resource_id=str(task.id),
+ access_level="none",
+ organization_member=membership,
+ )
+ AccessControl.objects.create(
+ team=self.team,
+ resource="account",
+ resource_id=str(account.id),
+ access_level="none",
+ organization_member=membership,
+ )
+ other_team = Team.objects.create(organization=self.organization)
+ CustomerTask.objects.for_team(other_team.id).create(
+ team=other_team, assigned_to=user, name="Other project", due_at=now
+ )
+ assert build_customer_task_digest(user=user, team=self.team, reference_time=now) is None
+ CustomerTask.objects.for_team(self.team.id).create(team=self.team, assigned_to=user, name="Visible", due_at=now)
+ assert build_customer_task_digest(user=user, team=self.team, reference_time=now) is not None
+ AccessControl.objects.create(
+ team=self.team,
+ resource="project",
+ resource_id=str(self.team.id),
+ access_level="none",
+ organization_member=membership,
+ )
+ assert build_customer_task_digest(user=user, team=self.team, reference_time=now) is None
+
+
+class TestCustomerTaskDigestTemplate(SimpleTestCase):
+ @parameterized.expand([(1,), (10,), (11,), (19,)])
+ def test_due_today_preview_includes_total_and_remaining_count(self, total: int) -> None:
+ tasks = [
+ {
+ "name": f"Task {index}",
+ "url": f"https://example.com/tasks/{index}",
+ "due_label": "Today at 09:00 UTC",
+ }
+ for index in range(1, total + 1)
+ ]
+ due_today_url = (
+ "https://example.com/project/1/customer_analytics/tasks?status=open&assignee=7&archive=active&due=today"
+ )
+ document = html.fromstring(
+ render_to_string(
+ "email/customer_task_digest.html",
+ {"digest": {"project_name": "Example project", "due_today": tasks, "due_today_url": due_today_url}},
+ )
+ )
+
+ heading = document.xpath("//h2[starts-with(., 'Due today')]")[0]
+ assert heading.text_content() == f"Due today ({total})"
+ assert heading.xpath("following-sibling::ul[1]/li/a/text()") == [
+ f"Task {index}" for index in range(1, min(total, 10) + 1)
+ ]
+ if total > 10:
+ task_label = "task" if total == 11 else "tasks"
+ remaining_link = heading.xpath("following-sibling::p[1]/a")[0]
+ assert remaining_link.text_content() == f"+{total - 10} more {task_label} due today"
+ assert remaining_link.get("href") == due_today_url
+ else:
+ assert "more task" not in document.text_content()
diff --git a/products/customer_analytics/frontend/CustomerAnalyticsScene.test.tsx b/products/customer_analytics/frontend/CustomerAnalyticsScene.test.tsx
index 64b91c5860c5..7723426e0755 100644
--- a/products/customer_analytics/frontend/CustomerAnalyticsScene.test.tsx
+++ b/products/customer_analytics/frontend/CustomerAnalyticsScene.test.tsx
@@ -2,6 +2,7 @@ import '@testing-library/jest-dom'
import { cleanup, render, screen } from '@testing-library/react'
import { Provider } from 'kea'
+import { router } from 'kea-router'
import type { ReactNode } from 'react'
import { FEATURE_FLAGS } from 'lib/constants'
@@ -65,6 +66,42 @@ describe('CustomerAnalyticsScene', () => {
featureFlagLogic.unmount()
})
+ it.each([
+ [
+ 'customerAnalyticsTasks',
+ '/customer_analytics/tasks',
+ 'Feature requests',
+ '/customer_analytics/feature-requests',
+ ],
+ [
+ 'customerAnalyticsFeatureRequests',
+ '/customer_analytics/feature-requests',
+ 'Tasks',
+ '/customer_analytics/tasks',
+ ],
+ ])('does not carry task filters across tabs from %s', (scene, path, label, destination) => {
+ router.actions.push(path, { status: 'open', archive: 'active', due: 'overdue', assignee: 'me' })
+ sceneLogic.actions.setScene(Scene.CustomerAnalytics, scene, emptySceneParams)
+ featureFlagLogic.actions.setFeatureFlags(
+ [
+ FEATURE_FLAGS.CUSTOMER_ANALYTICS,
+ FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS,
+ FEATURE_FLAGS.CUSTOMER_ANALYTICS_FEATURE_REQUESTS,
+ ],
+ {
+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS]: true,
+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS]: true,
+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS_FEATURE_REQUESTS]: true,
+ }
+ )
+ render(
+ <Provider>
+ <CustomerAnalyticsScene />
+ </Provider>
+ )
+ expect(screen.getByText(label).closest('a')).toHaveAttribute('href', `/project/997${destination}`)
+ })
+
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],
diff --git a/products/customer_analytics/frontend/CustomerAnalyticsScene.tsx b/products/customer_analytics/frontend/CustomerAnalyticsScene.tsx
index 573bd3084459..dd68cbe2354a 100644
--- a/products/customer_analytics/frontend/CustomerAnalyticsScene.tsx
+++ b/products/customer_analytics/frontend/CustomerAnalyticsScene.tsx
@@ -124,6 +124,26 @@ function CustomerAnalyticsSceneContent(): JSX.Element {
</>
)
+ const tabLink = (url: string, tab: string): string => {
+ const params = { ...searchParams }
+ if (tab !== activeTab && (tab === 'tasks' || activeTab === 'tasks')) {
+ for (const key of [
+ 'search',
+ 'status',
+ 'assignee',
+ 'archive',
+ 'due',
+ 'account',
+ 'sort',
+ 'page',
+ 'task_id',
+ 'source',
+ ]) {
+ delete params[key]
+ }
+ }
+ return combineUrl(url, params).url
+ }
const tabs: LemonTab<string>[] = []
if (featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]) {
@@ -131,25 +151,25 @@ function CustomerAnalyticsSceneContent(): JSX.Element {
key: 'feed',
label: 'Feed',
content: <FeedTabContent />,
- link: combineUrl(urls.customerAnalyticsFeed(), searchParams).url,
+ link: tabLink(urls.customerAnalyticsFeed(), 'feed'),
})
tabs.push({
key: 'accounts',
label: 'Accounts',
content: <AccountsTabContent />,
- link: combineUrl(urls.customerAnalyticsAccounts(), searchParams).url,
+ link: tabLink(urls.customerAnalyticsAccounts(), 'accounts'),
})
tabs.push({
key: 'notes',
label: 'Notes',
content: <AccountNotesTabContent />,
- link: combineUrl(urls.customerAnalyticsNotes(), searchParams).url,
+ link: tabLink(urls.customerAnalyticsNotes(), 'notes'),
})
tabs.push({
key: 'announcements',
label: 'Announcements',
content: <AnnouncementsTabContent />,
- link: combineUrl(urls.customerAnalyticsAnnouncements(), searchParams).url,
+ link: tabLink(urls.customerAnalyticsAnnouncements(), 'announcements'),
})
}
@@ -158,7 +178,7 @@ function CustomerAnalyticsSceneContent(): JSX.Element {
key: 'feature_requests',
label: 'Feature requests',
content: <FeatureRequestsTabContent />,
- link: combineUrl(urls.customerAnalyticsFeatureRequests(), searchParams).url,
+ link: tabLink(urls.customerAnalyticsFeatureRequests(), 'feature_requests'),
})
}
@@ -167,7 +187,7 @@ function CustomerAnalyticsSceneContent(): JSX.Element {
key: 'tasks',
label: 'Tasks',
content: <CustomerTasksInbox canCreate={canCreateCustomerTasks} canViewAll={canViewAllCustomerTasks} />,
- link: combineUrl(urls.customerAnalyticsTasks(), searchParams).url,
+ link: tabLink(urls.customerAnalyticsTasks(), 'tasks'),
})
}
@@ -175,7 +195,7 @@ function CustomerAnalyticsSceneContent(): JSX.Element {
key: 'dashboard',
label: 'Dashboard',
content: dashboardContent,
- link: combineUrl(urls.customerAnalyticsDashboard(), searchParams).url,
+ link: tabLink(urls.customerAnalyticsDashboard(), 'dashboard'),
})
if (featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_JOURNEYS]) {
@@ -183,7 +203,7 @@ function CustomerAnalyticsSceneContent(): JSX.Element {
key: 'journeys',
label: 'Customer journeys',
content: <CustomerJourneys />,
- link: combineUrl(urls.customerAnalyticsJourneys(), searchParams).url,
+ link: tabLink(urls.customerAnalyticsJourneys(), 'journeys'),
})
}
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksFilters.tsx b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksFilters.tsx
index bb04821a3728..610237cf7f70 100644
--- a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksFilters.tsx
+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksFilters.tsx
@@ -78,7 +78,7 @@ export function CustomerTasksFilters({ logic, context, canViewAll = false }: Cus
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 })
+ options.unshift({ key: filters.account.id, label: filters.account.name || filters.account.id })
}
return (
<div className="flex flex-wrap items-center gap-2" data-attr="customer-tasks-filters">
@@ -145,7 +145,7 @@ export function CustomerTasksFilters({ logic, context, canViewAll = false }: Cus
}
>
<LemonButton type="secondary" size="small" sideIcon={<IconChevronDown />}>
- {filters.account?.name ?? 'Account'}
+ {filters.account?.name || 'Account'}
</LemonButton>
</LemonDropdown>
)}
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.test.tsx b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.test.tsx
index 2dc77605ba7d..5ff9197ea4bf 100644
--- a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.test.tsx
+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.test.tsx
@@ -2,8 +2,11 @@ import '@testing-library/jest-dom'
import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'
import { Provider } from 'kea'
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { urls } from 'scenes/urls'
+
import { initKeaTests } from '~/test/init'
import { accountsList, customerTasksList } from 'products/customer_analytics/frontend/generated/api'
@@ -14,6 +17,7 @@ import { CustomerTasksTable } from './CustomerTasksTable'
jest.mock('products/customer_analytics/frontend/generated/api', () => ({
accountsList: jest.fn(),
+ accountsRetrieve: jest.fn(),
customerTasksArchiveCreate: jest.fn(),
customerTasksCreate: jest.fn(),
customerTasksList: jest.fn(),
@@ -193,4 +197,21 @@ describe('CustomerTasksTable', () => {
expect(findTableHeader(accountTable.getByRole('table'), 'Account')).toBeUndefined()
expect(within(filterBar(accountTable.container)).queryByText('Choose member')).toBeNull()
})
+ test('shows the due window a link asked for', async () => {
+ cleanup()
+ logic.unmount()
+ router.actions.push(urls.customerAnalyticsTasks(), { due: 'overdue' })
+ logic = customerTasksLogic({ context: 'inbox' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ const inbox = render(
+ <Provider>
+ <CustomerTasksTable logic={logic} context="inbox" canViewAll />
+ </Provider>
+ )
+
+ expect(within(filterBar(inbox.container)).queryByText('Overdue')).not.toBeNull()
+ expect(within(filterBar(inbox.container)).queryByText('Any time')).toBeNull()
+ })
})
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.test.ts b/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.test.ts
index ced1f3d5aa2c..fd98a67e44b0 100644
--- a/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.test.ts
+++ b/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.test.ts
@@ -3,9 +3,11 @@ import type { CustomerTaskApi } from 'products/customer_analytics/frontend/gener
import {
customerTaskDueBounds,
customerTaskEditDisabledReason,
+ customerTaskSearchParams,
customerTasksQuery,
defaultCustomerTaskFilters,
hasCustomerTaskFilters,
+ parseCustomerTaskSearchParams,
} from './customerTaskFilters'
import type { CustomerTaskDueFilter, CustomerTasksContext } from './customerTaskFilters'
@@ -115,4 +117,45 @@ describe('customer task filter helpers', () => {
)
).toMatchObject({ assigned_to: assignedTo })
})
+ test.each([
+ ['the inbox defaults', {}],
+ ['a filtered view', { status: 'all', assignee: 'unassigned', due: 'overdue', archive: 'archived', page: '3' }],
+ [
+ 'a named member and an account',
+ { assignee: '42', account: '0199ed4a-5c03-0000-3220-df21df612e95', sort: '-updated_at' },
+ ],
+ ['a search', { search: 'renewal' }],
+ ['a whitespace search the query still sends', { search: ' ' }],
+ ])('round-trips %s through the search params', (_, params) => {
+ expect(customerTaskSearchParams(parseCustomerTaskSearchParams(params))).toEqual(params)
+ })
+
+ test.each([
+ ['an unknown status', { status: 'archived' }, { status: 'open' }],
+ ['an unknown due window', { due: 'next_week' }, { due: 'any' }],
+ ['an unknown archive state', { archive: 'deleted' }, { archiveState: 'active' }],
+ ['a non-member assignee', { assignee: 'someone' }, { assignee: 'me' }],
+ ['a negative member id', { assignee: '-1' }, { assignee: 'me' }],
+ ['an out-of-range member id', { assignee: '2147483648' }, { assignee: 'me' }],
+ ['an empty account', { account: '' }, { account: null }],
+ ['a path-shaped account', { account: '../../x' }, { account: null }],
+ ])('falls back to the inbox default for %s', (_, params, expected) => {
+ expect(parseCustomerTaskSearchParams(params).filters).toMatchObject(expected)
+ })
+
+ test.each([
+ ['an unknown column', { sort: 'priority' }, 'due_at'],
+ ['a known column', { sort: '-name' }, '-name'],
+ ])('resolves the ordering for %s', (_, params, expected) => {
+ expect(parseCustomerTaskSearchParams(params).ordering).toBe(expected)
+ })
+
+ test.each([
+ ['no page', {}, 1],
+ ['page zero', { page: '0' }, 1],
+ ['a fractional page', { page: '2.5' }, 1],
+ ['a later page', { page: '4' }, 4],
+ ])('resolves %s', (_, params, expected) => {
+ expect(parseCustomerTaskSearchParams(params).page).toBe(expected)
+ })
})
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.ts b/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.ts
index a6456bb035f6..6ae49f560bab 100644
--- a/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.ts
+++ b/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.ts
@@ -1,6 +1,7 @@
import type { Sorting } from '@posthog/lemon-ui'
import { dayjs, dayjsLocalToTimezone, dayjsNowInTimezone } from 'lib/dayjs'
+import { isUUIDLike } from 'lib/utils/guards'
import type {
CustomerTaskApi,
@@ -14,6 +15,8 @@ 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 MAX_CUSTOMER_TASK_ASSIGNEE_ID = 2_147_483_647
const CUSTOMER_TASK_ORDERINGS = [
'name',
'-name',
@@ -200,6 +203,95 @@ export function customerTasksQuery(
return query
}
+export const CUSTOMER_TASK_FILTER_URL_KEYS = ['search', 'status', 'assignee', 'archive', 'due', 'account'] as const
+
+export const CUSTOMER_TASK_URL_KEYS = [...CUSTOMER_TASK_FILTER_URL_KEYS, 'sort', 'page'] as const
+
+// Event names are consumed by product analytics, so changing one splits its historical data.
+export const CustomerTaskEvents = {
+ InboxViewed: 'customer analytics tasks inbox viewed',
+} as const
+
+export type CustomerTaskUrlState = {
+ filters: CustomerTaskFilters
+ ordering: CustomerTaskOrdering
+ page: number
+}
+
+// The inbox keeps `overdue` and `today` symbolic in the link so customerTaskDueBounds resolves them
+// against the project timezone when the page opens, not when the link was written.
+export function customerTaskSearchParams(state: CustomerTaskUrlState): Record<string, string> {
+ const defaults = defaultCustomerTaskFilters('inbox')
+ const params: Record<string, string> = {}
+ if (state.filters.search) {
+ params.search = state.filters.search
+ }
+ if (state.filters.status !== defaults.status) {
+ params.status = state.filters.status
+ }
+ if (state.filters.assignee !== defaults.assignee) {
+ params.assignee = String(state.filters.assignee)
+ }
+ if (state.filters.archiveState !== defaults.archiveState) {
+ params.archive = state.filters.archiveState
+ }
+ if (state.filters.due !== defaults.due) {
+ params.due = state.filters.due
+ }
+ if (state.filters.account) {
+ params.account = state.filters.account.id
+ }
+ if (state.ordering !== DEFAULT_CUSTOMER_TASK_ORDERING) {
+ params.sort = state.ordering
+ }
+ if (state.page > 1) {
+ params.page = String(state.page)
+ }
+ return params
+}
+
+function parseAssignee(value: unknown): CustomerTaskAssigneeFilter | null {
+ if (value === 'any' || value === 'me' || value === 'unassigned') {
+ return value
+ }
+ const memberId = Number(value)
+ return Number.isInteger(memberId) && memberId > 0 && memberId <= MAX_CUSTOMER_TASK_ASSIGNEE_ID ? memberId : null
+}
+
+function parseOneOf<T extends string>(value: unknown, allowed: readonly T[]): T | null {
+ return allowed.some((candidate) => candidate === value) ? (value as T) : null
+}
+
+function parseOption<T extends string>(value: unknown, options: readonly { value: T }[]): T | null {
+ return parseOneOf(
+ value,
+ options.map((option) => option.value)
+ )
+}
+
+// A link only carries the account id, so the name stays empty until the logic resolves it.
+export function parseCustomerTaskSearchParams(searchParams: Record<string, any>): CustomerTaskUrlState {
+ const defaults = defaultCustomerTaskFilters('inbox')
+ const page = Number(searchParams.page)
+ return {
+ filters: {
+ // The router parses a purely numeric query param into a number, so `?search=123` arrives
+ // as 123. A string check would drop it and the link would show an unfiltered list.
+ search: searchParams.search != null ? String(searchParams.search) : '',
+ status: parseOption(searchParams.status, CUSTOMER_TASK_STATUS_OPTIONS) ?? defaults.status,
+ assignee: parseAssignee(searchParams.assignee) ?? defaults.assignee,
+ archiveState: parseOption(searchParams.archive, CUSTOMER_TASK_ARCHIVE_OPTIONS) ?? defaults.archiveState,
+ account:
+ typeof searchParams.account === 'string' && isUUIDLike(searchParams.account)
+ ? { id: searchParams.account, name: '' }
+ : null,
+ due: parseOption(searchParams.due, CUSTOMER_TASK_DUE_OPTIONS) ?? defaults.due,
+ },
+ ordering: parseOneOf(searchParams.sort, CUSTOMER_TASK_ORDERINGS) ?? DEFAULT_CUSTOMER_TASK_ORDERING,
+ page: Number.isInteger(page) && page > 0 ? page : 1,
+ }
+}
+
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
index c92f3ef09b0f..50ab7a4d539a 100644
--- a/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.test.ts
+++ b/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.test.ts
@@ -1,30 +1,37 @@
import { MOCK_DEFAULT_USER } from 'lib/api.mock'
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
import { ApiError } from 'lib/api-error'
+import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import { initKeaTests } from '~/test/init'
import {
accountsList,
+ accountsRetrieve,
customerTasksCreate,
customerTasksList,
+ customerTasksRetrieve,
customerTasksPartialUpdate,
} from 'products/customer_analytics/frontend/generated/api'
import type { CustomerTaskApi } from 'products/customer_analytics/frontend/generated/api.schemas'
-import { customerTasksPersistencePrefix } from './customerTaskFilters'
+import { customerTasksPersistencePrefix, parseCustomerTaskSearchParams } from './customerTaskFilters'
import { customerTasksLogic } from './customerTasksLogic'
jest.mock('products/customer_analytics/frontend/generated/api', () => ({
accountsList: jest.fn(),
+ accountsRetrieve: jest.fn(),
customerTasksArchiveCreate: jest.fn(),
customerTasksCreate: jest.fn(),
customerTasksList: jest.fn(),
+ customerTasksRetrieve: jest.fn(),
customerTasksPartialUpdate: jest.fn(),
customerTasksRestoreCreate: jest.fn(),
}))
@@ -33,6 +40,10 @@ const mockCreate = customerTasksCreate as jest.MockedFunction<typeof customerTas
const mockList = customerTasksList as jest.MockedFunction<typeof customerTasksList>
const mockAccounts = accountsList as jest.MockedFunction<typeof accountsList>
const mockUpdate = customerTasksPartialUpdate as jest.MockedFunction<typeof customerTasksPartialUpdate>
+const mockAccount = accountsRetrieve as jest.MockedFunction<typeof accountsRetrieve>
+
+const URL_ACCOUNT_ID = '0199ed4a-5c03-0000-3220-df21df612e95'
+const SECOND_URL_ACCOUNT_ID = '0199ed4a-5c03-0000-3220-df21df612e96'
function task(canEdit = true): CustomerTaskApi {
return {
@@ -64,6 +75,8 @@ describe('customerTasksLogic', () => {
mockList.mockResolvedValue({ count: 0, next: null, previous: null, results: [] })
mockAccounts.mockResolvedValue({ count: 0, next: null, previous: null, results: [] })
mockUpdate.mockResolvedValue(task())
+ mockAccount.mockResolvedValue({ id: URL_ACCOUNT_ID, name: 'Acme' } as never)
+ router.actions.push(urls.customerAnalyticsTasks())
})
afterEach(() => {
@@ -91,6 +104,17 @@ describe('customerTasksLogic', () => {
)
})
+ test('opens a linked task even when persisted filters exclude it', async () => {
+ const linkedTask = task()
+ ;(customerTasksRetrieve as jest.Mock).mockResolvedValue(linkedTask)
+ router.actions.push(urls.customerAnalyticsTasks(), { task_id: linkedTask.id })
+ logic = customerTasksLogic({ context: 'inbox' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.modalTask).toEqual(linkedTask)
+ expect(logic.values.modalOpen).toBe(true)
+ })
+
test('creates a task for the current account without exposing a different account', async () => {
logic = customerTasksLogic({ context: 'account', accountId: 'account-1' })
logic.mount()
@@ -179,6 +203,7 @@ describe('customerTasksLogic', () => {
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.filters).toMatchObject({ status: 'completed', assignee: 'unassigned' })
logic.unmount()
+ router.actions.push(urls.customerAnalyticsTasks())
const otherUserLogic = customerTasksLogic({
context: 'inbox',
@@ -263,4 +288,154 @@ describe('customerTasksLogic', () => {
await expectLogic(logic).toFinishAllListeners()
expect(mockUpdate).not.toHaveBeenCalled()
})
+ test('lets a link override the filters the person left behind', async () => {
+ const prefix = customerTasksPersistencePrefix(1, 42)
+ logic = customerTasksLogic({ context: 'inbox', canViewAll: true, persistPrefix: prefix })
+ logic.mount()
+ logic.actions.setFilters({ status: 'completed', assignee: 'unassigned' })
+ await expectLogic(logic).toFinishAllListeners()
+ logic.unmount()
+
+ router.actions.push(urls.customerAnalyticsTasks(), { due: 'overdue', assignee: 'me' })
+ mockList.mockClear()
+ logic = customerTasksLogic({ context: 'inbox', canViewAll: true, persistPrefix: prefix })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.filters).toMatchObject({ status: 'open', assignee: 'me', due: 'overdue' })
+ expect(mockList).toHaveBeenCalledTimes(1)
+ expect(mockList).toHaveBeenLastCalledWith(
+ expect.any(String),
+ expect.objectContaining({ assigned_to: 'me', statuses: 'open,in_progress', due_before: expect.any(String) })
+ )
+ })
+
+ test('keeps the persisted filters when the link carries none', async () => {
+ const prefix = customerTasksPersistencePrefix(1, 42)
+ logic = customerTasksLogic({ context: 'inbox', canViewAll: true, persistPrefix: prefix })
+ logic.mount()
+ logic.actions.setFilters({ status: 'completed' })
+ await expectLogic(logic).toFinishAllListeners()
+ logic.unmount()
+
+ router.actions.push(urls.customerAnalyticsTasks())
+ logic = customerTasksLogic({ context: 'inbox', canViewAll: true, persistPrefix: prefix })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.filters).toMatchObject({ status: 'completed' })
+ })
+
+ test('keeps the persisted filters when a link only sorts', async () => {
+ const prefix = customerTasksPersistencePrefix(1, 42)
+ logic = customerTasksLogic({ context: 'inbox', canViewAll: true, persistPrefix: prefix })
+ logic.mount()
+ logic.actions.setFilters({ status: 'completed' })
+ await expectLogic(logic).toFinishAllListeners()
+ logic.unmount()
+
+ router.actions.push(urls.customerAnalyticsTasks(), { sort: '-name' })
+ logic = customerTasksLogic({ context: 'inbox', canViewAll: true, persistPrefix: prefix })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.filters).toMatchObject({ status: 'completed' })
+ expect(logic.values.ordering).toBe('-name')
+ })
+
+ test('keeps a digits-only search the router reads back as a number', async () => {
+ router.actions.push(`${urls.customerAnalyticsTasks()}?search=123`)
+ logic = customerTasksLogic({ context: 'inbox', canViewAll: true })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(router.values.searchParams.search).toBe(123)
+ expect(logic.values.filters.search).toBe('123')
+ expect(mockList).toHaveBeenLastCalledWith(expect.any(String), expect.objectContaining({ search: '123' }))
+
+ logic.actions.setSearch('456')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.filters.search).toBe('456')
+ })
+
+ test('writes the inbox filters, sort and page back to the link', async () => {
+ logic = customerTasksLogic({ context: 'inbox', canViewAll: true })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setFilters({ due: 'overdue', status: 'all' })
+ logic.actions.setTaskOrdering('-updated_at')
+ logic.actions.setPage(2)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(router.values.searchParams).toMatchObject({
+ due: 'overdue',
+ status: 'all',
+ sort: '-updated_at',
+ page: 2,
+ })
+ expect(parseCustomerTaskSearchParams(router.values.searchParams)).toEqual({
+ filters: logic.values.filters,
+ ordering: logic.values.ordering,
+ page: logic.values.page,
+ })
+ })
+
+ test('names the account a link can only identify by id', async () => {
+ router.actions.push(urls.customerAnalyticsTasks(), { account: URL_ACCOUNT_ID })
+ logic = customerTasksLogic({ context: 'inbox', canViewAll: true })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockAccount).toHaveBeenCalledWith(expect.any(String), URL_ACCOUNT_ID)
+ expect(logic.values.filters.account).toEqual({ id: URL_ACCOUNT_ID, name: 'Acme' })
+ expect(mockList).toHaveBeenLastCalledWith(
+ expect.any(String),
+ expect.objectContaining({ account_id: URL_ACCOUNT_ID })
+ )
+ })
+
+ test('ignores a slow account read for an account the person moved off', async () => {
+ let resolveAccount = (): void => {}
+ mockAccount.mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveAccount = () => resolve({ id: URL_ACCOUNT_ID, name: 'Acme' } as never)
+ })
+ )
+ router.actions.push(urls.customerAnalyticsTasks(), { account: URL_ACCOUNT_ID })
+ logic = customerTasksLogic({ context: 'inbox', canViewAll: true })
+ logic.mount()
+
+ logic.actions.setAccountFilter({ id: SECOND_URL_ACCOUNT_ID, name: 'Initech' })
+ resolveAccount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.filters.account).toEqual({ id: SECOND_URL_ACCOUNT_ID, name: 'Initech' })
+ })
+
+ test('reports where an inbox visit came from once, then drops the source', async () => {
+ const captureSpy = jest.spyOn(posthog, 'capture')
+ router.actions.push(urls.customerAnalyticsTasks(), { source: 'task_digest', due: 'overdue' })
+ logic = customerTasksLogic({ context: 'inbox', canViewAll: true })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(captureSpy).toHaveBeenCalledWith('customer analytics tasks inbox viewed', { source: 'task_digest' })
+ expect(router.values.searchParams).not.toHaveProperty('source')
+ expect(logic.values.filters.due).toBe('overdue')
+ captureSpy.mockRestore()
+ })
+
+ test('leaves the link alone for the account tab', async () => {
+ router.actions.push(urls.customerAnalyticsTasks())
+ logic = customerTasksLogic({ context: 'account', accountId: 'account-1' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setFilters({ status: 'completed' })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(router.values.searchParams).toEqual({})
+ })
})
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.ts b/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.ts
index 08b6464caee2..b8027ecfa7c8 100644
--- a/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.ts
+++ b/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.ts
@@ -13,20 +13,27 @@ import {
selectors,
} from 'kea'
import { loaders } from 'kea-loaders'
+import { router, urlToAction } from 'kea-router'
+import posthog from 'posthog-js'
import { lemonToast, type PaginationManual, type Sorting } from '@posthog/lemon-ui'
import { ApiError } from 'lib/api-error'
+import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
+import { objectsEqual } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import type { UserType } from '~/types'
import {
accountsList,
+ accountsRetrieve,
customerTasksArchiveCreate,
customerTasksCreate,
customerTasksList,
+ customerTasksRetrieve,
customerTasksPartialUpdate,
customerTasksRestoreCreate,
} from 'products/customer_analytics/frontend/generated/api'
@@ -41,14 +48,20 @@ import type {
} from 'products/customer_analytics/frontend/generated/api.schemas'
import {
+ CUSTOMER_TASK_FILTER_URL_KEYS,
+ CUSTOMER_TASK_URL_KEYS,
+ customerTaskSearchParams,
+ CustomerTaskEvents,
customerTasksQuery,
DEFAULT_CUSTOMER_TASK_ORDERING,
defaultCustomerTaskFilters,
hasCustomerTaskFilters,
+ parseCustomerTaskSearchParams,
type CustomerTaskAccountFilter,
type CustomerTaskFilters,
type CustomerTaskOrdering,
type CustomerTasksContext,
+ type CustomerTaskUrlState,
customerTaskOrderingToSorting,
customerTaskSortingToOrdering,
} from './customerTaskFilters'
@@ -92,6 +105,7 @@ export interface customerTasksLogicValues {
user: UserType | null
}
export interface customerTasksLogicActions {
+ openTaskFromUrl: (taskId: string) => { taskId: string }
closeModal: () => void
createTask: (task: CustomerTaskCreateApi) => { task: CustomerTaskCreateApi }
loadAccountOptions: (payload: { query: string }) => { query: string }
@@ -106,6 +120,8 @@ export interface customerTasksLogicActions {
setAccountFilter: (account: CustomerTaskAccountFilter | null) => { account: CustomerTaskAccountFilter | null }
setAccountFilterOpen: (open: boolean) => { open: boolean }
setFilters: (filters: Partial<CustomerTaskFilters>) => { filters: Partial<CustomerTaskFilters> }
+ setFiltersFromUrl: (state: CustomerTaskUrlState) => { state: CustomerTaskUrlState }
+ setAccountFilterName: (name: string) => { name: string }
setTaskOrdering: (ordering: CustomerTaskOrdering) => { ordering: CustomerTaskOrdering }
setTaskSorting: (sorting: Sorting | null) => { sorting: Sorting | null }
setPage: (page: number) => { page: number }
@@ -127,6 +143,10 @@ export type customerTasksLogicType = MakeLogicType<
CustomerTasksLogicProps
>
+function taskUrlState(values: customerTasksLogicValues): CustomerTaskUrlState {
+ return { filters: values.filters, ordering: values.ordering, page: values.page }
+}
+
// 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 {
@@ -147,9 +167,12 @@ export const customerTasksLogic: LogicWrapper<customerTasksLogicType> = kea<cust
path(['products', 'customer_analytics', 'frontend', 'components', 'CustomerTasks', 'customerTasksLogic']),
connect(() => ({ values: [teamLogic, ['currentTeamId', 'timezone'], userLogic, ['user']] })),
actions({
+ openTaskFromUrl: (taskId: string) => ({ taskId }),
loadTaskPage: true,
loadAccountOptions: (payload: { query: string }) => payload,
setFilters: (filters: Partial<CustomerTaskFilters>) => ({ filters }),
+ setFiltersFromUrl: (state: CustomerTaskUrlState) => ({ state }),
+ setAccountFilterName: (name: string) => ({ name }),
setTaskOrdering: (ordering: CustomerTaskOrdering) => ({ ordering }),
setTaskSorting: (sorting: Sorting | null) => ({ sorting }),
setSearch: (search: string) => ({ search }),
@@ -235,14 +258,25 @@ export const customerTasksLogic: LogicWrapper<customerTasksLogicType> = kea<cust
...s,
account: a.account,
}),
+ setAccountFilterName: (s: CustomerTaskFilters, a: { name: string }) =>
+ s.account ? { ...s, account: { ...s.account, name: a.name } } : s,
+ setFiltersFromUrl: (_: CustomerTaskFilters, a: { state: CustomerTaskUrlState }) => a.state.filters,
resetFilters: () => defaultCustomerTaskFilters(props.context),
},
],
- ordering: [DEFAULT_CUSTOMER_TASK_ORDERING, { setTaskOrdering: (_, { ordering }) => ordering }],
+ ordering: [
+ DEFAULT_CUSTOMER_TASK_ORDERING,
+ {
+ setTaskOrdering: (_, { ordering }) => ordering,
+ setFiltersFromUrl: (_: CustomerTaskOrdering, a: { state: CustomerTaskUrlState }) =>
+ a.state.ordering,
+ },
+ ],
page: [
1,
{
setPage: (_: number, a: { page: number }) => a.page,
+ setFiltersFromUrl: (_: number, a: { state: CustomerTaskUrlState }) => a.state.page,
setFilters: () => 1,
setSearch: () => 1,
setAccountFilter: () => 1,
@@ -360,7 +394,37 @@ export const customerTasksLogic: LogicWrapper<customerTasksLogicType> = kea<cust
],
})),
listeners(({ actions, props, values }) => ({
+ openTaskFromUrl: async ({ taskId }, breakpoint) => {
+ if (values.currentTeamId === null) {
+ return
+ }
+ try {
+ const task = await customerTasksRetrieve(String(values.currentTeamId), taskId)
+ breakpoint()
+ actions.openEditModal(task)
+ } catch (error) {
+ breakpoint()
+ lemonToast.error(
+ taskWriteFailureMessage(error, 'Could not open the task. Refresh the page to try again.')
+ )
+ }
+ },
setFilters: () => actions.loadTaskPage(),
+ setFiltersFromUrl: async () => {
+ actions.loadTaskPage()
+ const account = values.filters.account
+ if (!account || account.name || values.currentTeamId === null) {
+ return
+ }
+ try {
+ const resolved = await accountsRetrieve(String(values.currentTeamId), account.id)
+ if (values.filters.account?.id === account.id) {
+ actions.setAccountFilterName(resolved.name)
+ }
+ } catch {
+ // The account filter still applies; the control falls back to its generic label.
+ }
+ },
setSearch: () => actions.loadTaskPage(),
setAccountFilter: () => actions.loadTaskPage(),
setPage: () => actions.loadTaskPage(),
@@ -502,10 +566,65 @@ export const customerTasksLogic: LogicWrapper<customerTasksLogicType> = kea<cust
}
},
})),
+ trackedActionToUrl(({ props, values }) => {
+ if (props.context !== 'inbox') {
+ return {}
+ }
+ const toUrl = (): [string, Record<string, any>, any, { replace: boolean }] => {
+ const searchParams = { ...router.values.searchParams }
+ for (const key of CUSTOMER_TASK_URL_KEYS) {
+ delete searchParams[key]
+ }
+ Object.assign(searchParams, customerTaskSearchParams(taskUrlState(values)))
+ return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]
+ }
+ return {
+ setFilters: toUrl,
+ setSearch: toUrl,
+ setAccountFilter: toUrl,
+ setPage: toUrl,
+ setTaskOrdering: toUrl,
+ resetFilters: toUrl,
+ }
+ }),
+ urlToAction(({ actions, props, values }) => {
+ if (props.context !== 'inbox') {
+ return {}
+ }
+ return {
+ [urls.customerAnalyticsTasks()]: (_, searchParams) => {
+ if (typeof searchParams.task_id === 'string' && searchParams.task_id !== values.modalTask?.id) {
+ actions.openTaskFromUrl(searchParams.task_id)
+ }
+ const parsed = parseCustomerTaskSearchParams(searchParams)
+ // A link that names a filter decides the whole view, so its filters replace the ones
+ // the person left behind. A link that only sorts or pages leaves them alone.
+ const hasFiltersInUrl = CUSTOMER_TASK_FILTER_URL_KEYS.some((key) => searchParams[key] !== undefined)
+ const next: CustomerTaskUrlState = {
+ filters: hasFiltersInUrl ? parsed.filters : values.filters,
+ ordering: parsed.ordering,
+ page: parsed.page,
+ }
+ const current = customerTaskSearchParams(taskUrlState(values))
+ if (!objectsEqual(current, customerTaskSearchParams(next))) {
+ actions.setFiltersFromUrl(next)
+ }
+ },
+ }
+ }),
afterMount(({ actions, props }) => {
actions.loadTaskPage()
if (props.context === 'inbox') {
actions.loadAccountOptions({ query: '' })
+ const { source, ...rest } = router.values.searchParams
+ posthog.capture(CustomerTaskEvents.InboxViewed, {
+ source: typeof source === 'string' ? source : null,
+ })
+ // Drop the source so a second visit in the same session, and any link the person copies,
+ // are not attributed to whatever brought them here first.
+ if (source !== undefined) {
+ router.actions.replace(router.values.location.pathname, rest, router.values.hashParams)
+ }
}
}),
])