: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): account meetings tab, api, and sync controls (#78503)
Arthur Moreira de Deus52c3b6f5ca3f
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 4397a469df97..1b0bbc858e26 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -15,6 +15,7 @@ Do NOT:- Import DRF, serializers, or HTTP concerns"""+import asynciofrom collections.abc import Iterablefrom datetime import datetime, timedeltafrom enum import Enum@@ -22,6 +23,7 @@ from typing import TYPE_CHECKING, Any, Optional, castfrom uuid import UUIDfrom django.apps import apps+from django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom django.db import IntegrityError, transactionfrom django.db.models import CharField, Exists, OuterRef, Prefetch, Q@@ -30,6 +32,8 @@ from django.utils import timezoneimport structlogfrom celery import current_appfrom pydantic import ValidationError as PydanticValidationError+from temporalio.common import RetryPolicy, WorkflowIDReusePolicy+from temporalio.exceptions import WorkflowAlreadyStartedErrorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Integration, OrganizationMembership, Tag@@ -2556,24 +2560,101 @@ def get_account_support_tickets(return list_account_tickets(team_id, account.external_id, limit=limit)-def get_account_meetings(+def list_calendar_sync_statuses(team_id: int) -> list[contracts.CalendarSyncStatus]:+ """Sync state of every connected calendar for the team: last completed sync and+ whether a run is currently in flight (started but not finished, within the sync+ activity's timeout — a run past it is considered dead, not running)."""+ from products.customer_analytics.backend.logic.calendar_sync import ( # noqa: PLC0415 — keeps requests/HogQL layers off the import path+ LAST_SYNCED_AT_CONFIG_KEY,+ SYNC_STALE_AFTER,+ SYNC_STARTED_AT_CONFIG_KEY,+ )++ statuses = []+ for integration in Integration.objects.filter(team_id=team_id, kind="google-calendar").order_by("id"):+ config = integration.config or {}+ last_synced_at = _parse_datetime(config.get(LAST_SYNCED_AT_CONFIG_KEY))+ started_at = _parse_datetime(config.get(SYNC_STARTED_AT_CONFIG_KEY))+ is_syncing = bool(+ started_at+ and (last_synced_at is None or started_at > last_synced_at)+ and started_at > timezone.now() - SYNC_STALE_AFTER+ )+ statuses.append(+ contracts.CalendarSyncStatus(+ integration_id=integration.id,+ last_synced_at=last_synced_at,+ is_syncing=is_syncing,+ )+ )+ return statuses+++def _parse_datetime(value: str | None) -> datetime | None:+ if not value:+ return None+ try:+ return datetime.fromisoformat(value)+ except ValueError:+ return None+++def trigger_calendar_sync(team_id: int, integration_id: int) -> str | None:+ """Start the calendar-sync workflow for one connected calendar, outside the hourly+ schedule. Returns 'started', 'already_running' (a sync for this calendar is in+ flight; the workflow id is deterministic per integration), or None when the+ integration doesn't exist for this team (→ 404)."""+ if not Integration.objects.filter(id=integration_id, team_id=team_id, kind="google-calendar").exists():+ return None++ from posthog.temporal.common.client import sync_connect # noqa: PLC0415 — keeps temporal off the import path++ from products.customer_analytics.backend.temporal.calendar_sync import ( # noqa: PLC0415 — same+ CalendarSyncInput,+ CalendarSyncWorkflow,+ )++ client = sync_connect()+ try:+ asyncio.run(+ client.start_workflow(+ CalendarSyncWorkflow.run,+ CalendarSyncInput(integration_id=integration_id, team_id=team_id),+ id=f"google-calendar-sync-{integration_id}",+ task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ retry_policy=RetryPolicy(maximum_attempts=1),+ )+ )+ except WorkflowAlreadyStartedError:+ return "already_running"+ return "started"+++def list_account_meetings(team_id: int,account_id: str,user_access_control: "UserAccessControl",*,+ offset: int = 0,limit: int = 100,-) -> list[contracts.MeetingView] | None:- """Synced calendar meetings for an accessible account, newest first. None when the- account isn't accessible (→ 404)."""+ search: str | None = None,+) -> tuple[list[contracts.MeetingView], int] | None:+ """Synced calendar meetings for an accessible account, newest first, optionally+ filtered by ``search`` (title or attendee email/name). None when the account isn't+ accessible (→ 404)."""if get_accessible_account_id(team_id, account_id, user_access_control) is None:return None- meetings = (- Meeting.objects.for_team(team_id)- .filter(account_id=account_id)- .order_by("-start_time")- .prefetch_related("participants")[:limit]- )- return [+ queryset = Meeting.objects.for_team(team_id).filter(account_id=account_id)+ if search:+ queryset = queryset.filter(+ Q(title__icontains=search)+ | Q(participants__email__icontains=search)+ | Q(participants__display_name__icontains=search)+ ).distinct()+ count = queryset.count()+ meetings = queryset.order_by("-start_time").prefetch_related("participants")[offset : offset + limit]+ views = [contracts.MeetingView(id=meeting.id,title=meeting.title,@@ -2587,12 +2668,14 @@ def get_account_meetings(display_name=participant.display_name,response_status=participant.response_status,is_organizer=participant.is_organizer,+ person_id=participant.person_id,)for participant in meeting.participants.all()],)for meeting in meetings]+ return views, countdef list_account_notebooks(diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex b4388e5bb45f..53a3a9237207 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -133,6 +133,15 @@ class AccountChannelSummaryView:generated_at: datetime+@dataclass(frozen=True)+class CalendarSyncStatus:+ """Sync state of one connected calendar, as shown in settings."""++ integration_id: int+ last_synced_at: datetime | None+ is_syncing: bool++@dataclass(frozen=True)class MeetingParticipantView:"""One attendee of a synced calendar meeting."""@@ -141,6 +150,7 @@ class MeetingParticipantView:display_name: strresponse_status: stris_organizer: bool+ person_id: UUID | None@dataclass(frozen=True)diff --git a/products/customer_analytics/backend/logic/calendar_sync.py b/products/customer_analytics/backend/logic/calendar_sync.pyindex 56643cdb31d0..d3d6b32a6c43 100644--- a/products/customer_analytics/backend/logic/calendar_sync.py+++ b/products/customer_analytics/backend/logic/calendar_sync.py@@ -23,6 +23,10 @@ EVENTS_URL = "https://www.googleapis.com/calendar/v3/calendars/primary/events"BACKFILL_DAYS = 365PAGE_SIZE = 250SYNC_TOKEN_CONFIG_KEY = "calendar_sync_token"+SYNC_STARTED_AT_CONFIG_KEY = "calendar_sync_started_at"+LAST_SYNCED_AT_CONFIG_KEY = "calendar_last_synced_at"+# Matches the sync activity's start_to_close timeout: past this, an unfinished run is dead.+SYNC_STALE_AFTER = timedelta(minutes=30)PERSON_EMAIL_LOOKUP_QUERY = """SELECT id, properties.email@@ -70,6 +74,9 @@ def sync_calendar_integration(integration_id: int, team_id: int) -> CalendarSyncconnected_email = (integration.config or {}).get("email", "")internal_domain = _domain_of(connected_email)+ integration.config[SYNC_STARTED_AT_CONFIG_KEY] = timezone.now().isoformat()+ integration.save(update_fields=["config"])+counts = CalendarSyncCounts()sync_token = (integration.config or {}).get(SYNC_TOKEN_CONFIG_KEY)try:@@ -78,6 +85,7 @@ def sync_calendar_integration(integration_id: int, team_id: int) -> CalendarSyncnext_sync_token = _sync_events(team, access_token, None, internal_domain, counts)integration.config[SYNC_TOKEN_CONFIG_KEY] = next_sync_token+ integration.config[LAST_SYNCED_AT_CONFIG_KEY] = timezone.now().isoformat()integration.save(update_fields=["config"])return counts@@ -137,6 +145,8 @@ def _process_events(team: Team, events: list[dict], internal_domain: str, countsexternal_emails = {p["email"] for parsed in to_upsert for p in parsed["participants"] if not p["is_internal"]}accounts_by_email = _match_accounts_for_emails(team, sorted(external_emails))+ all_emails = {p["email"] for parsed in to_upsert for p in parsed["participants"]}+ person_uuid_by_email = _person_uuids_by_email(team, sorted(all_emails))for parsed in to_upsert:account = next(@@ -147,7 +157,7 @@ def _process_events(team: Team, events: list[dict], internal_domain: str, countscounts.matched += 1else:counts.unmatched_emails.update(p["email"] for p in parsed["participants"] if not p["is_internal"])- _upsert_meeting(team, parsed, account)+ _upsert_meeting(team, parsed, account, person_uuid_by_email)counts.upserted += 1@@ -197,7 +207,7 @@ def _parse_event(event: dict, internal_domain: str) -> dict | None:}-def _upsert_meeting(team: Team, parsed: dict, account: Account | None) -> None:+def _upsert_meeting(team: Team, parsed: dict, account: Account | None, person_uuid_by_email: dict[str, str]) -> None:defaults = {"title": parsed["title"],"description": parsed["description"],@@ -225,8 +235,11 @@ def _upsert_meeting(team: Team, parsed: dict, account: Account | None) -> None:"display_name": participant["display_name"],"response_status": participant["response_status"],"is_organizer": participant["is_organizer"],+ "person_id": person_uuid_by_email.get(participant["email"]),},)+ current_emails = [participant["email"] for participant in parsed["participants"]]+ MeetingParticipant.objects.for_team(team.id).filter(meeting=meeting).exclude(email__in=current_emails).delete()def _delete_filtered_out(team: Team, event: dict) -> None:@@ -295,7 +308,9 @@ def _match_accounts_for_emails(team: Team, emails: list[str]) -> dict[str, Accoureturn matched-def _group_keys_via_persons(team: Team, emails: list[str], group_type_index: int) -> dict[str, str]:+def _person_uuids_by_email(team: Team, emails: list[str]) -> dict[str, str]:+ if not emails:+ return {}# Deferred: hogql.query pulls the whole query-runner layer into module import.from posthog.hogql import ast # noqa: PLC0415from posthog.hogql.query import execute_hogql_query # noqa: PLC0415@@ -312,6 +327,15 @@ def _group_keys_via_persons(team: Team, emails: list[str], group_type_index: intlower = (prop_email or "").lower()if lower and lower not in email_to_uuid:email_to_uuid[lower] = str(person_uuid)+ return email_to_uuid+++def _group_keys_via_persons(team: Team, emails: list[str], group_type_index: int) -> dict[str, str]:+ # Deferred: hogql.query pulls the whole query-runner layer into module import.+ from posthog.hogql import ast # noqa: PLC0415+ from posthog.hogql.query import execute_hogql_query # noqa: PLC0415++ email_to_uuid = _person_uuids_by_email(team, emails)if not email_to_uuid:return {}diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex 30b07f5cba2f..740cd4ac9248 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -41,6 +41,7 @@ from products.customer_analytics.backend.facade.contracts import (AccountRelationship,AccountRelationshipDefinition,AccountView,+ CalendarSyncStatus,CustomerJourneyView,CustomerProfileConfigView,CustomPropertyDefinitionView,@@ -378,6 +379,36 @@ class SupportTicketSerializer(DataclassSerializer):fields = ["id", "ticket_number", "status", "last_message_at", "last_message_text", "deep_link"]+class CalendarSyncStatusSerializer(DataclassSerializer):+ """Sync state of one connected calendar (read-only)."""++ integration_id = serializers.IntegerField(read_only=True, help_text="Id of the google-calendar integration.")+ last_synced_at = serializers.DateTimeField(+ read_only=True, allow_null=True, help_text="When the last sync run completed; null before the first sync."+ )+ is_syncing = serializers.BooleanField(read_only=True, help_text="Whether a sync run is currently in flight.")++ class Meta:+ dataclass = CalendarSyncStatus+ ref_name = "CalendarSyncStatus"+ fields = ["integration_id", "last_synced_at", "is_syncing"]+++class CalendarSyncTriggerSerializer(serializers.Serializer):+ """Request body of the calendar sync-now trigger."""++ integration_id = serializers.IntegerField(help_text="Id of the google-calendar integration to sync.")+++class CalendarSyncTriggerResponseSerializer(serializers.Serializer):+ """Response of the calendar sync-now trigger."""++ status = serializers.ChoiceField(+ choices=[("started", "started"), ("already_running", "already_running")],+ help_text="'started' (a sync run began) or 'already_running' (a sync for this calendar was already in flight, so this was a no-op).",+ )++class MeetingParticipantSerializer(DataclassSerializer):"""One attendee of a synced calendar meeting (read-only)."""@@ -390,11 +421,14 @@ class MeetingParticipantSerializer(DataclassSerializer):help_text="The attendee's RSVP: 'needs_action', 'accepted', 'declined', or 'tentative'.",)is_organizer = serializers.BooleanField(read_only=True, help_text="Whether this attendee organized the meeting.")+ person_id = serializers.UUIDField(+ read_only=True, allow_null=True, help_text="UUID of the PostHog person resolved for this attendee, if any."+ )class Meta:dataclass = MeetingParticipantViewref_name = "MeetingParticipant"- fields = ["email", "display_name", "response_status", "is_organizer"]+ fields = ["email", "display_name", "response_status", "is_organizer", "person_id"]class MeetingSerializer(DataclassSerializer):diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex 929e0de96c22..64b881f238d6 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -21,7 +21,7 @@ from uuid import UUIDfrom django.db import transactionfrom drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import OpenApiParameter, extend_schema+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schemafrom rest_framework import mixins, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import PermissionDenied, ValidationError@@ -29,12 +29,13 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.throttling import UserRateThrottle+from posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.tagged_item import TaggedItemViewSetMixinfrom posthog.exceptions import Conflictfrom posthog.helpers.impersonation import is_impersonatedfrom posthog.models.user import User-from posthog.permissions import get_authenticator_scopes, is_service_auth+from posthog.permissions import TeamMemberStrictManagementPermission, get_authenticator_scopes, is_service_authfrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom posthog.rbac.user_access_control import UserAccessControl, model_to_resource@@ -47,6 +48,9 @@ from products.customer_analytics.backend.presentation.views.serializers import (AccountRelationshipSerializer,AccountRelationshipWriteSerializer,AccountSerializer,+ CalendarSyncStatusSerializer,+ CalendarSyncTriggerResponseSerializer,+ CalendarSyncTriggerSerializer,CustomerJourneySerializer,CustomerProfileConfigSerializer,CustomPropertyDefinitionSerializer,@@ -964,17 +968,37 @@ class AccountViewSet(return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)return Response(SupportTicketSerializer(instance=tickets, many=True).data)- @extend_schema(parameters=[_ACCOUNT_ID_PARAM], responses={200: MeetingSerializer(many=True)})- @action(methods=["GET"], detail=True, pagination_class=None)+ @extend_schema(+ parameters=[+ _ACCOUNT_ID_PARAM,+ OpenApiParameter(+ name="search",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Filter meetings by title or attendee email/name.",+ ),+ ],+ responses={200: MeetingSerializer(many=True)},+ )+ @action(methods=["GET"], detail=True)def meetings(self, request: Request, *args, **kwargs) -> Response:- meetings = api.get_account_meetings(- self.team_id,- self.kwargs["pk"],- user_access_control=self.user_access_control,- )- if meetings is None:+ if api.get_accessible_account_id(self.team_id, self.kwargs["pk"], self.user_access_control) is None:return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)- return Response(MeetingSerializer(instance=meetings, many=True).data)+ search = request.query_params.get("search", "").strip() or None++ def fetch(offset: int, limit: int) -> tuple[list[contracts.MeetingView], int]:+ result = api.list_account_meetings(+ self.team_id,+ self.kwargs["pk"],+ self.user_access_control,+ offset=offset,+ limit=limit,+ search=search,+ )+ return result if result is not None else ([], 0)++ return self._paginate_via_facade(request, fetch, MeetingSerializer)def dangerously_get_required_scopes(self, request: Request, view) -> builtins.list[str] | None:super_method = getattr(super(), "dangerously_get_required_scopes", None)@@ -1621,3 +1645,34 @@ def _event_stream_write_fields(validated, raw_data: dict) -> dict:"""The event-stream columns the caller actually sent, so a PATCH that omits a fieldleaves it untouched (the serializer fields carry defaults for create)."""return {column: getattr(validated, key) for key, column in _EVENT_STREAM_WRITE_FIELDS.items() if key in raw_data}+++class CalendarSyncViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.GenericViewSet):+ """Calendar-sync controls for Customer analytics settings. Sync runs on an hourly+ Temporal schedule; this surface only offers the manual "sync now" escape hatch."""++ scope_object = "account"+ scope_object_read_actions = ["list"]+ # Same gate as IntegrationViewSet: any member can read status, starting a run needs admin.+ permission_classes = [TeamMemberStrictManagementPermission]+ serializer_class = CalendarSyncTriggerSerializer+ pagination_class = None # a team connects a handful of calendars — nothing to paginate+ queryset = None # no model — state lives in integration config, reached through the facade++ @extend_schema(responses={200: CalendarSyncStatusSerializer(many=True)})+ def list(self, request: Request, *args, **kwargs) -> Response:+ statuses = api.list_calendar_sync_statuses(self.team_id)+ return Response(CalendarSyncStatusSerializer(instance=statuses, many=True).data)++ @validated_request(+ request_serializer=CalendarSyncTriggerSerializer,+ responses={200: OpenApiResponse(response=CalendarSyncTriggerResponseSerializer)},+ summary="Sync a connected calendar now",+ description="Start a sync run for one connected Google Calendar immediately, outside the hourly schedule.",+ )+ @action(methods=["POST"], detail=False, url_path="sync_now")+ def sync_now(self, request: ValidatedRequest, *args, **kwargs) -> Response:+ result = api.trigger_calendar_sync(self.team_id, request.validated_data["integration_id"])+ if result is None:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)+ return Response(CalendarSyncTriggerResponseSerializer({"status": result}).data)diff --git a/products/customer_analytics/backend/routes.py b/products/customer_analytics/backend/routes.pyindex 75e553de0f4e..78caffc568ec 100644--- a/products/customer_analytics/backend/routes.py+++ b/products/customer_analytics/backend/routes.py@@ -10,6 +10,7 @@ from products.customer_analytics.backend.presentation.views.views import (AccountRelationshipDefinitionViewSet,AccountRelationshipViewSet,AccountViewSet,+ CalendarSyncViewSet,CustomerJourneyViewSet,CustomerProfileConfigViewSet,CustomPropertyDefinitionViewSet,@@ -69,6 +70,12 @@ def register_routes(routers: RouterRegistry) -> None:"project_event_streams",["team_id"],)+ routers.projects.register(+ r"calendar_sync",+ CalendarSyncViewSet,+ "project_calendar_sync",+ ["team_id"],+ )project_accounts_router = routers.projects.register(r"accounts", AccountViewSet, "project_accounts", ["team_id"])project_accounts_router.register(r"notebooks", AccountNotebookViewSet, "project_account_notebooks", ["team_id", "account_id"]diff --git a/products/customer_analytics/backend/test/test_calendar_sync.py b/products/customer_analytics/backend/test/test_calendar_sync.pyindex a0ad0f484d87..ce7e10eb23c3 100644--- a/products/customer_analytics/backend/test/test_calendar_sync.py+++ b/products/customer_analytics/backend/test/test_calendar_sync.py@@ -45,9 +45,11 @@ class TestCalendarSync(BaseTest):sensitive_config={"access_token": "ACCESS", "refresh_token": "REFRESH"},)- def _sync(self, responses: list[MagicMock]) -> calendar_sync.CalendarSyncCounts:+ def _sync(+ self, responses: list[MagicMock], person_uuids: dict[str, str] | None = None+ ) -> calendar_sync.CalendarSyncCounts:with (- patch.object(calendar_sync, "_group_keys_via_persons", return_value={}),+ patch.object(calendar_sync, "_person_uuids_by_email", return_value=person_uuids or {}),patch.object(calendar_sync.requests, "get", side_effect=responses),):return calendar_sync.sync_calendar_integration(self.integration.id, self.team.id)@@ -148,6 +150,28 @@ class TestCalendarSync(BaseTest):self._sync([_pages_response([event])])assert Meeting.objects.for_team(self.team.id).get().account_id == account.id+ def test_removed_attendee_is_deleted_on_resync(self):+ self._sync([_pages_response([_event()])])+ assert MeetingParticipant.objects.for_team(self.team.id).count() == 2++ only_organizer = _event(+ attendees=[+ {"email": "[email protected]", "responseStatus": "accepted"},+ {"email": "[email protected]", "responseStatus": "accepted"},+ ]+ )+ self._sync([_pages_response([only_organizer])])+ emails = set(MeetingParticipant.objects.for_team(self.team.id).values_list("email", flat=True))+ assert emails == {"[email protected]", "[email protected]"}++ def test_resolved_person_uuid_is_stored_on_participants(self):+ person_uuid = "0198b6f3-0000-0000-0000-000000000001"+ self._sync([_pages_response([_event()])], person_uuids={"[email protected]": person_uuid})++ participants = {p.email: p for p in MeetingParticipant.objects.for_team(self.team.id)}+ assert str(participants["[email protected]"].person_id) == person_uuid+ assert participants["[email protected]"].person_id is None+def test_ambiguous_email_domain_matches_nothing(self):for name in ("Acme US", "Acme EU"):account = Account.objects.for_team(self.team.id).create(diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.pyindex c4bec20c78a0..16233507efab 100644--- a/products/customer_analytics/backend/test/test_views.py+++ b/products/customer_analytics/backend/test/test_views.py@@ -2666,6 +2666,98 @@ class TestAccountSupportTicketViewSet(APIBaseTest):self.assertEqual(status.HTTP_403_FORBIDDEN, self.client.get(self.endpoint).status_code)+class TestCalendarSyncViewSet(APIBaseTest):+ def _become_admin(self):+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()++ def test_sync_now_starts_the_workflow_for_a_team_owned_integration(self):+ from posthog.models.integration import Integration++ self._become_admin()+ integration = Integration.objects.create(team=self.team, kind="google-calendar", integration_id="sub-1")+ with patch("posthog.temporal.common.client.sync_connect") as mock_connect:+ mock_connect.return_value.start_workflow.return_value = _immediate_future()+ response = self.client.post(+ f"/api/environments/{self.team.id}/calendar_sync/sync_now/",+ {"integration_id": integration.id},+ )++ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())+ self.assertEqual(response.json(), {"status": "started"})+ workflow_kwargs = mock_connect.return_value.start_workflow.call_args.kwargs+ self.assertEqual(workflow_kwargs["id"], f"google-calendar-sync-{integration.id}")++ def test_list_reports_last_synced_and_in_flight_runs(self):+ from datetime import timedelta++ from django.utils import timezone as dj_timezone++ from posthog.models.integration import Integration++ now = dj_timezone.now()+ synced = Integration.objects.create(+ team=self.team,+ kind="google-calendar",+ integration_id="sub-synced",+ config={+ "calendar_sync_started_at": (now - timedelta(minutes=5)).isoformat(),+ "calendar_last_synced_at": (now - timedelta(minutes=4)).isoformat(),+ },+ )+ syncing = Integration.objects.create(+ team=self.team,+ kind="google-calendar",+ integration_id="sub-syncing",+ config={"calendar_sync_started_at": (now - timedelta(minutes=1)).isoformat()},+ )+ stale = Integration.objects.create(+ team=self.team,+ kind="google-calendar",+ integration_id="sub-stale",+ config={"calendar_sync_started_at": (now - timedelta(hours=2)).isoformat()},+ )++ response = self.client.get(f"/api/environments/{self.team.id}/calendar_sync/")++ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())+ by_id = {row["integration_id"]: row for row in response.json()}+ self.assertFalse(by_id[synced.id]["is_syncing"])+ self.assertIsNotNone(by_id[synced.id]["last_synced_at"])+ self.assertTrue(by_id[syncing.id]["is_syncing"])+ self.assertFalse(by_id[stale.id]["is_syncing"])++ def test_sync_now_404s_for_another_teams_integration(self):+ from posthog.models.integration import Integration++ self._become_admin()+ other_team = Team.objects.create(organization=self.organization, name="other")+ integration = Integration.objects.create(team=other_team, kind="google-calendar", integration_id="sub-2")+ response = self.client.post(+ f"/api/environments/{self.team.id}/calendar_sync/sync_now/",+ {"integration_id": integration.id},+ )+ self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)++ def test_sync_now_requires_project_admin(self):+ from posthog.models.integration import Integration++ integration = Integration.objects.create(team=self.team, kind="google-calendar", integration_id="sub-3")+ response = self.client.post(+ f"/api/environments/{self.team.id}/calendar_sync/sync_now/",+ {"integration_id": integration.id},+ )+ self.assertEqual(status.HTTP_403_FORBIDDEN, response.status_code)+++def _immediate_future():++ async def _done():+ return None++ return _done()++class TestAccountMeetingViewSet(APIBaseTest):def test_list_returns_the_accounts_meetings_newest_first_with_participants(self):account = Account.objects.unscoped().create(team=self.team, name="Acme Corp", external_id="acme-1")@@ -2686,9 +2778,35 @@ class TestAccountMeetingViewSet(APIBaseTest):response = self.client.get(f"/api/environments/{self.team.id}/accounts/{account.id}/meetings/")self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())- data = response.json()+ payload = response.json()+ self.assertEqual(payload["count"], 2)+ data = payload["results"]self.assertEqual([m["id"] for m in data], [str(newer.id), str(older.id)])self.assertEqual(data[0]["participants"],- [{"email": "[email protected]", "display_name": "", "response_status": "accepted", "is_organizer": False}],+ [+ {+ "email": "[email protected]",+ "display_name": "",+ "response_status": "accepted",+ "is_organizer": False,+ "person_id": None,+ }+ ],+ )++ def test_search_filters_by_title_or_attendee(self):+ account = Account.objects.unscoped().create(team=self.team, name="Acme Corp", external_id="acme-2")+ review = Meeting.objects.unscoped().create(+ team=self.team, account=account, ical_uid="uid-r", start_time="2026-08-01T15:00:00Z", title="Review")+ kickoff = Meeting.objects.unscoped().create(+ team=self.team, account=account, ical_uid="uid-k", start_time="2026-08-02T15:00:00Z", title="Kickoff"+ )+ MeetingParticipant.objects.unscoped().create(team=self.team, meeting=kickoff, email="[email protected]")++ endpoint = f"/api/environments/{self.team.id}/accounts/{account.id}/meetings/"+ by_title = self.client.get(endpoint, {"search": "review"}).json()+ self.assertEqual([m["id"] for m in by_title["results"]], [str(review.id)])+ by_attendee = self.client.get(endpoint, {"search": "jane"}).json()+ self.assertEqual([m["id"] for m in by_attendee["results"]], [str(kickoff.id)])diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex de3fe10fdf57..262d49dc6c9c 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -135,7 +135,8 @@ Each ticket row links to the ticket in the conversations UI via the `deep_link`Like Opportunities, it loads directly in the logic (no embedded query), so the root `useMountedLogic` is enough — no `useAttachedLogic` needed.The Meetings tab (flag-gated, `CUSTOMER_ANALYTICS_CSP`) lists the account's synced Google Calendar meetings from the `accounts/:id/meetings` endpoint — rows are written by the calendar-sync Temporal workflow (`backend/logic/calendar_sync.py`) from calendars connected in Customer analytics settings, and attach to an account via known emails → person resolution → email domains.-`accountMeetingsLogic` owns three states like the Support tickets tab (skeleton / load-failed / "no meetings yet"), plus the **"Edit matching" dropdown**: two `LemonInputSelect` chip inputs editing the account's `email_domains` and `known_emails` properties (normalized, merged into `properties` via `accountsPartialUpdate`, propagated through `accountLinksLogic.loadAccountSuccess`).+`accountMeetingsLogic` owns three states like the Support tickets tab (skeleton on first load / load-failed / "no meetings yet"), plus **server-side pagination and search** (like the Users tab: `page` + `searchTerm` feed the endpoint's `limit`/`offset`/`search` params; search debounces, resets to page 1, and fires `MeetingsSearched`), the **attendee cell** state (first 3 attendees shown, "+N more"/"show less" toggles `expandedAttendeeMeetingIds`; attendees with a resolved `person_id` — populated by the sync via the same HogQL person-email lookup the account matching uses — get a leading `ProfilePicture` (xs, gravatar-by-email) and link to their person page, firing `MeetingAttendeeClicked`; each attendee carries a minimal RSVP glyph after the name — green check accepted, red x declined, muted "?" tentative, nothing for needs_action), and the **"Edit matching" inline panel**: two `LemonInputSelect` chip inputs editing the account's `email_domains` and `known_emails` properties (normalized, merged into `properties` via `accountsPartialUpdate`, propagated through `accountLinksLogic.loadAccountSuccess`).+The matching editor is deliberately an inline panel above the table, not a dropdown — the `LemonInputSelect` suggestion popover opens below the inputs and would cover Save/Cancel inside a small overlay, so the buttons sit beside the inputs instead.Saving fires `MeetingMatchingSaved`; a newly saved matching only affects meetings the sync processes afterwards — it does not retro-match already-synced meetings.Like Opportunities, data loads directly in the logic, so the root `useMountedLogic` is enough.@@ -275,6 +276,8 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions| `customer analytics account summaries page changed` | `accountSummariesLogic` `loadSummariesPage` listener (only dispatched by the pagination controls) | `page` || `customer analytics account support ticket clicked` | `AccountSupportTicketsExpansion.tsx` ticket `<Link>` `onClick` | _(none — ticket number/customer content kept out)_ || `customer analytics account meeting matching saved` | `accountMeetingsLogic` `saveMatching` listener (after the PATCH succeeds) | `domain_count`, `email_count` (no raw domains/emails — customer PII kept out) |+| `customer analytics account meetings searched` | `accountMeetingsLogic` `setSearchTerm` listener (post-debounce) | `has_query`, `query_length` (no raw text) |+| `customer analytics account meeting attendee clicked` | `AccountMeetingsExpansion.tsx` attendee `<Link>` `onClick` (person links only) | _(none — attendee email/person id is customer PII and kept out)_ || `customer analytics account event stream toggled` | `eventStreamLogic` (`../EventStream/`) `setAccountMembership` listener — the "Include in event stream" toggle in the expanded row's Event stream tab | `account_id`, `included`, `member_count` || `customer analytics event stream config saved` | `eventStreamLogic` `saveEventStreamSuccess` listener — the Save button in the Event stream settings section | `enabled`, `event_count`, `has_slack_channel`, `member_count` || `customer analytics event stream test message sent` | `eventStreamLogic` `sendTestMessageSuccess` listener — the "Send test message" button in the Event stream settings section | `event_count`, `member_count` |diff --git a/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsxindex f91dc8a922ab..7e1c49acb51a 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsx@@ -1,93 +1,141 @@import { useActions, useValues } from 'kea'+import posthog from 'posthog-js'-import { IconPencil } from '@posthog/icons'+import { IconCheck, IconPencil, IconX } from '@posthog/icons'import {LemonButton,- LemonDivider,- LemonDropdown,+ LemonInput,LemonInputSelect,LemonSkeleton,LemonTable,LemonTableColumns,LemonTag,+ Link,+ ProfilePicture,} from '@posthog/lemon-ui'import { BigLeaguesHog } from 'lib/components/hedgehogs'import { TZLabel } from 'lib/components/TZLabel'+import { urls } from 'scenes/urls'-import { MeetingApi } from 'products/customer_analytics/frontend/generated/api.schemas'+import { MeetingApi, MeetingParticipantApi } from 'products/customer_analytics/frontend/generated/api.schemas'-import { accountMeetingsLogic, NOT_LOADED } from './accountMeetingsLogic'+import { accountMeetingsLogic, NOT_LOADED, PAGE_SIZE } from './accountMeetingsLogic'+import { AccountsEvents } from './constants'-// Matches the Support tickets tab, the other client-side-paginated account tab.-const PAGE_SIZE = 10+const COLLAPSED_ATTENDEE_COUNT = 3-function EditMeetingMatchingButton({ accountId }: { accountId: string }): JSX.Element {+function MatchingEditor({ accountId }: { accountId: string }): JSX.Element {const logic = accountMeetingsLogic({ accountId })- const { matchingEditorOpen, domainsDraft, emailsDraft, savingMatching } = useValues(logic)- const { openMatchingEditor, closeMatchingEditor, setDomainsDraft, setEmailsDraft, saveMatching } = useActions(logic)+ const { domainsDraft, emailsDraft, savingMatching } = useValues(logic)+ const { closeMatchingEditor, setDomainsDraft, setEmailsDraft, saveMatching } = useActions(logic)return (- <LemonDropdown- closeOnClickInside={false}- visible={matchingEditorOpen}- onVisibilityChange={(visible) => {- if (!visible) {- closeMatchingEditor()- }- }}- showArrow- overlay={- <div className="flex flex-col gap-2 w-80">- <span className="text-xs text-secondary">- Meetings with attendees at these domains or addresses match this account.- </span>- <div className="flex flex-col gap-1">- <span className="text-xs font-semibold text-secondary">Email domains</span>- <LemonInputSelect- mode="multiple"- allowCustomValues- disableFiltering- size="small"- value={domainsDraft}- onChange={setDomainsDraft}- placeholder="acme.com"- />- </div>- <div className="flex flex-col gap-1">- <span className="text-xs font-semibold text-secondary">Known emails</span>- <LemonInputSelect- mode="multiple"- allowCustomValues- disableFiltering- size="small"- value={emailsDraft}- onChange={setEmailsDraft}- placeholder="[email protected]"- />- </div>- <LemonDivider className="my-1" />- <div className="flex flex-row gap-2 justify-end">- <LemonButton size="xsmall" type="secondary" onClick={closeMatchingEditor}>- Cancel- </LemonButton>- <LemonButton size="xsmall" type="primary" onClick={saveMatching} loading={savingMatching}>- Save- </LemonButton>- </div>+ <div className="flex flex-col gap-2 border rounded p-3 bg-bg-light">+ <span className="text-xs text-secondary">+ Meetings with attendees at these domains or addresses match this account.+ </span>+ <div className="flex flex-wrap items-end gap-2">+ <div className="flex flex-col gap-1 flex-1 min-w-56">+ <span className="text-xs font-semibold text-secondary">Email domains</span>+ <LemonInputSelect+ mode="multiple"+ allowCustomValues+ disableFiltering+ size="small"+ value={domainsDraft}+ onChange={setDomainsDraft}+ placeholder="acme.com"+ />+ </div>+ <div className="flex flex-col gap-1 flex-1 min-w-56">+ <span className="text-xs font-semibold text-secondary">Known emails</span>+ <LemonInputSelect+ mode="multiple"+ allowCustomValues+ disableFiltering+ size="small"+ value={emailsDraft}+ onChange={setEmailsDraft}+ placeholder="[email protected]"+ /></div>- }+ <div className="flex flex-row gap-2 shrink-0">+ <LemonButton size="small" type="secondary" onClick={closeMatchingEditor}>+ Cancel+ </LemonButton>+ <LemonButton size="small" type="primary" onClick={saveMatching} loading={savingMatching}>+ Save+ </LemonButton>+ </div>+ </div>+ </div>+ )+}++const RSVP_ICONS: Partial<Record<string, JSX.Element>> = {+ accepted: <IconCheck className="text-success" />,+ declined: <IconX className="text-danger" />,+ tentative: <span className="text-muted font-medium">?</span>,+}++function AttendeeLink({ participant }: { participant: MeetingParticipantApi }): JSX.Element {+ const label = participant.display_name || participant.email+ const rsvp = RSVP_ICONS[participant.response_status]+ const name = participant.person_id ? (+ <Link+ to={urls.personByUUID(participant.person_id)}+ title={participant.email}+ onClick={() => posthog.capture(AccountsEvents.MeetingAttendeeClicked)}>- <LemonButton- size="small"- type="secondary"- icon={<IconPencil />}- data-attr="edit-meeting-matching"- onClick={openMatchingEditor}- >- Edit matching- </LemonButton>- </LemonDropdown>+ {label}+ </Link>+ ) : (+ <span title={participant.email}>{label}</span>+ )+ return (+ <span className="inline-flex items-center gap-1 align-bottom">+ {participant.person_id && <ProfilePicture user={{ email: participant.email }} size="xs" />}+ {name}+ {rsvp && (+ <span className="text-xs leading-none" title={`RSVP: ${participant.response_status}`}>+ {rsvp}+ </span>+ )}+ </span>+ )+}++function AttendeeList({ accountId, meeting }: { accountId: string; meeting: MeetingApi }): JSX.Element {+ const logic = accountMeetingsLogic({ accountId })+ const { expandedAttendeeMeetingIds } = useValues(logic)+ const { toggleAttendeesExpanded } = useActions(logic)++ const expanded = expandedAttendeeMeetingIds.includes(meeting.id)+ const shown = expanded ? meeting.participants : meeting.participants.slice(0, COLLAPSED_ATTENDEE_COUNT)+ const hiddenCount = meeting.participants.length - shown.length++ return (+ <span className="text-sm">+ {shown.map((participant, index) => (+ <span key={participant.email}>+ <AttendeeLink participant={participant} />+ {index < shown.length - 1 ? ', ' : ''}+ </span>+ ))}+ {hiddenCount > 0 && (+ <>+ {', '}+ <Link onClick={() => toggleAttendeesExpanded(meeting.id)}>+{hiddenCount} more</Link>+ </>+ )}+ {expanded && meeting.participants.length > COLLAPSED_ATTENDEE_COUNT && (+ <>+ {' '}+ <Link onClick={() => toggleAttendeesExpanded(meeting.id)}>show less</Link>+ </>+ )}+ </span>)}@@ -107,53 +155,52 @@ const STATUS_TAG_TYPE = {cancelled: 'danger',} as const-const columns: LemonTableColumns<MeetingApi> = [- {- title: 'Meeting',- key: 'title',- render: (_, meeting) =>- meeting.title ? (- <span className="font-medium line-clamp-1">{meeting.title}</span>- ) : (- <span className="text-muted italic">Untitled meeting</span>- ),- },- {- title: 'When',- key: 'start_time',- width: 140,- render: (_, meeting) => <TZLabel time={meeting.start_time} />,- sorter: (a, b) => a.start_time.localeCompare(b.start_time),- },- {- title: 'Attendees',- key: 'participants',- render: (_, meeting) => (- <span className="line-clamp-1 text-sm">- {meeting.participants.map((participant) => participant.display_name || participant.email).join(', ')}- </span>- ),- },- {- title: 'Status',- key: 'status',- width: 100,- render: (_, meeting) => (- <LemonTag type={STATUS_TAG_TYPE[meeting.status as keyof typeof STATUS_TAG_TYPE] ?? 'default'}>- {meeting.status}- </LemonTag>- ),- },-]-export function AccountMeetingsExpansion({ accountId }: { accountId: string }): JSX.Element {- const { meetingsResult, meetingsResultLoading } = useValues(accountMeetingsLogic({ accountId }))+ const logic = accountMeetingsLogic({ accountId })+ const { meetingsResult, meetingsResultLoading, searchTerm, page, matchingEditorOpen } = useValues(logic)+ const { setSearchTerm, setPage, openMatchingEditor } = useActions(logic)- if (meetingsResultLoading || meetingsResult === NOT_LOADED) {+ if (meetingsResult === NOT_LOADED) {return <LemonSkeleton className="h-64 w-full" />}- const { meetings, loadFailed } = meetingsResult+ const { meetings, count, loadFailed } = meetingsResult+ const hasSearch = searchTerm.trim().length > 0++ const columns: LemonTableColumns<MeetingApi> = [+ {+ title: 'Meeting',+ key: 'title',+ render: (_, meeting) =>+ meeting.title ? (+ <span className="font-medium line-clamp-1">{meeting.title}</span>+ ) : (+ <span className="text-muted italic">Untitled meeting</span>+ ),+ },+ {+ title: 'When',+ key: 'start_time',+ width: 140,+ render: (_, meeting) => <TZLabel time={meeting.start_time} />,+ sorter: (a, b) => a.start_time.localeCompare(b.start_time),+ },+ {+ title: 'Attendees',+ key: 'participants',+ render: (_, meeting) => <AttendeeList accountId={accountId} meeting={meeting} />,+ },+ {+ title: 'Status',+ key: 'status',+ width: 100,+ render: (_, meeting) => (+ <LemonTag type={STATUS_TAG_TYPE[meeting.status as keyof typeof STATUS_TAG_TYPE] ?? 'default'}>+ {meeting.status}+ </LemonTag>+ ),+ },+ ]let content: JSX.Elementif (loadFailed) {@@ -163,7 +210,7 @@ export function AccountMeetingsExpansion({ accountId }: { accountId: string }):detail="Something went wrong loading this account's meetings. Try refreshing the page."/>)- } else if (!meetings || meetings.length === 0) {+ } else if (count === 0 && !hasSearch && !meetingsResultLoading) {content = (<MeetingsEmptyStatetitle="No meetings yet"@@ -175,19 +222,46 @@ export function AccountMeetingsExpansion({ accountId }: { accountId: string }):<LemonTable<MeetingApi>size="small"embedded- dataSource={meetings}+ dataSource={meetings ?? []}columns={columns}rowKey="id"- pagination={{ pageSize: PAGE_SIZE }}+ loading={meetingsResultLoading}+ pagination={{+ controlled: true,+ pageSize: PAGE_SIZE,+ currentPage: page,+ entryCount: count,+ onForward: () => setPage(page + 1),+ onBackward: () => setPage(page - 1),+ }}+ emptyState="No meetings match your search."/>)}return (<div className="flex flex-col gap-2">- <div className="flex justify-end">- <EditMeetingMatchingButton accountId={accountId} />+ <div className="flex flex-wrap items-center justify-between gap-2">+ <LemonInput+ type="search"+ placeholder="Search by meeting or attendee..."+ value={searchTerm}+ onChange={setSearchTerm}+ size="small"+ className="min-w-64"+ />+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconPencil />}+ active={matchingEditorOpen}+ data-attr="edit-meeting-matching"+ onClick={openMatchingEditor}+ >+ Edit matching+ </LemonButton></div>+ {matchingEditorOpen && <MatchingEditor accountId={accountId} />}{content}</div>)diff --git a/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.test.tsindex e29e7d193b8a..61514b834eeb 100644--- a/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.test.ts@@ -8,9 +8,9 @@ import {accountsPartialUpdate,accountsRetrieve,} from 'products/customer_analytics/frontend/generated/api'-import type { AccountApi, MeetingApi } from 'products/customer_analytics/frontend/generated/api.schemas'+import type { AccountApi, PaginatedMeetingListApi } from 'products/customer_analytics/frontend/generated/api.schemas'-import { accountMeetingsLogic } from './accountMeetingsLogic'+import { accountMeetingsLogic, PAGE_SIZE } from './accountMeetingsLogic'jest.mock('products/customer_analytics/frontend/generated/api', () => ({// Keep the real module for everything else — connected logics call other generated@@ -25,6 +25,10 @@ const mockList = accountsMeetingsList as jest.MockedFunction<typeof accountsMeetconst mockRetrieve = accountsRetrieve as jest.MockedFunction<typeof accountsRetrieve>const mockPartialUpdate = accountsPartialUpdate as jest.MockedFunction<typeof accountsPartialUpdate>+function pageOf(meetings: any[], count?: number): PaginatedMeetingListApi {+ return { results: meetings, count: count ?? meetings.length, next: null, previous: null }+}+describe('accountMeetingsLogic', () => {let logic: ReturnType<typeof accountMeetingsLogic.build>@@ -47,12 +51,12 @@ describe('accountMeetingsLogic', () => {}it('loads the account meetings', async () => {- const meetings = [{ id: 'm-1', title: 'Kickoff', status: 'confirmed' }] as MeetingApi[]- mockList.mockResolvedValue(meetings)+ const meetings = [{ id: 'm-1', title: 'Kickoff', status: 'confirmed' }]+ mockList.mockResolvedValue(pageOf(meetings))await mount()- expect(logic.values.meetingsResult).toEqual({ meetings })+ expect(logic.values.meetingsResult).toEqual({ meetings, count: 1 })})it('surfaces a load-failed result (not an infinite skeleton) and captures the error when the fetch throws', async () => {@@ -60,12 +64,34 @@ describe('accountMeetingsLogic', () => {await mount()- expect(logic.values.meetingsResult).toEqual({ meetings: null, loadFailed: true })+ expect(logic.values.meetingsResult).toEqual({ meetings: null, count: 0, loadFailed: true })expect(posthog.captureException).toHaveBeenCalledTimes(1)})+ it('search resets to page 1 and reloads with the search param; paging sends the matching offset', async () => {+ mockList.mockResolvedValue(pageOf([], 25))+ await mount()++ logic.actions.setPage(3)+ await expectLogic(logic).toFinishAllListeners()+ expect(mockList).toHaveBeenLastCalledWith(expect.any(String), 'acc-1', {+ limit: PAGE_SIZE,+ offset: 2 * PAGE_SIZE,+ search: undefined,+ })++ logic.actions.setSearchTerm('jane')+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.page).toBe(1)+ expect(mockList).toHaveBeenLastCalledWith(expect.any(String), 'acc-1', {+ limit: PAGE_SIZE,+ offset: 0,+ search: 'jane',+ })+ })+it('saves normalized matching values without clobbering other account properties', async () => {- mockList.mockResolvedValue([])+ mockList.mockResolvedValue(pageOf([]))mockRetrieve.mockResolvedValue({id: 'acc-1',properties: { billing_id: 'cus_123', email_domains: ['old.com'] },diff --git a/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.tsindex 80779da29ea5..ab8281f8a62a 100644--- a/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.ts@@ -19,17 +19,21 @@ import type {import { accountLinksLogic } from './accountLinksLogic'import { AccountsEvents } from './constants'+// Matches the Users tab, the other server-side-paginated account tab.+export const PAGE_SIZE = 10+export interface AccountMeetingsLogicProps {accountId: string}export interface AccountMeetingsResult {meetings: MeetingApi[] | null+ count: numberloadFailed?: boolean}// The view compares against this by reference to tell "not loaded yet" from a loaded empty result.-export const NOT_LOADED: AccountMeetingsResult = { meetings: null }+export const NOT_LOADED: AccountMeetingsResult = { meetings: null, count: 0 }function cleanEmails(values: string[]): string[] {return Array.from(new Set(values.map((value) => value.trim().toLowerCase()).filter(Boolean)))@@ -45,10 +49,13 @@ export interface accountMeetingsLogicValues {currentTeamId: number | null // teamLogicdomainsDraft: string[]emailsDraft: string[]+ expandedAttendeeMeetingIds: string[]matchingEditorOpen: booleanmeetingsResult: AccountMeetingsResultmeetingsResultLoading: boolean+ page: numbersavingMatching: boolean+ searchTerm: string}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -96,6 +103,15 @@ export interface accountMeetingsLogicActions {setEmailsDraft: (emails: string[]) => {emails: string[]}+ setPage: (page: number) => {+ page: number+ }+ setSearchTerm: (searchTerm: string) => {+ searchTerm: string+ }+ toggleAttendeesExpanded: (meetingId: string) => {+ meetingId: string+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -126,6 +142,9 @@ export const accountMeetingsLogic = kea<accountMeetingsLogicType>([saveMatching: true,saveMatchingStarted: true,saveMatchingFinished: true,+ setSearchTerm: (searchTerm: string) => ({ searchTerm }),+ setPage: (page: number) => ({ page }),+ toggleAttendeesExpanded: (meetingId: string) => ({ meetingId }),}),loaders(({ props, values }) => ({meetingsResult: [@@ -133,13 +152,17 @@ export const accountMeetingsLogic = kea<accountMeetingsLogicType>([{loadMeetings: async (): Promise<AccountMeetingsResult> => {try {- const meetings = await accountsMeetingsList(String(values.currentTeamId), props.accountId)- return { meetings }+ const response = await accountsMeetingsList(String(values.currentTeamId), props.accountId, {+ limit: PAGE_SIZE,+ offset: (values.page - 1) * PAGE_SIZE,+ search: values.searchTerm.trim() || undefined,+ })+ return { meetings: [...response.results], count: response.count }} catch (error) {posthog.captureException(error as Error, {scope: 'accountMeetingsLogic.loadMeetings',})- return { meetings: null, loadFailed: true }+ return { meetings: null, count: 0, loadFailed: true }}},},@@ -172,8 +195,37 @@ export const accountMeetingsLogic = kea<accountMeetingsLogicType>([saveMatchingFinished: () => false,},],+ searchTerm: [+ '',+ {+ setSearchTerm: (_, { searchTerm }) => searchTerm,+ },+ ],+ page: [+ 1,+ {+ setPage: (_, { page }) => page,+ setSearchTerm: () => 1,+ },+ ],+ expandedAttendeeMeetingIds: [+ [] as string[],+ {+ toggleAttendeesExpanded: (state, { meetingId }) =>+ state.includes(meetingId) ? state.filter((id) => id !== meetingId) : [...state, meetingId],+ },+ ],}),listeners(({ actions, values, props }) => ({+ setPage: () => actions.loadMeetings(),+ setSearchTerm: async ({ searchTerm }, breakpoint) => {+ await breakpoint(300)+ actions.loadMeetings()+ posthog.capture(AccountsEvents.MeetingsSearched, {+ has_query: searchTerm.trim().length > 0,+ query_length: searchTerm.trim().length,+ })+ },openMatchingEditor: () => {actions.setDomainsDraft(values.account?.properties?.email_domains ?? [])actions.setEmailsDraft(values.account?.properties?.known_emails ?? [])diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.tsindex fc4fa250599b..1f0ceed06a48 100644--- a/products/customer_analytics/frontend/components/Accounts/constants.ts+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts@@ -57,6 +57,8 @@ export const AccountsEvents = {SummariesPageChanged: 'customer analytics account summaries page changed',SupportTicketClicked: 'customer analytics account support ticket clicked',MeetingMatchingSaved: 'customer analytics account meeting matching saved',+ MeetingsSearched: 'customer analytics account meetings searched',+ MeetingAttendeeClicked: 'customer analytics account meeting attendee clicked',EventStreamMembershipToggled: 'customer analytics account event stream toggled',EventStreamConfigSaved: 'customer analytics event stream config saved',EventStreamTestMessageSent: 'customer analytics event stream test message sent',diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 94d43af363bf..eea285f6fe3d 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -458,6 +458,11 @@ export interface MeetingParticipantApi {readonly response_status: string/** Whether this attendee organized the meeting. */readonly is_organizer: boolean+ /**+ * UUID of the PostHog person resolved for this attendee, if any.+ * @nullable+ */+ readonly person_id: string | null}/**@@ -483,6 +488,15 @@ export interface MeetingApi {readonly participants: readonly MeetingParticipantApi[]}+export interface PaginatedMeetingListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: MeetingApi[]+}+/*** Metadata for one message a channel summary covered — never the message text.*/@@ -667,6 +681,52 @@ export interface AnnouncementChannelApi {customer_name: string | null}+/**+ * Sync state of one connected calendar (read-only).+ */+export interface CalendarSyncStatusApi {+ /** Id of the google-calendar integration. */+ readonly integration_id: number+ /**+ * When the last sync run completed; null before the first sync.+ * @nullable+ */+ readonly last_synced_at: string | null+ /** Whether a sync run is currently in flight. */+ readonly is_syncing: boolean+}++/**+ * Request body of the calendar sync-now trigger.+ */+export interface CalendarSyncTriggerApi {+ /** Id of the google-calendar integration to sync. */+ integration_id: number+}++/**+ * * `started` - started+ * * `already_running` - already_running+ */+export type CalendarSyncTriggerResponseStatusEnumApi =+ (typeof CalendarSyncTriggerResponseStatusEnumApi)[keyof typeof CalendarSyncTriggerResponseStatusEnumApi]++export const CalendarSyncTriggerResponseStatusEnumApi = {+ Started: 'started',+ AlreadyRunning: 'already_running',+} as const++/**+ * Response of the calendar sync-now trigger.+ */+export interface CalendarSyncTriggerResponseApi {+ /** 'started' (a sync run began) or 'already_running' (a sync for this calendar was already in flight, so this was a no-op).+ *+ * * `started` - started+ * * `already_running` - already_running */+ status: CalendarSyncTriggerResponseStatusEnumApi+}+/*** * `text` - text* * `number` - number@@ -1540,6 +1600,21 @@ export type AccountsRelationshipsListParams = {include_history?: boolean}+export type AccountsMeetingsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+ /**+ * Filter meetings by title or attendee email/name.+ */+ search?: string+}+export type AccountsSummariesListParams = {/*** Number of results to return per page.diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.tsindex d29bc7fc9998..acf5eab725d3 100644--- a/products/customer_analytics/frontend/generated/api.ts+++ b/products/customer_analytics/frontend/generated/api.ts@@ -17,12 +17,16 @@ import type {AccountRelationshipDefinitionsListParams,AccountRelationshipWriteApi,AccountsListParams,+ AccountsMeetingsListParams,AccountsNotebooksListParams,AccountsRelationshipsListParams,AccountsSummariesListParams,AnnouncementApi,AnnouncementChannelApi,AnnouncementsListParams,+ CalendarSyncStatusApi,+ CalendarSyncTriggerApi,+ CalendarSyncTriggerResponseApi,CustomPropertyDefinitionApi,CustomPropertyDefinitionsListParams,CustomPropertyDefinitionsValuesRetrieveParams,@@ -45,7 +49,6 @@ import type {ExternalAccountListPageApi,GroupUsageMetricApi,GroupsTypesMetricsListParams,- MeetingApi,PaginatedAccountChannelSummaryListApi,PaginatedAccountListApi,PaginatedAccountNoteListApi,@@ -58,6 +61,7 @@ import type {PaginatedCustomerJourneyListApi,PaginatedCustomerProfileConfigListApi,PaginatedGroupUsageMetricListApi,+ PaginatedMeetingListApi,PatchedAccountApi,PatchedAccountRelationshipDefinitionApi,PatchedCustomPropertyDefinitionApi,@@ -547,16 +551,29 @@ export const accountsDestroy = async (projectId: string, id: string, options?: R})}-export const getAccountsMeetingsListUrl = (projectId: string, id: string) => {- return `/api/projects/${projectId}/accounts/${id}/meetings/`+export const getAccountsMeetingsListUrl = (projectId: string, id: string, params?: AccountsMeetingsListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/accounts/${id}/meetings/?${stringifiedParams}`+ : `/api/projects/${projectId}/accounts/${id}/meetings/`}export const accountsMeetingsList = async (projectId: string,id: string,+ params?: AccountsMeetingsListParams,options?: RequestInit-): Promise<MeetingApi[]> => {- return apiMutator<MeetingApi[]>(getAccountsMeetingsListUrl(projectId, id), {+): Promise<PaginatedMeetingListApi> => {+ return apiMutator<PaginatedMeetingListApi>(getAccountsMeetingsListUrl(projectId, id, params), {...options,method: 'GET',})@@ -681,6 +698,42 @@ export const announcementsChannelsList = async (})}+export const getCalendarSyncListUrl = (projectId: string) => {+ return `/api/projects/${projectId}/calendar_sync/`+}++/**+ * Calendar-sync controls for Customer analytics settings. Sync runs on an hourly+ * Temporal schedule; this surface only offers the manual "sync now" escape hatch.+ */+export const calendarSyncList = async (projectId: string, options?: RequestInit): Promise<CalendarSyncStatusApi[]> => {+ return apiMutator<CalendarSyncStatusApi[]>(getCalendarSyncListUrl(projectId), {+ ...options,+ method: 'GET',+ })+}++export const getCalendarSyncSyncNowCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/calendar_sync/sync_now/`+}++/**+ * Start a sync run for one connected Google Calendar immediately, outside the hourly schedule.+ * @summary Sync a connected calendar now+ */+export const calendarSyncSyncNowCreate = async (+ projectId: string,+ calendarSyncTriggerApi: CalendarSyncTriggerApi,+ options?: RequestInit+): Promise<CalendarSyncTriggerResponseApi> => {+ return apiMutator<CalendarSyncTriggerResponseApi>(getCalendarSyncSyncNowCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(calendarSyncTriggerApi),+ })+}+export const getCustomPropertyDefinitionsListUrl = (projectId: string,params?: CustomPropertyDefinitionsListParamsdiff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.tsindex e8fd06e9893f..eef935aa059d 100644--- a/products/customer_analytics/frontend/generated/api.zod.ts+++ b/products/customer_analytics/frontend/generated/api.zod.ts@@ -297,6 +297,16 @@ export const AnnouncementsCreateBody = /* @__PURE__ */ zod.object({),})+/**+ * Start a sync run for one connected Google Calendar immediately, outside the hourly schedule.+ * @summary Sync a connected calendar now+ */+export const CalendarSyncSyncNowCreateBody = /* @__PURE__ */ zod+ .object({+ integration_id: zod.number().describe('Id of the google-calendar integration to sync.'),+ })+ .describe('Request body of the calendar sync-now trigger.')+export const customPropertyDefinitionsCreateBodyNameMax = 400export const customPropertyDefinitionsCreateBodyTargetTypeDefault = `account`diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncConfig.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncConfig.tsxindex 512397558a16..45bceba43962 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncConfig.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncConfig.tsx@@ -1,23 +1,77 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'+import { IconRefresh, IconTrash } from '@posthog/icons'import { LemonButton } from '@posthog/lemon-ui'import api from 'lib/api'+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'+import { TZLabel } from 'lib/components/TZLabel'+import { TeamMembershipLevel } from 'lib/constants'import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { IntegrationView } from 'lib/integrations/IntegrationView'import { ICONS } from 'lib/integrations/utils'import { urls } from 'scenes/urls'+import { calendarSyncLogic } from './calendarSyncLogic'+export function CalendarSyncConfig(): JSX.Element {const { integrations, integrationsLoading } = useValues(integrationsLogic)+ const { deleteIntegration } = useActions(integrationsLogic)+ const { statusByIntegrationId, triggeringIntegrationIds } = useValues(calendarSyncLogic)+ const { syncNow } = useActions(calendarSyncLogic)+ const restrictedReason = useRestrictedArea({+ scope: RestrictionScope.Project,+ minimumAccessLevel: TeamMembershipLevel.Admin,+ })const calendarIntegrations = integrations?.filter((integration) => integration.kind === 'google-calendar') ?? []return (<div className="flex flex-col gap-4">- {calendarIntegrations.map((integration) => (- <IntegrationView key={integration.id} integration={integration} />- ))}+ {calendarIntegrations.map((integration) => {+ const syncStatus = statusByIntegrationId[integration.id]+ const isSyncing = !!syncStatus?.is_syncing || triggeringIntegrationIds.includes(integration.id)+ return (+ <IntegrationView+ key={integration.id}+ integration={integration}+ // A custom suffix replaces IntegrationView's built-in Disconnect button, so it returns here.+ suffix={+ <div className="flex flex-row items-center gap-2">+ <span className="text-xs text-secondary whitespace-nowrap">+ {isSyncing ? (+ 'Syncing...'+ ) : syncStatus?.last_synced_at ? (+ <>+ Last synced <TZLabel time={syncStatus.last_synced_at} />+ </>+ ) : (+ 'Not synced yet'+ )}+ </span>+ <LemonButton+ type="secondary"+ icon={<IconRefresh />}+ loading={isSyncing}+ disabledReason={isSyncing ? 'A sync is already running' : restrictedReason}+ onClick={() => syncNow(integration.id)}+ >+ Sync now+ </LemonButton>+ <LemonButton+ type="secondary"+ status="danger"+ icon={<IconTrash />}+ onClick={() => deleteIntegration(integration.id)}+ disabledReason={restrictedReason}+ >+ Disconnect+ </LemonButton>+ </div>+ }+ />+ )+ })}<div className="flex"><LemonButtontype="primary"diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/calendarSyncLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/calendarSyncLogic.tsnew file mode 100644index 000000000000..1dd3297b194e--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/calendarSyncLogic.ts@@ -0,0 +1,154 @@+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 { teamLogic } from 'scenes/teamLogic'++import { calendarSyncList, calendarSyncSyncNowCreate } from 'products/customer_analytics/frontend/generated/api'+import type { CalendarSyncStatusApi } from 'products/customer_analytics/frontend/generated/api.schemas'++const POLL_INTERVAL_MS = 5000+// start_workflow returns before the run writes its start marker, so keep the local+// "syncing" state alive until the server status takes over or this window expires.+const TRIGGER_HANDOFF_TIMEOUT_MS = 120_000++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface calendarSyncLogicValues {+ currentTeamId: number | null // teamLogic+ statusByIntegrationId: Record<number, CalendarSyncStatusApi>+ statuses: CalendarSyncStatusApi[]+ statusesLoading: boolean+ triggeredAtByIntegrationId: Record<number, number>+ triggeringIntegrationIds: number[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface calendarSyncLogicActions {+ loadStatuses: () => any+ loadStatusesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadStatusesSuccess: (+ statuses: CalendarSyncStatusApi[],+ payload?: any+ ) => {+ statuses: CalendarSyncStatusApi[]+ payload?: any+ }+ syncNow: (integrationId: number) => {+ integrationId: number+ triggeredAt: number+ }+ triggerFinished: (integrationId: number) => {+ integrationId: number+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface calendarSyncLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ statusByIntegrationId: (statuses: CalendarSyncStatusApi[]) => Record<number, CalendarSyncStatusApi>+ triggeringIntegrationIds: (triggeredAtByIntegrationId: Record<number, number>) => number[]+ }+}++export type calendarSyncLogicType = MakeLogicType<+ calendarSyncLogicValues,+ calendarSyncLogicActions,+ Record<string, any>,+ calendarSyncLogicMeta+>++export const calendarSyncLogic = kea<calendarSyncLogicType>([+ path(['scenes', 'customerAnalytics', 'configuration', 'calendarSyncLogic']),+ connect(() => ({+ values: [teamLogic, ['currentTeamId']],+ })),+ actions({+ syncNow: (integrationId: number) => ({ integrationId, triggeredAt: Date.now() }),+ triggerFinished: (integrationId: number) => ({ integrationId }),+ }),+ loaders(({ values }) => ({+ statuses: [+ [] as CalendarSyncStatusApi[],+ {+ loadStatuses: async (): Promise<CalendarSyncStatusApi[]> => {+ try {+ return [...(await calendarSyncList(String(values.currentTeamId)))]+ } catch (error) {+ posthog.captureException(error as Error, { scope: 'calendarSyncLogic.loadStatuses' })+ return values.statuses+ }+ },+ },+ ],+ })),+ reducers({+ triggeredAtByIntegrationId: [+ {} as Record<number, number>,+ {+ syncNow: (state, { integrationId, triggeredAt }) => ({ ...state, [integrationId]: triggeredAt }),+ triggerFinished: (state, { integrationId }) =>+ Object.fromEntries(Object.entries(state).filter(([id]) => Number(id) !== integrationId)),+ },+ ],+ }),+ selectors({+ statusByIntegrationId: [+ (s) => [s.statuses],+ (statuses: CalendarSyncStatusApi[]): Record<number, CalendarSyncStatusApi> =>+ Object.fromEntries(statuses.map((status) => [status.integration_id, status])),+ ],+ triggeringIntegrationIds: [+ (s) => [s.triggeredAtByIntegrationId],+ (triggeredAtByIntegrationId: Record<number, number>): number[] =>+ Object.keys(triggeredAtByIntegrationId).map(Number),+ ],+ }),+ listeners(({ actions, values }) => ({+ // A sync in flight (or a trigger awaiting its server-side start marker) self-perpetuates+ // the status poll; the breakpoint cancels it on unmount.+ loadStatusesSuccess: async (_, breakpoint) => {+ for (const [id, triggeredAt] of Object.entries(values.triggeredAtByIntegrationId)) {+ const integrationId = Number(id)+ if (+ values.statusByIntegrationId[integrationId]?.is_syncing ||+ Date.now() - triggeredAt > TRIGGER_HANDOFF_TIMEOUT_MS+ ) {+ actions.triggerFinished(integrationId)+ }+ }+ if (values.statuses.some((status) => status.is_syncing) || values.triggeringIntegrationIds.length > 0) {+ await breakpoint(POLL_INTERVAL_MS)+ actions.loadStatuses()+ }+ },+ syncNow: async ({ integrationId }) => {+ try {+ const result = await calendarSyncSyncNowCreate(String(values.currentTeamId), {+ integration_id: integrationId,+ })+ if (result.status === 'already_running') {+ lemonToast.info('A sync for this calendar is already running')+ actions.triggerFinished(integrationId)+ } else {+ lemonToast.success('Calendar sync started. New meetings appear in a few minutes.')+ }+ } catch (error) {+ posthog.captureException(error as Error, { scope: 'calendarSyncLogic.syncNow' })+ lemonToast.error('Failed to start the calendar sync')+ actions.triggerFinished(integrationId)+ } finally {+ actions.loadStatuses()+ }+ },+ })),+ afterMount(({ actions }) => {+ actions.loadStatuses()+ }),+])diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yamlindex b6de0858ad70..d55b4c375232 100644--- a/products/customer_analytics/mcp/tools.yaml+++ b/products/customer_analytics/mcp/tools.yaml@@ -119,7 +119,9 @@ tools:properties:description: >Typed account properties. `stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`,- `zendesk_id` are optional string identifiers for the account in external systems. All fields are+ `zendesk_id` are optional string identifiers for the account in external systems. `email_domains`+ (company email domains, e.g. ["acme.com"]) and `known_emails` (individual addresses, for contacts on+ personal domains) match synced touchpoints such as calendar meetings to this account. All fields areoptional.tags:description: >@@ -288,8 +290,10 @@ tools:description: >Typed account properties. The server replaces the `properties` object as a whole, so include anyexisting values you want to preserve. Supported keys: `stripe_customer_id`, `hubspot_deal_id`,- `billing_id`, `sfdc_id`, `zendesk_id` (optional string identifiers for external systems). To assign- users (CSM, account executive, ...), use `accounts-relationships-create` instead.+ `billing_id`, `sfdc_id`, `zendesk_id` (optional string identifiers for external systems), plus+ `email_domains` (company email domains, e.g. ["acme.com"]) and `known_emails` (individual addresses,+ for contacts on personal domains) which match synced touchpoints such as calendar meetings to this+ account. To assign users (CSM, account executive, ...), use `accounts-relationships-create` instead.tags:description: >Tag names to set on the account. Replaces the full existing tag set — pass the complete list, not a@@ -476,6 +480,12 @@ tools:when it failed, and `slack_message_ts` plus `sent_at` when it succeeded. Use this to check delivery progressafter `announcements-create`.feature_flag: customer-analytics-csp+ calendar-sync-list:+ operation: calendar_sync_list+ enabled: false+ calendar-sync-sync-now-create:+ operation: calendar_sync_sync_now_create+ enabled: falsecustom-property-definitions-create:operation: custom_property_definitions_createenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 0f1545fd02e0..897eb96fd7e0 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -13475,6 +13475,52 @@ export namespace Schemas {version?: number | null;}+ /**+ * Sync state of one connected calendar (read-only).+ */+ export interface CalendarSyncStatus {+ /** Id of the google-calendar integration. */+ readonly integration_id: number;+ /**+ * When the last sync run completed; null before the first sync.+ * @nullable+ */+ readonly last_synced_at: string | null;+ /** Whether a sync run is currently in flight. */+ readonly is_syncing: boolean;+ }++ /**+ * Request body of the calendar sync-now trigger.+ */+ export interface CalendarSyncTrigger {+ /** Id of the google-calendar integration to sync. */+ integration_id: number;+ }++ /**+ * * `started` - started+ * * `already_running` - already_running+ */+ export type CalendarSyncTriggerResponseStatusEnum = typeof CalendarSyncTriggerResponseStatusEnum[keyof typeof CalendarSyncTriggerResponseStatusEnum];+++ export const CalendarSyncTriggerResponseStatusEnum = {+ Started: 'started',+ AlreadyRunning: 'already_running',+ } as const;++ /**+ * Response of the calendar sync-now trigger.+ */+ export interface CalendarSyncTriggerResponse {+ /** 'started' (a sync run began) or 'already_running' (a sync for this calendar was already in flight, so this was a no-op).+ *+ * * `started` - started+ * * `already_running` - already_running */+ status: CalendarSyncTriggerResponseStatusEnum;+ }+/*** * `needs_approval` - needs_approval* * `disabled` - disabled@@ -43807,6 +43853,11 @@ export namespace Schemas {readonly response_status: string;/** Whether this attendee organized the meeting. */readonly is_organizer: boolean;+ /**+ * UUID of the PostHog person resolved for this attendee, if any.+ * @nullable+ */+ readonly person_id: string | null;}/**@@ -46973,6 +47024,15 @@ export namespace Schemas {results: MaxCoreMemory[];}+ export interface PaginatedMeetingList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: Meeting[];+ }+export interface PaginatedMessageCategoryList {count: number;/** @nullable */@@ -79233,6 +79293,21 @@ export namespace Schemas {include_history?: boolean;};+ export type AccountsMeetingsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ /**+ * Filter meetings by title or attendee email/name.+ */+ search?: string;+ };+export type AccountsSummariesListParams = {/*** Number of results to return per page.diff --git a/services/mcp/src/tools/generated/customer_analytics.ts b/services/mcp/src/tools/generated/customer_analytics.tsindex c2c96537d196..a0fce73c4947 100644--- a/services/mcp/src/tools/generated/customer_analytics.ts+++ b/services/mcp/src/tools/generated/customer_analytics.ts@@ -202,7 +202,7 @@ const accountRelationshipDefinitionsRetrieve = (): ToolBase<const AccountsCreateSchema = AccountsCreateBody.extend({properties: AccountsCreateBody.shape['properties'].describe(- 'Typed account properties. `stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id` are optional string identifiers for the account in external systems. All fields are optional.'+ 'Typed account properties. `stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id` are optional string identifiers for the account in external systems. `email_domains` (company email domains, e.g. ["acme.com"]) and `known_emails` (individual addresses, for contacts on personal domains) match synced touchpoints such as calendar meetings to this account. All fields are optional.'),tags: AccountsCreateBody.shape['tags'].describe('Tag names to attach to the account. Tags are created on demand if they do not already exist for the team.'@@ -415,7 +415,7 @@ const AccountsPartialUpdateSchema = AccountsPartialUpdateParams.omit({ project_i.extend(AccountsPartialUpdateBody.shape).extend({properties: AccountsPartialUpdateBody.shape['properties'].describe(- 'Typed account properties. The server replaces the `properties` object as a whole, so include any existing values you want to preserve. Supported keys: `stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id` (optional string identifiers for external systems). To assign users (CSM, account executive, ...), use `accounts-relationships-create` instead.'+ 'Typed account properties. The server replaces the `properties` object as a whole, so include any existing values you want to preserve. Supported keys: `stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id` (optional string identifiers for external systems), plus `email_domains` (company email domains, e.g. ["acme.com"]) and `known_emails` (individual addresses, for contacts on personal domains) which match synced touchpoints such as calendar meetings to this account. To assign users (CSM, account executive, ...), use `accounts-relationships-create` instead.'),tags: AccountsPartialUpdateBody.shape['tags'].describe('Tag names to set on the account. Replaces the full existing tag set — pass the complete list, not a delta. Tags are created on demand if they do not already exist for the team.'