:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(customer-analytics): add task digest notification settings (#102658)
posthog[bot]0a7438fd6729
diff --git a/docs/internal/customer-analytics-tasks-workflows.md b/docs/internal/customer-analytics-tasks-workflows.mdindex 4a7c814169f4..69f6b40f4f03 100644--- a/docs/internal/customer-analytics-tasks-workflows.md+++ b/docs/internal/customer-analytics-tasks-workflows.md@@ -63,3 +63,19 @@ The overdue link selects `status=open`, `assignee=me`, `archive=active`, and `duExplicit 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.++## Task digest preferences++In **Settings > Customer analytics > Notifications**, each user can enable task digest emails and choose a send time and a cadence of **Weekdays** or **Every day**.+The time uses the project timezone shown beside the control.+The time dropdown offers half-hour choices and preserves any previously saved custom time.+Preferences are disabled by default and apply only to the current user in the project.+Use **Save** to persist changes; a failed save keeps the draft available to retry.+The same Notifications section contains the existing event stream settings, and existing event stream settings links still open it.+Task digest controls require the customer tasks feature; event stream controls retain their existing feature access.++The user-config API stores preferences in `UserCustomerAnalyticsConfig.properties.task_digest`, with `enabled`, `send_time` (`HH:MM`), and `cadence` (`weekdays` or `every_day`).+`GET` and `PATCH /api/projects/{project_id}/user_customer_analytics_config/@me/` expose this object alongside `pinned_properties`.+Omitted fields retain their stored values, including fields within `task_digest`.+Missing preferences return disabled, 09:00, and weekdays without changing other stored settings.+Scheduling and email delivery are implemented separately.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 6a2f73124aef..c296a33cb49d 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -2388,6 +2388,46 @@ snapshots:hash: v1.k794b7964.88c3253cfe129808e538e59d6eb8eb8fa948540042edd8248e9836cccce1a4af.RnBgBRDh8HKCK7PYoGDeuXTEbHHl5vnlNpU9IGLwFykcustomer-analytics-google-account-backfill--invalid-range--light:hash: v1.k794b7964.7eb703bdf24bb2b8adcb1f8d90097dec56b85e0e0b6778e0ea0c68a9c6d9fbb0.W0aCVMrWUlFruWBqwJYpotdaFJ3BfR9P16qCdJn5jBc+ customer-analytics-task-digest--disabled--dark:+ hash: v1.k794b7964.ae01056717a47bec34aec4b29b51dbffdbad9f3beadf2f27835712948b272416.2qnYq9dgh27zEXhBFUmmV0Q6ncIhXJxbqokBLN_TMp0+ customer-analytics-task-digest--disabled--light:+ hash: v1.k794b7964.0f54b9aae06c11ec7e578b8e719a6601a02c8a046dbf5637ba1e7dfa7ee29afa.ezFFvdbACX_INpRrm2sYV4iY7st0k_09kTVaQqXOLQI+ customer-analytics-task-digest--disabled-narrow--dark:+ hash: v1.k794b7964.30ddcd7c3a50d2099d8b3a51fba73dea79f55bf5cb7be3e6fbe5632c05dd4991.IcNLpPiQMmzdjVmCVaotmFOPaamRZ-4vow5E5hsJ2qc+ customer-analytics-task-digest--disabled-narrow--light:+ hash: v1.k794b7964.cfe4fb8db36af42a105e28c7ac05c00feeacf936efe3ce347635f073f0f7b232.N1423RxucB1UkEcmXzxVnuO0FbrHRV-P7h86Mwp-5Rs+ customer-analytics-task-digest--enabled--dark:+ hash: v1.k794b7964.c46b4707a793a0da2ee25765d23c8d35805937da2ea9d8eab32b6ea66304ad14.OZmysS_2ZIu66DVe1-fouywP8vno_Q3rFt2E5CiscBs+ customer-analytics-task-digest--enabled--light:+ hash: v1.k794b7964.d9a955d9720984912203a138ef78e3d6a859795e0b24b8691289f9454d17e312.Ffs7-EAa7kd6CU9VTfXUvb1ZAmcK8a1idlx7pV6DsBg+ customer-analytics-task-digest--enabled-narrow--dark:+ hash: v1.k794b7964.e6ade4ff02fae015a9f2e6dcfb78c4c896c29634467a3eadcce2a75128c78d6d.PFA2_r7X9cyR2w7kL6NSSq6IGiIlAeczAWM6rjuns1g+ customer-analytics-task-digest--enabled-narrow--light:+ hash: v1.k794b7964.18ea967140e7b9b0d583553509a649356f785e8c280b54d0f6527d403919fd5e.tA-t5UJ5KFeu7wwRJJNzyPr0t4yS3FVOPjtLbgwOEyk+ customer-analytics-task-digest--load-failed--dark:+ hash: v1.k794b7964.2bffe522ea75433e18a4ce276ce3b36dbc3929dc6476c34d9a754794e7255c83.pn4Ztq9oSAteDdbQ0oe5owukoy4eOhCZmtRl3Lx7ckA+ customer-analytics-task-digest--load-failed--light:+ hash: v1.k794b7964.63433084c821666f5916c099049d56ea37f7b6a2299bc322247f81dfed888a96.9XOFbpuOGqtgqZovnDYKzGOmPAuHJ8iYX60V-ArT6os+ customer-analytics-task-digest--loading--dark:+ hash: v1.k794b7964.491a12056bf7e9e6e44c38340458cbaf53d47d1ae5bc8a93faaeb3ae634793d6.lo8eK2aIIHQtpzAIgdt-DuHuJyxGPgC6s3swxdSM2vI+ customer-analytics-task-digest--loading--light:+ hash: v1.k794b7964.535d0384156a59ab65a24aa868d723d335a2ad8035c34491fec3016293ffa3eb.n294201Z3nIUQakrdMU07ov4HEFOI_pJSrawKBau8Rs+ customer-analytics-task-digest--notifications--dark:+ hash: v1.k794b7964.3843d72378b750f2eb01e02d6f42e4515c8d62d7cde08cc3893b2fdbf68ed0fe.JVtyYacQVPhvThsqZPCxMm20xQYFPoPbw5sK_GvZ5Vk+ customer-analytics-task-digest--notifications--light:+ hash: v1.k794b7964.66f89754ed284d8c85694fc250dec4309ccf9b66b221cb4390c4b7efbffe20a1.xOkpRkWsoNkzPM2pxlZ2VLZxEHmtTNqo1BdRayELwBY+ customer-analytics-task-digest--notifications-narrow--dark:+ hash: v1.k794b7964.088d47f5affb863e93c88529c65b172b1c996508aa512ad0ac8e5964c18c3aca.r9eBxFpj4unGsP0j25OPJWHRrNLMEEaaG_03ZSyvkZc+ customer-analytics-task-digest--notifications-narrow--light:+ hash: v1.k794b7964.b91854f1f44cdba877ef5768af381a3c255dd0328852b6829196b9560d45da08.STtMTSSf1Ns26_1UoEaLnmm0xIrlbwdm_-SA_bOh1SU+ customer-analytics-task-digest--save-failed--dark:+ hash: v1.k794b7964.ae01056717a47bec34aec4b29b51dbffdbad9f3beadf2f27835712948b272416.P-KUGupBYEekBhsAsk9rN6HBORSmfHFNrf0wC0mUvNM+ customer-analytics-task-digest--save-failed--light:+ hash: v1.k794b7964.0f54b9aae06c11ec7e578b8e719a6601a02c8a046dbf5637ba1e7dfa7ee29afa.rQ8i--ME9FUQUMJUXr2c2qsCkrGuSHjF7ADC1O-gReo+ customer-analytics-task-digest--saving--dark:+ hash: v1.k794b7964.ae01056717a47bec34aec4b29b51dbffdbad9f3beadf2f27835712948b272416.ZlnJyGQQVpAQjUJGC2vWJ24-RI0fBAIuQWoesC_kfu0+ customer-analytics-task-digest--saving--light:+ hash: v1.k794b7964.0f54b9aae06c11ec7e578b8e719a6601a02c8a046dbf5637ba1e7dfa7ee29afa.wzf112F8I-WiRTpSK7sJTTxLWojQAu-fok0y6YGkXKodata-catalog-metric-tests--empty--dark:hash: v1.k794b7964.8c5bed6e45ecc0ce83e4fcb37057c6d87aad0a974e8ed035b9fc9e67a8c1dbd9.jNr2vi0P9-nEfiRddJJjwFg4ZekchSpeyXxdxNfAF1Edata-catalog-metric-tests--empty--light:@@ -7489,9 +7529,9 @@ snapshots:scenes-app-customer-analytics-track-rules--configured--light:hash: v1.k794b7964.bba94b79a426d56662ce339a8b85df4a5330e7a282296df81a6b31250d660d5d.XM42-sjLOeTezLtWry0RtWTIZCa60BN7uzEXh_B2_fsscenes-app-customer-analytics-track-rules--feature-gate-off--dark:- hash: v1.k794b7964.68dfb562def4db8fb8b8082b864115e315caf6662c6be713af5572a9f263bc57.z9X01dYMXIIFZXt9s1TM1GrALc0HZlSgEzRxu85W9Kg+ hash: v1.k794b7964.1953582915005b1b667aab6d6426a6f0110650326acafd80677457fd29a140e0.5gBcBS7LPWYkZa9dF6Z3DgpEhD9zY-H6phsW6MULrTUscenes-app-customer-analytics-track-rules--feature-gate-off--light:- hash: v1.k794b7964.365fcdc6fae12bf1f704d0bc3a6d8992b7fea05cb5d48eb78bfc1f2f24fac929.ad9HX_I4T-esxuMW3YamDdHs0pZbTQRDjBRsSvX8ReA+ hash: v1.k794b7964.d91ddc308f5de2da97c5969d4255d9176301fe62945033e2a1a6ec03087e3b88.f2cFIIZhVcmAi062Ftb_y3IHxG73ju_KyWfi8fq8cEwscenes-app-customer-analytics-track-rules--preview--dark:hash: v1.k794b7964.af87275e87b5a74732786b7c875841d4e5e071a537451f64d183c857af870d48.oBT40Wn2N3ewovrkOFYGQc1Tt1kYtsE4h40llof1VLwscenes-app-customer-analytics-track-rules--preview--light:diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex e11ad485abef..1d5fa1425e4f 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -57,7 +57,7 @@ import { AISection } from 'products/conversations/frontend/scenes/settings/AISecimport { GeneralSection } from 'products/conversations/frontend/scenes/settings/GeneralSection'import { NotificationsSection } from 'products/conversations/frontend/scenes/settings/NotificationsSection'import { ZendeskImportSection } from 'products/conversations/frontend/scenes/settings/ZendeskImportSection'-import { CustomerAnalyticsEventStream } from 'products/customer_analytics/frontend/components/EventStream/CustomerAnalyticsEventStream'+import { CustomerAnalyticsNotifications } from 'products/customer_analytics/frontend/components/TaskDigest/CustomerAnalyticsNotifications'import { AccountTrackRules } from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules'import { CustomerAnalyticsAccountConfig } from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomerAnalyticsAccountConfig'import {@@ -551,12 +551,11 @@ export const SETTINGS_MAP: SettingSection[] = [},{id: 'customer-analytics-event-stream',- title: 'Event stream',- description:- "Stream selected customers' events to a Slack channel of your choice in real time. Each team member configures their own stream: pick your events and channel here, then add customers from their account profiles.",- component: <CustomerAnalyticsEventStream />,- flag: ['CUSTOMER_ANALYTICS', 'CUSTOMER_ANALYTICS_CSP'],- keywords: ['event', 'stream', 'live', 'slack', 'accounts'],+ title: 'Notifications',+ description: 'Configure your task digest emails and customer event stream for this project.',+ component: <CustomerAnalyticsNotifications />,+ flag: 'CUSTOMER_ANALYTICS',+ keywords: ['notifications', 'email', 'digest', 'tasks', 'event', 'stream', 'live', 'slack', 'accounts'],},{id: 'customer-analytics-person-properties',diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 902615ca70c4..d0e7ae75c873 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -97,7 +97,11 @@ from products.customer_analytics.backend.facade.contracts import (InvalidCustomPropertyOptions as InvalidCustomPropertyOptions,)from products.customer_analytics.backend.facade.email_matching import schedule_email_thread_link_recalculation-from products.customer_analytics.backend.facade.enums import AccountPropertyPinKind, AccountRelationshipSource+from products.customer_analytics.backend.facade.enums import (+ AccountPropertyPinKind,+ AccountRelationshipSource,+ TaskDigestCadence,+)from products.customer_analytics.backend.logic import (account_presence as _account_presence_logic,account_track_rules as _account_track_rules_logic,@@ -1213,7 +1217,8 @@ def _to_user_customer_analytics_config(pinned_properties=[contracts.PinnedAccountProperty(kind=reference["kind"], id=UUID(str(reference["id"])))for reference in raw_references- ]+ ],+ task_digest=_user_customer_analytics_config_logic.read_task_digest(config),)@@ -1233,6 +1238,24 @@ def update_user_customer_analytics_config(return _to_user_customer_analytics_config(config)+def update_user_task_digest_preferences(+ *,+ team_id: int,+ user_id: int,+ enabled: bool | None = None,+ send_time: time | None = None,+ cadence: str | None = None,+) -> contracts.UserCustomerAnalyticsConfig:+ config = _user_customer_analytics_config_logic.update_task_digest(+ team_id=team_id,+ user_id=user_id,+ enabled=enabled,+ send_time=send_time,+ cadence=TaskDigestCadence(cadence) if cadence is not None else None,+ )+ return _to_user_customer_analytics_config(config)++# --- CustomPropertyDefinition ---diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex e06a753cec11..6c37f20e7f9f 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -59,9 +59,25 @@ class PinnedAccountProperty:id: UUID+TASK_DIGEST_SEND_TIME_FORMAT = "%H:%M"+++@dataclass(frozen=True)+class TaskDigestPreferences:+ """One user's task digest email preferences for one project.++ ``send_time`` is HH:MM in the project timezone.+ """++ enabled: bool = False+ send_time: str = "09:00"+ cadence: Literal["weekdays", "every_day"] = "weekdays"++@dataclass(frozen=True)class UserCustomerAnalyticsConfig:pinned_properties: list[PinnedAccountProperty] = field(default_factory=list)+ task_digest: TaskDigestPreferences = field(default_factory=TaskDigestPreferences)RelationshipSourceValue = Literal["human", "workflow", "ai", "salesforce_claim", "migration"]diff --git a/products/customer_analytics/backend/facade/enums.py b/products/customer_analytics/backend/facade/enums.pyindex c392566dfa5d..3f5be33d7111 100644--- a/products/customer_analytics/backend/facade/enums.py+++ b/products/customer_analytics/backend/facade/enums.py@@ -8,6 +8,13 @@ class AccountPropertyPinKind(str, Enum):RELATIONSHIP = "relationship"+class TaskDigestCadence(models.TextChoices):+ """How often a user's customer task digest email is sent."""++ WEEKDAYS = "weekdays", "Weekdays"+ EVERY_DAY = "every_day", "Every day"++class AccountRelationshipSource(models.TextChoices):"""Which kind of writer created or ended a relationship row. Rows written before provenancewas recorded carry NULL."""@@ -43,4 +50,5 @@ __all__ = ["AccountRelationshipSource","OwnershipRoleDiagnostic","OwnershipRoleState",+ "TaskDigestCadence",]diff --git a/products/customer_analytics/backend/logic/user_customer_analytics_config.py b/products/customer_analytics/backend/logic/user_customer_analytics_config.pyindex 4def80475727..1580c3bf677c 100644--- a/products/customer_analytics/backend/logic/user_customer_analytics_config.py+++ b/products/customer_analytics/backend/logic/user_customer_analytics_config.py@@ -1,9 +1,14 @@from collections.abc import Sequence+from datetime import datetime, time+from typing import Anyfrom uuid import UUID+from django.db import transaction+from posthog.models.scoping.manager import resolve_effective_team_id-from products.customer_analytics.backend.facade.enums import AccountPropertyPinKind+from products.customer_analytics.backend.facade import contracts+from products.customer_analytics.backend.facade.enums import AccountPropertyPinKind, TaskDigestCadencefrom products.customer_analytics.backend.models import (AccountRelationshipDefinition,CustomPropertyDefinition,@@ -14,6 +19,9 @@ from products.customer_analytics.backend.models import (PINNED_PROPERTIES_KEY = "pinned_properties"MAX_PINNED_PROPERTIES = 50+TASK_DIGEST_KEY = "task_digest"+DEFAULT_TASK_DIGEST = contracts.TaskDigestPreferences()+class InvalidPinnedAccountProperties(ValueError):def __init__(self, errors: list[str]) -> None:@@ -21,6 +29,7 @@ class InvalidPinnedAccountProperties(ValueError):self.errors = errorsdef get_or_create_config(*, team_id: int, user_id: int) -> UserCustomerAnalyticsConfig:# Resolve an environment (child team) id to its root team once. `for_team` canonicalizes its# filter but not the create kwargs, so a raw id makes the lookup never match, and the unique@@ -31,6 +40,11 @@ def get_or_create_config(*, team_id: int, user_id: int) -> UserCustomerAnalyticsuser_id=user_id,defaults={"properties": {PINNED_PROPERTIES_KEY: []}},)+ config = (+ UserCustomerAnalyticsConfig.objects.for_team(canonical_team_id, canonical=True)+ .select_for_update()+ .get(pk=config.pk)+ )if PINNED_PROPERTIES_KEY in config.properties:return config@@ -43,6 +57,7 @@ def get_or_create_config(*, team_id: int, user_id: int) -> UserCustomerAnalyticsreturn configdef update_pinned_properties(*, team_id: int, user_id: int, references: Sequence[tuple[AccountPropertyPinKind, UUID]]) -> UserCustomerAnalyticsConfig:@@ -59,6 +74,58 @@ def update_pinned_properties(return config+def read_task_digest(config: UserCustomerAnalyticsConfig) -> contracts.TaskDigestPreferences:+ """Read the digest preferences, filling in a disabled default for anything the row does not+ hold. A row written before this key existed, or holding only some of the three values, still+ reads as a complete set."""+ stored = config.properties.get(TASK_DIGEST_KEY)+ if not isinstance(stored, dict):+ stored = {}+ cadence = stored.get("cadence")+ return contracts.TaskDigestPreferences(+ enabled=stored.get("enabled") is True,+ send_time=_read_send_time(stored),+ cadence=cadence if cadence in TaskDigestCadence.values else DEFAULT_TASK_DIGEST.cadence,+ )+++def update_task_digest(+ *,+ team_id: int,+ user_id: int,+ enabled: bool | None = None,+ send_time: time | None = None,+ cadence: TaskDigestCadence | None = None,+) -> UserCustomerAnalyticsConfig:+ """Replace the values the caller passed and keep the rest of the digest preferences."""+ config = get_or_create_config(team_id=team_id, user_id=user_id)+ current = read_task_digest(config)+ config.properties = {+ **config.properties,+ TASK_DIGEST_KEY: {+ "enabled": current.enabled if enabled is None else enabled,+ "send_time": current.send_time+ if send_time is None+ else send_time.strftime(contracts.TASK_DIGEST_SEND_TIME_FORMAT),+ "cadence": current.cadence if cadence is None else cadence.value,+ },+ }+ config.save(update_fields=["properties", "updated_at"])+ return config+++def _read_send_time(stored: dict[str, Any]) -> str:+ value = stored.get("send_time")+ if isinstance(value, str):+ try:+ parsed = datetime.strptime(value, contracts.TASK_DIGEST_SEND_TIME_FORMAT)+ except ValueError:+ return DEFAULT_TASK_DIGEST.send_time+ return parsed.strftime(contracts.TASK_DIGEST_SEND_TIME_FORMAT)+ return DEFAULT_TASK_DIGEST.send_time++def _validate_pinned_properties(*, team_id: int, references: Sequence[tuple[AccountPropertyPinKind, UUID]]) -> None:if len(references) > MAX_PINNED_PROPERTIES:raise InvalidPinnedAccountProperties([f"Pin at most {MAX_PINNED_PROPERTIES} account properties."])diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex de5d3edc0400..65bcfb710a67 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -47,6 +47,7 @@ from products.customer_analytics.backend.facade.constants import (SLACK_SUMMARY_CADENCE_CHOICES,)from products.customer_analytics.backend.facade.contracts import (+ TASK_DIGEST_SEND_TIME_FORMAT,AccountAssignment,AccountChannelSummaryView,AccountNotebookView,@@ -79,7 +80,11 @@ from products.customer_analytics.backend.facade.contracts import (MeetingParticipantView,MeetingView,)-from products.customer_analytics.backend.facade.enums import AccountPropertyPinKind, AccountRelationshipSource+from products.customer_analytics.backend.facade.enums import (+ AccountPropertyPinKind,+ AccountRelationshipSource,+ TaskDigestCadence,+)class AccountTrackRuleFieldSerializer(serializers.Serializer):@@ -2075,12 +2080,44 @@ class PinnedAccountPropertySerializer(serializers.Serializer):)+class TaskDigestPreferencesSerializer(serializers.Serializer):+ enabled = serializers.BooleanField(help_text="Whether the task digest email is sent to this user.")+ send_time = serializers.TimeField(+ format=TASK_DIGEST_SEND_TIME_FORMAT,+ input_formats=[TASK_DIGEST_SEND_TIME_FORMAT],+ help_text="Time of day to send the digest, as HH:MM in the project timezone.",+ )+ cadence = serializers.ChoiceField(+ choices=TaskDigestCadence.choices,+ help_text="How often the digest is sent.",+ )+++class TaskDigestPreferencesUpdateSerializer(serializers.Serializer):+ enabled = serializers.BooleanField(required=False, help_text="Whether the task digest email is sent to this user.")+ send_time = serializers.TimeField(+ required=False,+ format=TASK_DIGEST_SEND_TIME_FORMAT,+ input_formats=[TASK_DIGEST_SEND_TIME_FORMAT],+ help_text="Time of day to send the digest, as HH:MM in the project timezone.",+ )+ cadence = serializers.ChoiceField(+ required=False,+ choices=TaskDigestCadence.choices,+ help_text="How often the digest is sent.",+ )++class UserCustomerAnalyticsConfigSerializer(serializers.Serializer):pinned_properties = PinnedAccountPropertySerializer(many=True,read_only=True,help_text="Account properties pinned in sidebar display order.",)+ task_digest = TaskDigestPreferencesSerializer(+ read_only=True,+ help_text="Task digest email preferences. Disabled until the user turns the digest on.",+ )class UserCustomerAnalyticsConfigUpdateSerializer(serializers.Serializer):@@ -2090,6 +2127,10 @@ class UserCustomerAnalyticsConfigUpdateSerializer(serializers.Serializer):required=False,help_text="Complete ordered list of account properties to pin. Omit to keep the current pins; pass an empty list to clear them.",)+ task_digest = TaskDigestPreferencesUpdateSerializer(+ required=False,+ help_text="Task digest email preferences to change. Omit the object to keep them all; omit a field inside it to keep that one.",+ )class AccountRelationshipDefinitionSerializer(DataclassSerializer):diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex f2450426986c..aac49d557516 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -912,12 +912,12 @@ class UserCustomerAnalyticsConfigViewSet(TeamAndOrgViewSetMixin, viewsets.Generiresponses={200: OpenApiResponse(response=UserCustomerAnalyticsConfigSerializer,- description="The requesting user's account sidebar configuration.",+ description="The requesting user's account sidebar and notification configuration.",)},summary="Get account sidebar configuration",description=(- "Get the requesting user's account sidebar configuration for this project. "+ "Get the requesting user's account sidebar and task digest configuration for this project. ""The first read creates an empty configuration row."),)@@ -939,26 +939,42 @@ class UserCustomerAnalyticsConfigViewSet(TeamAndOrgViewSetMixin, viewsets.Generi},summary="Update account sidebar configuration",description=(- "Replace the requesting user's ordered account sidebar properties when pinned_properties is provided. "- "Omitting pinned_properties leaves the configuration unchanged. "+ "Replace the requesting user's ordered account sidebar properties when pinned_properties is provided, "+ "and change the task digest email preferences when task_digest is provided. "+ "Anything omitted keeps its current value. ""At most 50 account custom properties and relationships can be pinned."),)def partial_update(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:- if "pinned_properties" not in request.validated_data:- return self.retrieve(request, *args, **kwargs)- pinned_properties = [- contracts.PinnedAccountProperty(kind=reference["kind"], id=reference["id"])- for reference in request.validated_data["pinned_properties"]- ]- try:- config = api.update_user_customer_analytics_config(+ user_id = cast(User, request.user).id+ config: contracts.UserCustomerAnalyticsConfig | None = None++ if "pinned_properties" in request.validated_data:+ pinned_properties = [+ contracts.PinnedAccountProperty(kind=reference["kind"], id=reference["id"])+ for reference in request.validated_data["pinned_properties"]+ ]+ try:+ config = api.update_user_customer_analytics_config(+ team_id=self.team_id,+ user_id=user_id,+ pinned_properties=pinned_properties,+ )+ except api.InvalidPinnedAccountProperties as error:+ raise ValidationError({"pinned_properties": error.errors})++ if "task_digest" in request.validated_data:+ task_digest = request.validated_data["task_digest"]+ config = api.update_user_task_digest_preferences(team_id=self.team_id,- user_id=cast(User, request.user).id,- pinned_properties=pinned_properties,+ user_id=user_id,+ enabled=task_digest.get("enabled"),+ send_time=task_digest.get("send_time"),+ cadence=task_digest.get("cadence"),)- except api.InvalidPinnedAccountProperties as error:- raise ValidationError({"pinned_properties": error.errors})++ if config is None:+ return self.retrieve(request, *args, **kwargs)return Response(UserCustomerAnalyticsConfigSerializer(instance=config).data)diff --git a/products/customer_analytics/backend/test/test_user_customer_analytics_config_api.py b/products/customer_analytics/backend/test/test_user_customer_analytics_config_api.pyindex 6bb5292f151b..4d4c2b18ede2 100644--- a/products/customer_analytics/backend/test/test_user_customer_analytics_config_api.py+++ b/products/customer_analytics/backend/test/test_user_customer_analytics_config_api.py@@ -1,4 +1,5 @@from datetime import timedelta+from typing import Anyfrom uuid import uuid4from posthog.test.base import APIBaseTest@@ -24,6 +25,12 @@ from products.customer_analytics.backend.models import (UserCustomerAnalyticsConfig,)+DISABLED_TASK_DIGEST = {"enabled": False, "send_time": "09:00", "cadence": "weekdays"}+++def config_body(pinned_properties: list[dict[str, str]], task_digest: dict[str, Any] | None = None) -> dict[str, Any]:+ return {"pinned_properties": pinned_properties, "task_digest": task_digest or DISABLED_TASK_DIGEST}+class TestUserCustomerAnalyticsConfigAPI(APIBaseTest):def setUp(self) -> None:@@ -51,7 +58,7 @@ class TestUserCustomerAnalyticsConfigAPI(APIBaseTest):response = self.client.get(self.endpoint)self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())- self.assertEqual(response.json(), {"pinned_properties": []})+ self.assertEqual(response.json(), config_body([]))config = UserCustomerAnalyticsConfig.objects.for_team(self.team.id).get(user_id=self.user.id)self.assertEqual(config.properties, {"pinned_properties": []})@@ -64,7 +71,7 @@ class TestUserCustomerAnalyticsConfigAPI(APIBaseTest):repeated = self.client.get(self.endpoint)self.assertEqual(repeated.status_code, status.HTTP_200_OK, repeated.json())- self.assertEqual(repeated.json(), {"pinned_properties": []})+ self.assertEqual(repeated.json(), config_body([]))config.refresh_from_db()self.assertEqual(config.properties, {"pinned_properties": [], "future_setting": "kept"})self.assertEqual(config.updated_at, updated_at)@@ -86,7 +93,7 @@ class TestUserCustomerAnalyticsConfigAPI(APIBaseTest):{"kind": "custom_property", "id": str(first.id)},]self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())- self.assertEqual(response.json(), {"pinned_properties": expected})+ self.assertEqual(response.json(), config_body(expected))config.refresh_from_db()self.assertEqual(config.properties, {"future_setting": "kept", "pinned_properties": expected})@@ -103,8 +110,8 @@ class TestUserCustomerAnalyticsConfigAPI(APIBaseTest):response = self.client.patch(self.endpoint, {"pinned_properties": pinned_properties}, format="json")self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())- self.assertEqual(response.json(), {"pinned_properties": pinned_properties})- self.assertEqual(self.client.get(self.endpoint).json(), {"pinned_properties": pinned_properties})+ self.assertEqual(response.json(), config_body(pinned_properties))+ self.assertEqual(self.client.get(self.endpoint).json(), config_body(pinned_properties))config = UserCustomerAnalyticsConfig.objects.for_team(self.team.id).get(user_id=self.user.id)self.assertEqual(config.properties["pinned_properties"], pinned_properties)self.assertEqual(config.pinned_custom_property_definition_ids, [first_custom.id, second_custom.id])@@ -114,13 +121,13 @@ class TestUserCustomerAnalyticsConfigAPI(APIBaseTest):with self.subTest(payload=payload):unchanged = self.client.patch(self.endpoint, payload, format="json")self.assertEqual(unchanged.status_code, status.HTTP_200_OK, unchanged.json())- self.assertEqual(unchanged.json(), {"pinned_properties": pinned_properties})- self.assertEqual(self.client.get(self.endpoint).json(), {"pinned_properties": pinned_properties})+ self.assertEqual(unchanged.json(), config_body(pinned_properties))+ self.assertEqual(self.client.get(self.endpoint).json(), config_body(pinned_properties))cleared = self.client.patch(self.endpoint, {"pinned_properties": []}, format="json")self.assertEqual(cleared.status_code, status.HTTP_200_OK, cleared.json())- self.assertEqual(cleared.json(), {"pinned_properties": []})+ self.assertEqual(cleared.json(), config_body([]))config.refresh_from_db()self.assertEqual(config.properties["pinned_properties"], [])self.assertEqual(config.pinned_custom_property_definition_ids, [])@@ -128,7 +135,11 @@ class TestUserCustomerAnalyticsConfigAPI(APIBaseTest):def test_config_is_isolated_by_requesting_user_and_project(self) -> None:definition = self._custom_property()pinned = [{"kind": "custom_property", "id": str(definition.id)}]- response = self.client.patch(self.endpoint, {"pinned_properties": pinned}, format="json")+ response = self.client.patch(+ self.endpoint,+ {"pinned_properties": pinned, "task_digest": {"enabled": True, "send_time": "07:30"}},+ format="json",+ )self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())other_user = User.objects.create_and_join(@@ -137,12 +148,12 @@ class TestUserCustomerAnalyticsConfigAPI(APIBaseTest):"testtest",)self.client.force_login(other_user)- self.assertEqual(self.client.get(self.endpoint).json(), {"pinned_properties": []})+ self.assertEqual(self.client.get(self.endpoint).json(), config_body([]))other_team = Team.objects.create(organization=self.organization, name="Other project")self.client.force_login(self.user)other_team_endpoint = f"/api/projects/{other_team.id}/user_customer_analytics_config/@me/"- self.assertEqual(self.client.get(other_team_endpoint).json(), {"pinned_properties": []})+ self.assertEqual(self.client.get(other_team_endpoint).json(), config_body([]))self.assertEqual(UserCustomerAnalyticsConfig.objects.unscoped().filter(team_id=self.team.id, user_id=self.user.id).count(),@@ -157,6 +168,46 @@ class TestUserCustomerAnalyticsConfigAPI(APIBaseTest):1,)+ def test_patch_task_digest_keeps_the_rest_of_the_configuration(self) -> None:+ pinned = [{"kind": "custom_property", "id": str(self._custom_property().id)}]+ self.client.patch(self.endpoint, {"pinned_properties": pinned}, format="json")+ config = UserCustomerAnalyticsConfig.objects.for_team(self.team.id).get(user_id=self.user.id)+ config.properties = {**config.properties, "future_setting": "kept"}+ config.save(update_fields=["properties"])++ enabled = self.client.patch(+ self.endpoint,+ {"task_digest": {"enabled": True, "send_time": "07:30", "cadence": "every_day"}},+ format="json",+ )++ digest = {"enabled": True, "send_time": "07:30", "cadence": "every_day"}+ self.assertEqual(enabled.status_code, status.HTTP_200_OK, enabled.json())+ self.assertEqual(enabled.json(), config_body(pinned, digest))+ self.assertEqual(self.client.get(self.endpoint).json(), config_body(pinned, digest))+ config.refresh_from_db()+ self.assertEqual(config.properties["future_setting"], "kept")+ self.assertEqual(config.properties["pinned_properties"], pinned)++ turned_off = self.client.patch(self.endpoint, {"task_digest": {"enabled": False}}, format="json")++ self.assertEqual(turned_off.status_code, status.HTTP_200_OK, turned_off.json())+ self.assertEqual(turned_off.json(), config_body(pinned, {**digest, "enabled": False}))++ @parameterized.expand(+ [+ ("cadence", {"cadence": "hourly"}),+ ("send_time", {"send_time": "25:00"}),+ ("send_time", {"send_time": "07:30:15"}),+ ]+ )+ def test_patch_rejects_invalid_task_digest(self, field: str, task_digest: dict[str, Any]) -> None:+ response = self.client.patch(self.endpoint, {"task_digest": task_digest}, format="json")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())+ self.assertEqual(response.json()["attr"], f"task_digest__{field}")+ self.assertEqual(self.client.get(self.endpoint).json(), config_body([]))+def test_environment_url_resolves_to_the_canonical_team(self) -> None:# `for_team` canonicalizes its filter but not the create kwargs, so an environment (child# team) id in the URL must resolve to the parent before the row is looked up or created.@@ -172,8 +223,8 @@ class TestUserCustomerAnalyticsConfigAPI(APIBaseTest):self.assertEqual(first.status_code, status.HTTP_200_OK, first.json())self.assertEqual(saved.status_code, status.HTTP_200_OK, saved.json())self.assertEqual(reread.status_code, status.HTTP_200_OK, reread.json())- self.assertEqual(reread.json(), {"pinned_properties": pinned})- self.assertEqual(self.client.get(self.endpoint).json(), {"pinned_properties": pinned})+ self.assertEqual(reread.json(), config_body(pinned))+ self.assertEqual(self.client.get(self.endpoint).json(), config_body(pinned))config = UserCustomerAnalyticsConfig.objects.for_team(self.team.id).get(user_id=self.user.id)self.assertEqual(config.team_id, self.team.id)self.assertEqual(UserCustomerAnalyticsConfig.objects.unscoped().filter(user_id=self.user.id).count(), 1)@@ -320,4 +371,4 @@ class TestUserCustomerAnalyticsConfigAPI(APIBaseTest):pinned = [{"kind": "custom_property", "id": str(self._custom_property().id)}]response = self.client.patch(self.endpoint, {"pinned_properties": pinned}, format="json")self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())- self.assertEqual(self.client.get(self.endpoint).json(), {"pinned_properties": pinned})+ self.assertEqual(self.client.get(self.endpoint).json(), config_body(pinned))diff --git a/products/customer_analytics/backend/test/test_user_customer_analytics_config_concurrency.py b/products/customer_analytics/backend/test/test_user_customer_analytics_config_concurrency.pynew file mode 100644index 000000000000..194dd20cf383--- /dev/null+++ b/products/customer_analytics/backend/test/test_user_customer_analytics_config_concurrency.py@@ -0,0 +1,54 @@+from concurrent.futures import ThreadPoolExecutor+from threading import Barrier+from typing import Any++from posthog.test.base import NonAtomicBaseTest++from django.db import connection++from products.customer_analytics.backend.logic.user_customer_analytics_config import (+ update_pinned_properties,+ update_task_digest,+)+from products.customer_analytics.backend.models import UserCustomerAnalyticsConfig+++class TestUserCustomerAnalyticsConfigConcurrency(NonAtomicBaseTest):+ def test_concurrent_preferences_and_pins_preserve_both_changes(self) -> None:+ config = UserCustomerAnalyticsConfig.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ user_id=self.user.id,+ properties={"pinned_properties": [{"kind": "custom_property", "id": "old-pin"}], "unrelated": "kept"},+ )+ read_barrier = Barrier(2, timeout=10)+ team_id, user_id = self.team.id, self.user.id++ def update_preferences(digest: bool) -> None:+ first_read = True++ def synchronize_read(execute: Any, sql: str, params: Any, many: bool, context: Any) -> Any:+ nonlocal first_read+ result = execute(sql, params, many, context)+ if first_read and sql.startswith("SELECT") and UserCustomerAnalyticsConfig._meta.db_table in sql:+ first_read = False+ read_barrier.wait()+ return result++ try:+ with connection.execute_wrapper(synchronize_read):+ if digest:+ update_task_digest(team_id=team_id, user_id=user_id, enabled=True)+ else:+ update_pinned_properties(team_id=team_id, user_id=user_id, references=[])+ finally:+ connection.close()++ with ThreadPoolExecutor(max_workers=2) as executor:+ futures = [executor.submit(update_preferences, digest) for digest in [False, True]]+ for future in futures:+ future.result(timeout=20)++ config.refresh_from_db()+ self.assertEqual(config.properties["pinned_properties"], [])+ self.assertTrue(config.properties["task_digest"]["enabled"])+ self.assertEqual(config.properties["unrelated"], "kept")diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsxindex 740935594888..951a64054297 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx@@ -579,6 +579,7 @@ const PINNED_PROPERTY_VALUES: CustomPropertyValueApi[] = PINNED_PROPERTY_FIXTUREcreated_by_id: 1,}))const PINNED_PROPERTIES_CONFIG: UserCustomerAnalyticsConfigApi = {+ task_digest: { enabled: false, send_time: '09:00', cadence: 'weekdays' },pinned_properties: [{ kind: 'custom_property', id: 'seats' },{ kind: 'relationship', id: RELATIONSHIP_DEFINITIONS.results[0].id },diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.tsindex d0cebb071754..f8c748583af4 100644--- a/products/customer_analytics/frontend/components/Accounts/constants.ts+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts@@ -73,6 +73,7 @@ export const AccountsEvents = {EventStreamMembershipToggled: 'customer analytics account event stream toggled',EventStreamConfigSaved: 'customer analytics event stream config saved',EventStreamTestMessageSent: 'customer analytics event stream test message sent',+ TaskDigestPreferencesSaved: 'customer analytics task digest preferences saved',NotesTabViewed: 'customer analytics notes tab viewed',NotesTabSearched: 'customer analytics notes tab searched',NotesTabFiltered: 'customer analytics notes tab filtered',diff --git a/products/customer_analytics/frontend/components/TaskDigest/CustomerAnalyticsNotifications.tsx b/products/customer_analytics/frontend/components/TaskDigest/CustomerAnalyticsNotifications.tsxnew file mode 100644index 000000000000..a1f991ffd76e--- /dev/null+++ b/products/customer_analytics/frontend/components/TaskDigest/CustomerAnalyticsNotifications.tsx@@ -0,0 +1,37 @@+import { useValues } from 'kea'++import { LemonBanner } from '@posthog/lemon-ui'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { CustomerAnalyticsEventStream } from '../EventStream/CustomerAnalyticsEventStream'+import { CustomerAnalyticsTaskDigest } from './CustomerAnalyticsTaskDigest'++export function CustomerAnalyticsNotifications(): JSX.Element {+ const { featureFlags } = useValues(featureFlagLogic)+ const showTaskDigest = featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS]+ const showEventStream = featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]++ return (+ <div className="flex flex-col gap-8">+ {showTaskDigest && (+ <section>+ <h3>Task digest emails</h3>+ <CustomerAnalyticsTaskDigest />+ </section>+ )}+ {showEventStream && (+ <section>+ <h3>Event stream</h3>+ <CustomerAnalyticsEventStream />+ </section>+ )}+ {!showTaskDigest && !showEventStream && (+ <LemonBanner type="info">+ Notifications are available with customer tasks or the customer event stream.+ </LemonBanner>+ )}+ </div>+ )+}diff --git a/products/customer_analytics/frontend/components/TaskDigest/CustomerAnalyticsTaskDigest.stories.tsx b/products/customer_analytics/frontend/components/TaskDigest/CustomerAnalyticsTaskDigest.stories.tsxnew file mode 100644index 000000000000..0a5f532c2e3d--- /dev/null+++ b/products/customer_analytics/frontend/components/TaskDigest/CustomerAnalyticsTaskDigest.stories.tsx@@ -0,0 +1,115 @@+import type { Meta, StoryObj } from '@storybook/react'++import { FEATURE_FLAGS } from 'lib/constants'++import { useStorybookMocks } from '~/mocks/browser'++import type { UserCustomerAnalyticsConfigApi } from '../../generated/api.schemas'+import { CustomerAnalyticsNotifications } from './CustomerAnalyticsNotifications'+import { CustomerAnalyticsTaskDigest } from './CustomerAnalyticsTaskDigest'++const CONFIG_URL = '/api/projects/:team_id/user_customer_analytics_config/@me/'++const disabledConfig: UserCustomerAnalyticsConfigApi = {+ pinned_properties: [],+ task_digest: { enabled: false, send_time: '09:00', cadence: 'weekdays' },+}++const enabledConfig: UserCustomerAnalyticsConfigApi = {+ pinned_properties: [],+ task_digest: { enabled: true, send_time: '07:00', cadence: 'every_day' },+}++interface TaskDigestStoryProps {+ config?: UserCustomerAnalyticsConfigApi+ loading?: boolean+ failing?: boolean+ notifications?: boolean+ saving?: boolean+ saveFails?: boolean+ width?: 'normal' | 'narrow'+}++function TaskDigestStory({+ config = disabledConfig,+ loading,+ failing,+ width,+ notifications,+ saving,+ saveFails,+}: TaskDigestStoryProps): JSX.Element {+ useStorybookMocks({+ get: {+ '/api/projects/:team_id/event_streams/': [],+ [CONFIG_URL]: () => {+ if (loading) {+ return new Promise<never>(() => {})+ }+ if (failing) {+ return [500, { detail: 'Could not load the preferences.' }]+ }+ return config+ },+ },+ patch: {+ [CONFIG_URL]: async ({ request }) => {+ if (saving) {+ return new Promise<never>(() => {})+ }+ if (saveFails) {+ return [500, { detail: 'Could not save the preferences.' }]+ }+ const body = (await request.json()) as Partial<UserCustomerAnalyticsConfigApi>+ return { ...config, ...body }+ },+ },+ })++ return (+ <div className={width === 'narrow' ? 'w-[520px] p-4' : 'w-[900px] p-4'}>+ {notifications ? <CustomerAnalyticsNotifications /> : <CustomerAnalyticsTaskDigest />}+ </div>+ )+}++const meta: Meta<typeof TaskDigestStory> = {+ title: 'Customer analytics/Task digest',+ component: TaskDigestStory,+ parameters: {+ layout: 'padded',+ featureFlags: [FEATURE_FLAGS.CUSTOMER_ANALYTICS, FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS],+ },+}+export default meta++type Story = StoryObj<typeof TaskDigestStory>++export const Disabled: Story = {}++export const Enabled: Story = { args: { config: enabledConfig } }++export const Loading: Story = {+ args: { loading: true },+ parameters: { testOptions: { waitForLoadersToDisappear: false } },+}++export const LoadFailed: Story = { args: { failing: true } }++export const DisabledNarrow: Story = { args: { width: 'narrow' } }++export const EnabledNarrow: Story = { args: { config: enabledConfig, width: 'narrow' } }++export const Notifications: Story = {+ args: { notifications: true },+ parameters: {+ featureFlags: [+ FEATURE_FLAGS.CUSTOMER_ANALYTICS,+ FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS,+ FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP,+ ],+ },+}+export const NotificationsNarrow: Story = { ...Notifications, args: { notifications: true, width: 'narrow' } }+export const Saving: Story = { args: { saving: true } }+export const SaveFailed: Story = { args: { saveFails: true } }diff --git a/products/customer_analytics/frontend/components/TaskDigest/CustomerAnalyticsTaskDigest.tsx b/products/customer_analytics/frontend/components/TaskDigest/CustomerAnalyticsTaskDigest.tsxnew file mode 100644index 000000000000..c732c14053e5--- /dev/null+++ b/products/customer_analytics/frontend/components/TaskDigest/CustomerAnalyticsTaskDigest.tsx@@ -0,0 +1,118 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonButton, LemonLabel, LemonSelect, LemonSkeleton, LemonSwitch } from '@posthog/lemon-ui'++import { taskDigestLogic } from './taskDigestLogic'++const CADENCE_OPTIONS = [+ { value: 'weekdays' as const, label: 'Weekdays' },+ { value: 'every_day' as const, label: 'Every day' },+]++function formatTimeLabel(hour: number, minute: number): string {+ return `${hour % 12 || 12}:${String(minute).padStart(2, '0')} ${hour < 12 ? 'AM' : 'PM'}`+}++const TIME_OPTIONS = Array.from({ length: 48 }, (_, index) => {+ const hour = Math.floor(index / 2)+ const minute = (index % 2) * 30+ return {+ value: `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`,+ label: formatTimeLabel(hour, minute),+ }+})++export function CustomerAnalyticsTaskDigest(): JSX.Element {+ const { draft, hasChanges, configLoading, isInitialLoading, configLoadFailed, timezone, validSendTime } =+ useValues(taskDigestLogic)+ const { setDraft, resetDraft, saveTaskDigest, loadConfig } = useActions(taskDigestLogic)+ const [hour, minute] = draft.send_time.split(':').map(Number)+ const timeOptions =+ validSendTime && !TIME_OPTIONS.some(({ value }) => value === draft.send_time)+ ? [+ {+ value: draft.send_time,+ label: `${formatTimeLabel(hour, minute)} (current)`,+ hidden: true,+ },+ ...TIME_OPTIONS,+ ]+ : TIME_OPTIONS++ if (isInitialLoading) {+ return <LemonSkeleton className="h-20 w-full" />+ }++ if (configLoadFailed) {+ return (+ <LemonBanner type="error" action={{ children: 'Try again', onClick: loadConfig, loading: configLoading }}>+ Couldn't load your task digest preferences.+ </LemonBanner>+ )+ }++ return (+ <div className="flex flex-col gap-4">+ <p className="mb-0">+ Get an email summary of the customer tasks assigned to you. Each team member sets their own preferences.+ </p>++ <div className="flex flex-row flex-wrap gap-4">+ <div className="flex flex-col gap-2">+ <LemonLabel htmlFor="task-digest-send-time">Send at</LemonLabel>+ <div className="flex flex-row flex-wrap items-center gap-2">+ <LemonSelect+ id="task-digest-send-time"+ aria-label="Send time"+ disabled={configLoading}+ value={draft.send_time}+ options={timeOptions}+ onChange={(send_time) => setDraft({ send_time })}+ data-attr="task-digest-send-time"+ />+ <span className="text-secondary">{timezone}</span>+ </div>+ </div>++ <div className="flex flex-col gap-2">+ <LemonLabel htmlFor="task-digest-cadence">How often</LemonLabel>+ <LemonSelect+ id="task-digest-cadence"+ disabled={configLoading}+ value={draft.cadence}+ options={CADENCE_OPTIONS}+ onChange={(cadence) => setDraft({ cadence })}+ data-attr="task-digest-cadence"+ />+ </div>+ </div>++ <LemonSwitch+ checked={draft.enabled}+ onChange={(enabled) => setDraft({ enabled })}+ label="Enable email digest"+ bordered+ disabled={configLoading}+ />++ <div className="flex flex-row flex-wrap gap-2 pt-2">+ <LemonButton+ type="secondary"+ onClick={resetDraft}+ disabledReason={configLoading ? 'Saving preferences' : hasChanges ? undefined : 'No changes'}+ >+ Clear changes+ </LemonButton>+ <LemonButton+ data-attr="save-customer-analytics-task-digest"+ type="primary"+ onClick={saveTaskDigest}+ loading={configLoading}+ disabledReason={!validSendTime ? 'Choose a valid send time' : hasChanges ? undefined : 'No changes'}+ >+ Save+ </LemonButton>+ </div>+ </div>+ )+}diff --git a/products/customer_analytics/frontend/components/TaskDigest/taskDigestLogic.test.ts b/products/customer_analytics/frontend/components/TaskDigest/taskDigestLogic.test.tsnew file mode 100644index 000000000000..9dabfb385d95--- /dev/null+++ b/products/customer_analytics/frontend/components/TaskDigest/taskDigestLogic.test.ts@@ -0,0 +1,110 @@+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'++import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'+import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { AccountsEvents } from 'products/customer_analytics/frontend/components/Accounts/constants'+import type { UserCustomerAnalyticsConfigApi } from 'products/customer_analytics/frontend/generated/api.schemas'++import { taskDigestLogic } from './taskDigestLogic'++const CONFIG_URL = '/api/projects/:team_id/user_customer_analytics_config/@me/'++const PINNED_PROPERTIES = [{ kind: 'custom_property' as const, id: 'custom-1' }]++const buildConfig = (overrides: Partial<UserCustomerAnalyticsConfigApi> = {}): UserCustomerAnalyticsConfigApi =>+ ({+ pinned_properties: PINNED_PROPERTIES,+ task_digest: { enabled: false, send_time: '09:00', cadence: 'weekdays' },+ ...overrides,+ }) as UserCustomerAnalyticsConfigApi++describe('taskDigestLogic', () => {+ let logic: ReturnType<typeof taskDigestLogic.build>++ const mountLogic = async (): Promise<void> => {+ logic = taskDigestLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadConfigSuccess']).toFinishAllListeners()+ }++ beforeEach(() => {+ initKeaTests()+ })++ afterEach(() => {+ logic?.unmount()+ resumeKeaLoadersErrors()+ jest.restoreAllMocks()+ })++ it('saves only the digest preferences, so pinned properties survive', async () => {+ let submittedBody: unknown+ useMocks({+ get: { [CONFIG_URL]: buildConfig() },+ patch: {+ [CONFIG_URL]: async ({ request }) => {+ submittedBody = await request.json()+ return buildConfig({ task_digest: { enabled: true, send_time: '07:30', cadence: 'every_day' } })+ },+ },+ })+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ await mountLogic()++ expect(logic.values.draft).toEqual({ enabled: false, send_time: '09:00', cadence: 'weekdays' })+ expect(logic.values.hasChanges).toBe(false)+ logic.actions.setDraft({ send_time: '' })+ expect(logic.values.validSendTime).toBe(false)++ logic.actions.setDraft({ enabled: true, send_time: '07:30', cadence: 'every_day' })+ expect(logic.values.hasChanges).toBe(true)+ expect(logic.values.validSendTime).toBe(true)++ logic.actions.saveTaskDigest()+ await expectLogic(logic).toDispatchActions(['saveTaskDigestSuccess']).toFinishAllListeners()++ expect(submittedBody).toEqual({ task_digest: { enabled: true, send_time: '07:30', cadence: 'every_day' } })+ expect(logic.values.config?.pinned_properties).toEqual(PINNED_PROPERTIES)+ expect(logic.values.hasChanges).toBe(false)+ expect(captureSpy).toHaveBeenCalledWith(+ AccountsEvents.TaskDigestPreferencesSaved,+ expect.objectContaining({ enabled: true, send_time: '07:30', cadence: 'every_day' })+ )+ })++ it('keeps the edits and notifies once when the save fails', async () => {+ silenceKeaLoadersErrors()+ const toastSpy = jest.spyOn(lemonToast, 'error')+ useMocks({+ get: { [CONFIG_URL]: buildConfig() },+ patch: { [CONFIG_URL]: () => [500, { detail: 'Could not save the preferences.' }] },+ })+ await mountLogic()++ logic.actions.setDraft({ enabled: true })+ logic.actions.saveTaskDigest()+ await expectLogic(logic).toDispatchActions(['saveTaskDigestFailure']).toFinishAllListeners()++ expect(logic.values.draft.enabled).toBe(true)+ expect(logic.values.hasChanges).toBe(true)+ expect(toastSpy).toHaveBeenCalledTimes(1)+ expect(toastSpy).toHaveBeenCalledWith(expect.stringContaining('Could not save the preferences.'))+ })++ it('reports a failed load instead of showing the defaults as saved preferences', async () => {+ silenceKeaLoadersErrors()+ useMocks({ get: { [CONFIG_URL]: () => [500, { detail: 'Could not load the preferences.' }] } })+ logic = taskDigestLogic()+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadConfigFailure']).toFinishAllListeners()++ expect(logic.values.configLoadFailed).toBe(true)+ expect(logic.values.isInitialLoading).toBe(false)+ })+})diff --git a/products/customer_analytics/frontend/components/TaskDigest/taskDigestLogic.ts b/products/customer_analytics/frontend/components/TaskDigest/taskDigestLogic.tsnew file mode 100644index 000000000000..a5662d60591b--- /dev/null+++ b/products/customer_analytics/frontend/components/TaskDigest/taskDigestLogic.ts@@ -0,0 +1,185 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { objectsEqual } from 'lib/utils/objects'+import { teamLogic } from 'scenes/teamLogic'++import {+ userCustomerAnalyticsConfigPartialUpdate,+ userCustomerAnalyticsConfigRetrieve,+} from 'products/customer_analytics/frontend/generated/api'+import type {+ TaskDigestCadenceEnumApi,+ TaskDigestPreferencesApi,+ UserCustomerAnalyticsConfigApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'++import { AccountsEvents } from '../Accounts/constants'++const CURRENT_USER_CONFIG_ID = '@me'++/** Locally staged edits to the digest preferences, applied on Save. */+export interface TaskDigestDraft {+ enabled: boolean+ send_time: string+ cadence: TaskDigestCadenceEnumApi+}++function draftFromConfig(config: UserCustomerAnalyticsConfigApi | null): TaskDigestDraft {+ const digest: TaskDigestPreferencesApi | undefined = config?.task_digest+ return {+ enabled: digest?.enabled ?? false,+ send_time: digest?.send_time ?? '09:00',+ cadence: digest?.cadence ?? 'weekdays',+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface taskDigestLogicValues {+ currentTeamId: number | null // teamLogic+ timezone: string // teamLogic+ config: UserCustomerAnalyticsConfigApi | null+ configLoadFailed: boolean+ configLoading: boolean+ draft: TaskDigestDraft+ hasChanges: boolean+ isInitialLoading: boolean+ validSendTime: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface taskDigestLogicActions {+ loadConfig: () => any+ loadConfigFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadConfigSuccess: (+ config: UserCustomerAnalyticsConfigApi,+ payload?: any+ ) => {+ config: UserCustomerAnalyticsConfigApi+ payload?: any+ }+ resetDraft: () => {+ value: true+ }+ saveTaskDigest: () => any+ saveTaskDigestFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ saveTaskDigestSuccess: (+ config: UserCustomerAnalyticsConfigApi,+ payload?: any+ ) => {+ config: UserCustomerAnalyticsConfigApi+ payload?: any+ }+ setDraft: (draft: Partial<TaskDigestDraft>) => {+ draft: Partial<TaskDigestDraft>+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface taskDigestLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ validSendTime: (draft: TaskDigestDraft) => boolean+ hasChanges: (draft: TaskDigestDraft, config: UserCustomerAnalyticsConfigApi | null) => boolean+ isInitialLoading: (configLoading: boolean, config: UserCustomerAnalyticsConfigApi | null) => boolean+ }+}++export type taskDigestLogicType = MakeLogicType<+ taskDigestLogicValues,+ taskDigestLogicActions,+ Record<string, any>,+ taskDigestLogicMeta+>++export const taskDigestLogic = kea<taskDigestLogicType>([+ path(['products', 'customerAnalytics', 'taskDigest', 'taskDigestLogic']),+ connect(() => ({+ values: [teamLogic, ['currentTeamId', 'timezone']],+ })),+ actions({+ setDraft: (draft: Partial<TaskDigestDraft>) => ({ draft }),+ resetDraft: true,+ }),+ loaders(({ values }) => ({+ config: [+ null as UserCustomerAnalyticsConfigApi | null,+ {+ loadConfig: async (): Promise<UserCustomerAnalyticsConfigApi> =>+ await userCustomerAnalyticsConfigRetrieve(String(values.currentTeamId), CURRENT_USER_CONFIG_ID),+ // Sends only task_digest, so the user's pinned sidebar properties stay untouched.+ saveTaskDigest: async (): Promise<UserCustomerAnalyticsConfigApi> =>+ await userCustomerAnalyticsConfigPartialUpdate(+ String(values.currentTeamId),+ CURRENT_USER_CONFIG_ID,+ { task_digest: values.draft }+ ),+ },+ ],+ })),+ reducers({+ configLoadFailed: [+ false,+ {+ loadConfig: () => false,+ loadConfigFailure: () => true,+ loadConfigSuccess: () => false,+ },+ ],+ draft: [+ draftFromConfig(null),+ {+ setDraft: (state, { draft }) => ({ ...state, ...draft }),+ loadConfigSuccess: (_, { config }) => draftFromConfig(config),+ saveTaskDigestSuccess: (_, { config }) => draftFromConfig(config),+ },+ ],+ }),+ selectors({+ validSendTime: [+ (s) => [s.draft],+ (draft: TaskDigestDraft): boolean => /^([01][0-9]|2[0-3]):[0-5][0-9]$/.test(draft.send_time),+ ],+ hasChanges: [+ (s) => [s.draft, s.config],+ (draft: TaskDigestDraft, config: UserCustomerAnalyticsConfigApi | null): boolean =>+ !objectsEqual(draft, draftFromConfig(config)),+ ],+ isInitialLoading: [+ (s) => [s.configLoading, s.config],+ (configLoading: boolean, config: UserCustomerAnalyticsConfigApi | null): boolean =>+ configLoading && config === null,+ ],+ }),+ // Failures get no listener: the global kea-loaders handler toasts and reports them, and the+ // load error banner runs off the configLoadFailed reducer.+ listeners(({ actions, values }) => ({+ resetDraft: () => {+ actions.setDraft(draftFromConfig(values.config))+ },+ saveTaskDigestSuccess: ({ config }) => {+ lemonToast.success('Task digest preferences saved')+ posthog.capture(AccountsEvents.TaskDigestPreferencesSaved, {+ enabled: config?.task_digest?.enabled ?? false,+ send_time: config?.task_digest?.send_time,+ cadence: config?.task_digest?.cadence,+ })+ },+ })),+ afterMount(({ actions }) => {+ actions.loadConfig()+ }),+])diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 5f450b2b7039..2a21ddea80ee 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -4331,14 +4331,53 @@ export interface PinnedAccountPropertyApi {id: string}+/**+ * * `weekdays` - Weekdays+ * * `every_day` - Every day+ */+export type TaskDigestCadenceEnumApi = (typeof TaskDigestCadenceEnumApi)[keyof typeof TaskDigestCadenceEnumApi]++export const TaskDigestCadenceEnumApi = {+ Weekdays: 'weekdays',+ EveryDay: 'every_day',+} as const++export interface TaskDigestPreferencesApi {+ /** Whether the task digest email is sent to this user. */+ enabled: boolean+ /** Time of day to send the digest, as HH:MM in the project timezone. */+ send_time: string+ /** How often the digest is sent.+ *+ * * `weekdays` - Weekdays+ * * `every_day` - Every day */+ cadence: TaskDigestCadenceEnumApi+}+export interface UserCustomerAnalyticsConfigApi {/** Account properties pinned in sidebar display order. */readonly pinned_properties: readonly PinnedAccountPropertyApi[]+ /** Task digest email preferences. Disabled until the user turns the digest on. */+ readonly task_digest: TaskDigestPreferencesApi+}++export interface TaskDigestPreferencesUpdateApi {+ /** Whether the task digest email is sent to this user. */+ enabled?: boolean+ /** Time of day to send the digest, as HH:MM in the project timezone. */+ send_time?: string+ /** How often the digest is sent.+ *+ * * `weekdays` - Weekdays+ * * `every_day` - Every day */+ cadence?: TaskDigestCadenceEnumApi}export interface PatchedUserCustomerAnalyticsConfigUpdateApi {/** Complete ordered list of account properties to pin. Omit to keep the current pins; pass an empty list to clear them. */pinned_properties?: PinnedAccountPropertyApi[]+ /** Task digest email preferences to change. Omit the object to keep them all; omit a field inside it to keep that one. */+ task_digest?: TaskDigestPreferencesUpdateApi}export type CustomerAnalyticsExternalAccountRetrieveParams = {diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.tsindex 6da9d0a29b2a..bd6f734ccefd 100644--- a/products/customer_analytics/frontend/generated/api.ts+++ b/products/customer_analytics/frontend/generated/api.ts@@ -2522,7 +2522,7 @@ export const getUserCustomerAnalyticsConfigRetrieveUrl = (projectId: string, id:}/**- * Get the requesting user's account sidebar configuration for this project. The first read creates an empty configuration row.+ * Get the requesting user's account sidebar and task digest configuration for this project. The first read creates an empty configuration row.* @summary Get account sidebar configuration*/export const userCustomerAnalyticsConfigRetrieve = async (@@ -2541,7 +2541,7 @@ export const getUserCustomerAnalyticsConfigPartialUpdateUrl = (projectId: string}/**- * Replace the requesting user's ordered account sidebar properties when pinned_properties is provided. Omitting pinned_properties leaves the configuration unchanged. At most 50 account custom properties and relationships can be pinned.+ * Replace the requesting user's ordered account sidebar properties when pinned_properties is provided, and change the task digest email preferences when task_digest is provided. Anything omitted keeps its current value. At most 50 account custom properties and relationships can be pinned.* @summary Update account sidebar configuration*/export const userCustomerAnalyticsConfigPartialUpdate = async (diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.tsindex 1584336a21c4..19f70aa06849 100644--- a/products/customer_analytics/frontend/generated/api.zod.ts+++ b/products/customer_analytics/frontend/generated/api.zod.ts@@ -1678,7 +1678,7 @@ export const GroupsTypesMetricsPartialUpdateBody = /* @__PURE__ */ zod.object({})/**- * Replace the requesting user's ordered account sidebar properties when pinned_properties is provided. Omitting pinned_properties leaves the configuration unchanged. At most 50 account custom properties and relationships can be pinned.+ * Replace the requesting user's ordered account sidebar properties when pinned_properties is provided, and change the task digest email preferences when task_digest is provided. Anything omitted keeps its current value. At most 50 account custom properties and relationships can be pinned.* @summary Update account sidebar configuration*/export const UserCustomerAnalyticsConfigPartialUpdateBody = /* @__PURE__ */ zod.object({@@ -1698,4 +1698,21 @@ export const UserCustomerAnalyticsConfigPartialUpdateBody = /* @__PURE__ */ zod..describe('Complete ordered list of account properties to pin. Omit to keep the current pins; pass an empty list to clear them.'),+ task_digest: zod+ .object({+ enabled: zod.boolean().optional().describe('Whether the task digest email is sent to this user.'),+ send_time: zod.iso+ .time({})+ .optional()+ .describe('Time of day to send the digest, as HH:MM in the project timezone.'),+ cadence: zod+ .enum(['weekdays', 'every_day'])+ .describe('\* `weekdays` - Weekdays\n\* `every_day` - Every day')+ .optional()+ .describe('How often the digest is sent.\n\n\* `weekdays` - Weekdays\n\* `every_day` - Every day'),+ })+ .optional()+ .describe(+ 'Task digest email preferences to change. Omit the object to keep them all; omit a field inside it to keep that one.'+ ),})diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.test.tsindex 15e6760aadf8..444bef3fd9be 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.test.ts+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.test.ts@@ -56,11 +56,13 @@ const buildRelationship = (...overrides,})-const defaultMocks = (- config: UserCustomerAnalyticsConfigApi = { pinned_properties: [] }-): Parameters<typeof useMocks>[0] => ({+const defaultMocks = (config: Partial<UserCustomerAnalyticsConfigApi> = {}): Parameters<typeof useMocks>[0] => ({get: {- [CONFIG_URL]: config,+ [CONFIG_URL]: {+ pinned_properties: [],+ task_digest: { enabled: false, send_time: '09:00', cadence: 'weekdays' },+ ...config,+ },[CUSTOM_PROPERTIES_URL]: { count: 1, results: [buildCustomProperty()] },[RELATIONSHIPS_URL]: { count: 1, results: [buildRelationship()] },},diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f3b8c6380e03..c0a84715e8be 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -74223,9 +74223,35 @@ export namespace Schemas {id: string;}+ /**+ * * `weekdays` - Weekdays+ * * `every_day` - Every day+ */+ export type TaskDigestCadenceEnum = typeof TaskDigestCadenceEnum[keyof typeof TaskDigestCadenceEnum];+++ export const TaskDigestCadenceEnum = {+ Weekdays: 'weekdays',+ EveryDay: 'every_day',+ } as const;++ export interface TaskDigestPreferencesUpdate {+ /** Whether the task digest email is sent to this user. */+ enabled?: boolean;+ /** Time of day to send the digest, as HH:MM in the project timezone. */+ send_time?: string;+ /** How often the digest is sent.+ *+ * * `weekdays` - Weekdays+ * * `every_day` - Every day */+ cadence?: TaskDigestCadenceEnum;+ }+export interface PatchedUserCustomerAnalyticsConfigUpdate {/** Complete ordered list of account properties to pin. Omit to keep the current pins; pass an empty list to clear them. */pinned_properties?: PinnedAccountProperty[];+ /** Task digest email preferences to change. Omit the object to keep them all; omit a field inside it to keep that one. */+ task_digest?: TaskDigestPreferencesUpdate;}/**@@ -91789,6 +91815,18 @@ export namespace Schemas {run_error?: string;}+ export interface TaskDigestPreferences {+ /** Whether the task digest email is sent to this user. */+ enabled: boolean;+ /** Time of day to send the digest, as HH:MM in the project timezone. */+ send_time: string;+ /** How often the digest is sent.+ *+ * * `weekdays` - Weekdays+ * * `every_day` - Every day */+ cadence: TaskDigestCadenceEnum;+ }+/*** Request body for handing a task off to a colleague: they become its owner.*/@@ -94271,6 +94309,8 @@ export namespace Schemas {export interface UserCustomerAnalyticsConfig {/** Account properties pinned in sidebar display order. */readonly pinned_properties: readonly PinnedAccountProperty[];+ /** Task digest email preferences. Disabled until the user turns the digest on. */+ readonly task_digest: TaskDigestPreferences;}export interface UserFacetSettings {