: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): google calendar sync engine on temporal (#78502)
Arthur Moreira de Deus77d17eb79db5
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex 48305c82953d..0fe558ed8b3f 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -180,6 +180,10 @@ from products.conversations.backend.temporal import (ACTIVITIES as CONVERSATIONS_ACTIVITIES,WORKFLOWS as CONVERSATIONS_WORKFLOWS,)+from products.customer_analytics.backend.facade.temporal import (+ ACTIVITIES as CUSTOMER_ANALYTICS_ACTIVITIES,+ WORKFLOWS as CUSTOMER_ANALYTICS_WORKFLOWS,+)from products.engineering_analytics.backend.facade.temporal import (CI_SIGNALS_ACTIVITIES,CI_SIGNALS_WORKFLOWS,@@ -409,11 +413,13 @@ _task_queue_specs = [+ DATA_IMPORT_EMIT_SIGNALS_WORKFLOWS+ BUSINESS_KNOWLEDGE_WORKFLOWS+ CONVERSATIONS_WORKFLOWS+ + CUSTOMER_ANALYTICS_WORKFLOWS+ REVIEW_HOG_WORKFLOWS,SIGNALS_PRODUCT_ACTIVITIES+ DATA_IMPORT_EMIT_SIGNALS_ACTIVITIES+ BUSINESS_KNOWLEDGE_ACTIVITIES+ CONVERSATIONS_ACTIVITIES+ + CUSTOMER_ANALYTICS_ACTIVITIES+ REVIEW_HOG_ACTIVITIES,),(diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex 6a4d245ceaf7..274e22c03250 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -83,6 +83,7 @@ from posthog.temporal.weekly_digest.types import WeeklyDigestInputfrom products.business_knowledge.backend.temporal.schedule import create_business_knowledge_refresh_coordinator_schedulefrom products.conversations.backend.temporal.channel_summary.schedule import create_channel_summary_coordinator_schedulefrom products.conversations.backend.temporal.schedule import create_support_reply_coordinator_schedule+from products.customer_analytics.backend.facade.temporal import create_calendar_sync_coordinator_schedulefrom products.engineering_analytics.backend.facade.temporal import (create_ci_signals_coordinator_schedule,create_github_job_logs_coordinator_schedule,@@ -873,6 +874,7 @@ schedules = [create_signals_scout_coordinator_schedule,create_support_reply_coordinator_schedule,create_channel_summary_coordinator_schedule,+ create_calendar_sync_coordinator_schedule,create_replay_vision_reconciler_schedule,create_replay_vision_estimates_schedule,create_github_job_logs_coordinator_schedule,diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 4bf2db1291d7..4397a469df97 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -90,6 +90,7 @@ from products.customer_analytics.backend.models import (DisplayType,EventStream,EventStreamMember,+ Meeting,SyncStatus,SyncTrigger,TargetType,@@ -2555,6 +2556,45 @@ def get_account_support_tickets(return list_account_tickets(team_id, account.external_id, limit=limit)+def get_account_meetings(+ team_id: int,+ account_id: str,+ user_access_control: "UserAccessControl",+ *,+ limit: int = 100,+) -> list[contracts.MeetingView] | None:+ """Synced calendar meetings for an accessible account, newest first. 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 [+ contracts.MeetingView(+ id=meeting.id,+ title=meeting.title,+ start_time=meeting.start_time,+ end_time=meeting.end_time,+ organizer_email=meeting.organizer_email,+ status=meeting.status,+ participants=[+ contracts.MeetingParticipantView(+ email=participant.email,+ display_name=participant.display_name,+ response_status=participant.response_status,+ is_organizer=participant.is_organizer,+ )+ for participant in meeting.participants.all()+ ],+ )+ for meeting in meetings+ ]++def list_account_notebooks(team_id: int,account_id: str,diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex 910c9855848e..b4388e5bb45f 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -133,6 +133,29 @@ class AccountChannelSummaryView:generated_at: datetime+@dataclass(frozen=True)+class MeetingParticipantView:+ """One attendee of a synced calendar meeting."""++ email: str+ display_name: str+ response_status: str+ is_organizer: bool+++@dataclass(frozen=True)+class MeetingView:+ """A synced calendar meeting as returned by the account meetings endpoint."""++ id: UUID+ title: str+ start_time: datetime+ end_time: datetime | None+ organizer_email: str+ status: str+ participants: list[MeetingParticipantView]++@dataclass(frozen=True)class AccountRef:"""Lightweight account reference for search/list result rows.diff --git a/products/customer_analytics/backend/facade/temporal.py b/products/customer_analytics/backend/facade/temporal.pynew file mode 100644index 000000000000..13725d373761--- /dev/null+++ b/products/customer_analytics/backend/facade/temporal.py@@ -0,0 +1,7 @@+"""Temporal wiring re-exports — the only path core may use to register this+product's workflows, activities, and schedules."""++from products.customer_analytics.backend.temporal import ACTIVITIES, WORKFLOWS+from products.customer_analytics.backend.temporal.calendar_sync import create_calendar_sync_coordinator_schedule++__all__ = ["ACTIVITIES", "WORKFLOWS", "create_calendar_sync_coordinator_schedule"]diff --git a/products/customer_analytics/backend/logic/calendar_sync.py b/products/customer_analytics/backend/logic/calendar_sync.pynew file mode 100644index 000000000000..56643cdb31d0--- /dev/null+++ b/products/customer_analytics/backend/logic/calendar_sync.py@@ -0,0 +1,388 @@+from dataclasses import dataclass, field+from datetime import datetime, timedelta+from email.utils import parseaddr+from typing import Any++from django.utils import timezone++import requests+import structlog++from posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, Integration, OauthIntegration+from posthog.models.person.person import Person+from posthog.models.person.util import get_persons_by_uuids+from posthog.models.team import Team+from posthog.personhog_client.caller_tag import personhog_caller_tag++from products.customer_analytics.backend.models import Account, Meeting, MeetingParticipant, MeetingStatus++logger = structlog.get_logger(__name__)++EVENTS_URL = "https://www.googleapis.com/calendar/v3/calendars/primary/events"+BACKFILL_DAYS = 365+PAGE_SIZE = 250+SYNC_TOKEN_CONFIG_KEY = "calendar_sync_token"++PERSON_EMAIL_LOOKUP_QUERY = """+SELECT id, properties.email+FROM persons+WHERE lower(properties.email) IN {emails}+ORDER BY is_identified DESC, created_at ASC, id ASC+"""++GROUP_KEY_BY_DISTINCT_ID_QUERY = """+SELECT distinct_id, argMaxIf({group_col}, timestamp, {group_col} != '') AS group_key+FROM events+WHERE distinct_id IN {distinct_ids} AND timestamp > now() - INTERVAL 90 DAY+GROUP BY distinct_id+"""+++class SyncTokenExpired(Exception):+ pass+++class CalendarSyncError(Exception):+ pass+++@dataclass+class CalendarSyncCounts:+ fetched: int = 0+ upserted: int = 0+ cancelled: int = 0+ skipped: int = 0+ matched: int = 0+ unmatched_emails: set[str] = field(default_factory=set)+++def sync_calendar_integration(integration_id: int, team_id: int) -> CalendarSyncCounts:+ """Sync one connected Google Calendar into customer_analytics meetings.++ First run pulls BACKFILL_DAYS of history plus all future events; later runs are+ incremental via the stored syncToken. A stale token (HTTP 410) drops the cursor+ and re-lists the whole window in the same run.+ """+ integration = Integration.objects.get(id=integration_id, team_id=team_id, kind="google-calendar")+ team = integration.team+ access_token = _get_fresh_access_token(integration)+ connected_email = (integration.config or {}).get("email", "")+ internal_domain = _domain_of(connected_email)++ counts = CalendarSyncCounts()+ sync_token = (integration.config or {}).get(SYNC_TOKEN_CONFIG_KEY)+ try:+ next_sync_token = _sync_events(team, access_token, sync_token, internal_domain, counts)+ except SyncTokenExpired:+ next_sync_token = _sync_events(team, access_token, None, internal_domain, counts)++ integration.config[SYNC_TOKEN_CONFIG_KEY] = next_sync_token+ integration.save(update_fields=["config"])+ return counts+++def _sync_events(+ team: Team, access_token: str, sync_token: str | None, internal_domain: str, counts: CalendarSyncCounts+) -> str:+ params: dict[str, Any] = {"singleEvents": "true", "showDeleted": "true", "maxResults": PAGE_SIZE}+ if sync_token:+ params["syncToken"] = sync_token+ else:+ params["timeMin"] = (timezone.now() - timedelta(days=BACKFILL_DAYS)).isoformat()++ next_sync_token = ""+ page_token: str | None = None+ while True:+ page_params = {**params, **({"pageToken": page_token} if page_token else {})}+ response = requests.get(+ EVENTS_URL, params=page_params, headers={"Authorization": f"Bearer {access_token}"}, timeout=30+ )+ if response.status_code == 410:+ raise SyncTokenExpired+ if response.status_code != 200:+ raise CalendarSyncError(f"Google Calendar API returned {response.status_code}: {response.text[:200]}")++ payload = response.json()+ events = payload.get("items", [])+ counts.fetched += len(events)+ _process_events(team, events, internal_domain, counts)++ page_token = payload.get("nextPageToken")+ if not page_token:+ next_sync_token = payload.get("nextSyncToken", "")+ break+ return next_sync_token+++def _process_events(team: Team, events: list[dict], internal_domain: str, counts: CalendarSyncCounts) -> None:+ to_upsert: list[dict] = []+ for event in events:+ if event.get("status") == "cancelled":+ _mark_cancelled(team, event, counts)+ continue+ parsed = (+ None if event.get("visibility") in ("private", "confidential") else _parse_event(event, internal_domain)+ )+ if parsed is None:+ # A stored event that stopped passing the filters (made private, external+ # attendee removed) must disappear, not linger with stale data.+ _delete_filtered_out(team, event)+ counts.skipped += 1+ continue+ to_upsert.append(parsed)++ if not to_upsert:+ return++ external_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))++ for parsed in to_upsert:+ account = next(+ (accounts_by_email[p["email"]] for p in parsed["participants"] if p["email"] in accounts_by_email),+ None,+ )+ if account is not None:+ counts.matched += 1+ else:+ counts.unmatched_emails.update(p["email"] for p in parsed["participants"] if not p["is_internal"])+ _upsert_meeting(team, parsed, account)+ counts.upserted += 1+++def _parse_event(event: dict, internal_domain: str) -> dict | None:+ ical_uid = event.get("iCalUID")+ start = _parse_when(event.get("start"))+ if not ical_uid or start is None:+ return None++ attendees = event.get("attendees") or []+ organizer_email = ((event.get("organizer") or {}).get("email") or "").lower()+ participants = []+ seen_emails = set()+ for attendee in attendees:+ email = (attendee.get("email") or "").lower()+ if not email or "@" not in email or attendee.get("resource") or email in seen_emails:+ continue+ # Rooms and shared calendars are invitees too, but they aren't people.+ if email.endswith("group.calendar.google.com") or email.endswith("resource.calendar.google.com"):+ continue+ seen_emails.add(email)+ participants.append(+ {+ "email": email,+ "display_name": attendee.get("displayName") or "",+ "response_status": _response_status(attendee.get("responseStatus")),+ "is_organizer": email == organizer_email,+ "is_internal": _domain_of(email) == internal_domain,+ }+ )++ # A meeting with no external attendee is internal business, not a customer touchpoint.+ if not any(not p["is_internal"] for p in participants):+ return None++ return {+ "ical_uid": ical_uid,+ "recurrence_instance_id": _recurrence_instance_id(event),+ "title": event.get("summary") or "",+ "description": event.get("description") or "",+ "start_time": start,+ "end_time": _parse_when(event.get("end")),+ "organizer_email": organizer_email,+ "meet_code": (event.get("conferenceData") or {}).get("conferenceId") or "",+ "status": event.get("status") if event.get("status") in MeetingStatus.values else MeetingStatus.CONFIRMED,+ "participants": participants,+ }+++def _upsert_meeting(team: Team, parsed: dict, account: Account | None) -> None:+ defaults = {+ "title": parsed["title"],+ "description": parsed["description"],+ "start_time": parsed["start_time"],+ "end_time": parsed["end_time"],+ "organizer_email": parsed["organizer_email"],+ "meet_code": parsed["meet_code"],+ "status": parsed["status"],+ }+ if account is not None:+ defaults["account"] = account++ meeting, _created = Meeting.objects.for_team(team.id).update_or_create(+ team_id=team.id,+ ical_uid=parsed["ical_uid"],+ recurrence_instance_id=parsed["recurrence_instance_id"],+ defaults=defaults,+ )+ for participant in parsed["participants"]:+ MeetingParticipant.objects.for_team(team.id).update_or_create(+ team_id=team.id,+ meeting=meeting,+ email=participant["email"],+ defaults={+ "display_name": participant["display_name"],+ "response_status": participant["response_status"],+ "is_organizer": participant["is_organizer"],+ },+ )+++def _delete_filtered_out(team: Team, event: dict) -> None:+ ical_uid = event.get("iCalUID")+ if not ical_uid:+ return+ Meeting.objects.for_team(team.id).filter(+ ical_uid=ical_uid, recurrence_instance_id=_recurrence_instance_id(event)+ ).delete()+++def _mark_cancelled(team: Team, event: dict, counts: CalendarSyncCounts) -> None:+ ical_uid = event.get("iCalUID")+ if not ical_uid:+ return+ updated = (+ Meeting.objects.for_team(team.id)+ .filter(ical_uid=ical_uid, recurrence_instance_id=_recurrence_instance_id(event))+ .update(status=MeetingStatus.CANCELLED)+ )+ counts.cancelled += updated+++def _match_accounts_for_emails(team: Team, emails: list[str]) -> dict[str, Account]:+ """Resolve attendee emails to accounts: pinned known_emails first, then person+ group links, then the email_domains fallback."""+ if not emails:+ return {}++ matched: dict[str, Account] = {}++ for email in emails:+ candidates = list(Account.objects.for_team(team.id).filter(_properties__known_emails__contains=[email])[:2])+ if len(candidates) == 1:+ matched[email] = candidates[0]+ elif len(candidates) > 1:+ logger.warning("calendar_sync_ambiguous_known_email", team_id=team.id, email=email)++ group_type_index = team.customer_analytics_config.account_group_type_index+ if group_type_index is not None:+ unresolved = [email for email in emails if email not in matched]+ email_to_group_key = _group_keys_via_persons(team, unresolved, group_type_index) if unresolved else {}+ if email_to_group_key:+ accounts = {+ account.external_id: account+ for account in Account.objects.for_team(team.id).filter(+ external_id__in=set(email_to_group_key.values())+ )+ }+ for email, group_key in email_to_group_key.items():+ if group_key in accounts:+ matched[email] = accounts[group_key]++ for email in emails:+ if email in matched:+ continue+ domain = _domain_of(email)+ if not domain:+ continue+ candidates = list(Account.objects.for_team(team.id).filter(_properties__email_domains__contains=[domain])[:2])+ if len(candidates) == 1:+ matched[email] = candidates[0]+ elif len(candidates) > 1:+ logger.warning("calendar_sync_ambiguous_email_domain", team_id=team.id, domain=domain)++ return matched+++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++ with tags_context(product=Product.CUSTOMER_ANALYTICS, feature=Feature.QUERY):+ response = execute_hogql_query(+ PERSON_EMAIL_LOOKUP_QUERY,+ placeholders={"emails": ast.Constant(value=emails)},+ team=team,+ query_type="customer_analytics_calendar_person_lookup",+ )+ email_to_uuid: dict[str, str] = {}+ for person_uuid, prop_email in response.results or []:+ lower = (prop_email or "").lower()+ if lower and lower not in email_to_uuid:+ email_to_uuid[lower] = str(person_uuid)+ if not email_to_uuid:+ return {}++ with personhog_caller_tag("customer_analytics/calendar-person-lookup"):+ persons = get_persons_by_uuids(team.pk, list(email_to_uuid.values()))+ persons_by_uuid: dict[str, Person] = {str(p.uuid): p for p in persons}++ distinct_id_to_email: dict[str, str] = {}+ for email, person_uuid in email_to_uuid.items():+ person = persons_by_uuid.get(person_uuid)+ for distinct_id in (person.distinct_ids or []) if person else []:+ distinct_id_to_email[distinct_id] = email+ if not distinct_id_to_email:+ return {}++ query = GROUP_KEY_BY_DISTINCT_ID_QUERY.format(group_col=f"`$group_{group_type_index}`")+ with tags_context(product=Product.CUSTOMER_ANALYTICS, feature=Feature.QUERY):+ response = execute_hogql_query(+ query,+ placeholders={"distinct_ids": ast.Constant(value=sorted(distinct_id_to_email))},+ team=team,+ query_type="customer_analytics_calendar_group_lookup",+ )++ email_to_group_key: dict[str, str] = {}+ for distinct_id, group_key in response.results or []:+ matched_email = distinct_id_to_email.get(distinct_id)+ if matched_email and group_key and matched_email not in email_to_group_key:+ email_to_group_key[matched_email] = group_key+ return email_to_group_key+++def _get_fresh_access_token(integration: Integration) -> str:+ oauth = OauthIntegration(integration)+ if integration.errors != ERROR_TOKEN_REFRESH_FAILED and oauth.access_token_expired():+ oauth.refresh_access_token()+ if integration.errors == ERROR_TOKEN_REFRESH_FAILED:+ raise CalendarSyncError(f"Token refresh failed for integration {integration.id}; reconnect the calendar")+ token = integration.access_token+ if not token:+ raise CalendarSyncError(f"Integration {integration.id} has no access token")+ return token+++def _parse_when(when: dict | None) -> datetime | None:+ if not when:+ return None+ raw = when.get("dateTime") or when.get("date")+ if not raw:+ return None+ try:+ parsed = datetime.fromisoformat(raw)+ except ValueError:+ return None+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=timezone.get_default_timezone())+ return parsed+++def _recurrence_instance_id(event: dict) -> str:+ if not event.get("recurringEventId"):+ return ""+ original = event.get("originalStartTime") or {}+ return (original.get("dateTime") or original.get("date") or "")[:64]+++def _response_status(raw: str | None) -> str:+ mapping = {"needsAction": "needs_action", "accepted": "accepted", "declined": "declined", "tentative": "tentative"}+ return mapping.get(raw or "", "needs_action")+++def _domain_of(email: str) -> str:+ _, address = parseaddr(email or "")+ return address.rsplit("@", 1)[-1].lower() if "@" in address else ""diff --git a/products/customer_analytics/backend/models/account.py b/products/customer_analytics/backend/models/account.pyindex 2b726402e8c8..f2b09f45a2f5 100644--- a/products/customer_analytics/backend/models/account.py+++ b/products/customer_analytics/backend/models/account.py@@ -24,6 +24,9 @@ class AccountProperties(BaseModel):# touchpoints (calendar attendees, email senders) that don't resolve to a# known person. Personal/free domains don't belong here.email_domains: list[str] = []+ # Individual addresses pinned to this account, checked before the domain+ # fallback. For contacts on personal/free domains a domain rule can't cover.+ known_emails: list[str] = []# External connectionsstripe_customer_id: str | None = Nonediff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex 4ffab178fdd1..30b07f5cba2f 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -49,6 +49,8 @@ from products.customer_analytics.backend.facade.contracts import (CustomPropertySourceView,CustomPropertySyncRunView,EventStreamView,+ MeetingParticipantView,+ MeetingView,)# Scope (value, label) pairs, kept in sync with ``CustomerProfileConfig.Scope``. Declared@@ -72,6 +74,11 @@ _ACCOUNT_PROPERTIES_SCHEMA = {"items": {"type": "string"},"description": "Email domains owned by this account's company, used to match inbound touchpoints to the account.",},+ "known_emails": {+ "type": "array",+ "items": {"type": "string"},+ "description": "Individual email addresses pinned to this account, matched before the domain fallback.",+ },"stripe_customer_id": {"type": "string", "nullable": True},"hubspot_deal_id": {"type": "string", "nullable": True},"billing_id": {"type": "string", "nullable": True},@@ -166,9 +173,10 @@ class AccountSerializer(DataclassSerializer):help_text=("Typed account properties: external system identifiers (stripe_customer_id, ""hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, "- "usage_dashboard_link, metabase_link) and email_domains (the company's email "- "domains, used to match inbound touchpoints). Defaults to an empty object. Unknown "- "keys are rejected. User assignments live on account relationships, not here."+ "usage_dashboard_link, metabase_link) plus touchpoint matching lists: email_domains "+ "(the company's email domains) and known_emails (individual addresses pinned to the "+ "account). Defaults to an empty object. Unknown keys are rejected. User assignments "+ "live on account relationships, not here."),)tags = serializers.ListField(@@ -370,6 +378,46 @@ class SupportTicketSerializer(DataclassSerializer):fields = ["id", "ticket_number", "status", "last_message_at", "last_message_text", "deep_link"]+class MeetingParticipantSerializer(DataclassSerializer):+ """One attendee of a synced calendar meeting (read-only)."""++ email = serializers.CharField(read_only=True, help_text="Email address of the attendee.")+ display_name = serializers.CharField(+ read_only=True, allow_blank=True, help_text="Display name from the calendar event; may be empty."+ )+ response_status = serializers.CharField(+ read_only=True,+ 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.")++ class Meta:+ dataclass = MeetingParticipantView+ ref_name = "MeetingParticipant"+ fields = ["email", "display_name", "response_status", "is_organizer"]+++class MeetingSerializer(DataclassSerializer):+ """A calendar meeting synced from a connected employee calendar (read-only)."""++ id = serializers.UUIDField(read_only=True, help_text="UUID of the meeting.")+ title = serializers.CharField(read_only=True, allow_blank=True, help_text="Meeting title; may be empty.")+ start_time = serializers.DateTimeField(read_only=True, help_text="When the meeting starts.")+ end_time = serializers.DateTimeField(read_only=True, allow_null=True, help_text="When the meeting ends.")+ organizer_email = serializers.CharField(+ read_only=True, allow_blank=True, help_text="Email address of the meeting organizer; may be empty."+ )+ status = serializers.CharField(+ read_only=True, help_text="Meeting status: 'confirmed', 'tentative', or 'cancelled'."+ )+ participants = MeetingParticipantSerializer(many=True, read_only=True, help_text="Attendees of the meeting.")++ class Meta:+ dataclass = MeetingView+ ref_name = "Meeting"+ fields = ["id", "title", "start_time", "end_time", "organizer_email", "status", "participants"]++class CustomPropertyReferenceSerializer(DataclassSerializer):"""A place that uses a custom property definition (read-only)."""diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex d4f45e83dacf..929e0de96c22 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -60,6 +60,7 @@ from products.customer_analytics.backend.presentation.views.serializers import (EventStreamMemberWriteSerializer,EventStreamSerializer,EventStreamTestMessageSerializer,+ MeetingSerializer,SupportTicketSerializer,)@@ -963,6 +964,18 @@ 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)+ 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:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)+ return Response(MeetingSerializer(instance=meetings, many=True).data)+def dangerously_get_required_scopes(self, request: Request, view) -> builtins.list[str] | None:super_method = getattr(super(), "dangerously_get_required_scopes", None)if callable(super_method):diff --git a/products/customer_analytics/backend/temporal/__init__.py b/products/customer_analytics/backend/temporal/__init__.pynew file mode 100644index 000000000000..24afeb02c8af--- /dev/null+++ b/products/customer_analytics/backend/temporal/__init__.py@@ -0,0 +1,9 @@+from products.customer_analytics.backend.temporal.calendar_sync import (+ CalendarSyncCoordinatorWorkflow,+ CalendarSyncWorkflow,+ calendar_sync_collect_integrations_activity,+ calendar_sync_integration_activity,+)++WORKFLOWS = [CalendarSyncCoordinatorWorkflow, CalendarSyncWorkflow]+ACTIVITIES = [calendar_sync_collect_integrations_activity, calendar_sync_integration_activity]diff --git a/products/customer_analytics/backend/temporal/calendar_sync.py b/products/customer_analytics/backend/temporal/calendar_sync.pynew file mode 100644index 000000000000..8337b5f19a25--- /dev/null+++ b/products/customer_analytics/backend/temporal/calendar_sync.py@@ -0,0 +1,203 @@+from __future__ import annotations++import json+from dataclasses import dataclass, field++from temporalio import activity, workflow+from temporalio.client import (+ Client,+ Schedule,+ ScheduleActionStartWorkflow,+ ScheduleIntervalSpec,+ ScheduleOverlapPolicy,+ SchedulePolicy,+ ScheduleSpec,+)+from temporalio.common import RetryPolicy, WorkflowIDReusePolicy+from temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedError++with workflow.unsafe.imports_passed_through():+ from datetime import timedelta++ from django.conf import settings++ import structlog++ from posthog.sync import database_sync_to_async+ from posthog.temporal.common.heartbeat import Heartbeater+ from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule++logger = structlog.get_logger(__name__)++CALENDAR_SYNC_COORDINATOR_SCHEDULE_ID = "customer-analytics-calendar-sync-coordinator-schedule"+CALENDAR_SYNC_COORDINATOR_WORKFLOW_NAME = "customer-analytics-calendar-sync-coordinator"+COORDINATOR_INTERVAL_MINUTES = 60+MAX_SYNCS_PER_RUN = 200+++@dataclass+class CalendarSyncCoordinatorInput:+ pass+++@dataclass+class CalendarSyncInput:+ integration_id: int = 0+ team_id: int = 0+++@dataclass+class CollectCalendarIntegrationsOutput:+ integrations: list[CalendarSyncInput] = field(default_factory=list)+++@dataclass+class CalendarSyncOutput:+ fetched: int = 0+ upserted: int = 0+ cancelled: int = 0+ skipped: int = 0+ matched: int = 0+ unmatched: int = 0+++@dataclass+class CalendarSyncCoordinatorOutput:+ due_count: int = 0+ started_count: int = 0+ skipped_count: int = 0+++def _collect_calendar_integrations() -> list[CalendarSyncInput]:+ # Deferred: keeps Django models out of the workflow sandbox import path.+ from posthog.models.integration import Integration # noqa: PLC0415++ rows = Integration.objects.filter(kind="google-calendar").values_list("id", "team_id")[:MAX_SYNCS_PER_RUN]+ return [CalendarSyncInput(integration_id=row[0], team_id=row[1]) for row in rows]+++async def calendar_sync_collect_integrations_activity(+ _input: CalendarSyncCoordinatorInput,+) -> CollectCalendarIntegrationsOutput:+ """List connected Google Calendars across teams; connecting is the opt-in."""+ async with Heartbeater():+ integrations = await database_sync_to_async(_collect_calendar_integrations, thread_sensitive=False)()+ logger.info("calendar_sync coordinator: connected calendars", count=len(integrations))+ return CollectCalendarIntegrationsOutput(integrations=integrations)+++def _run_calendar_sync(input: CalendarSyncInput) -> CalendarSyncOutput:+ # Deferred: the sync logic pulls requests/HogQL layers that don't belong in the sandbox.+ from products.customer_analytics.backend.logic.calendar_sync import ( # noqa: PLC0415+ CalendarSyncError,+ sync_calendar_integration,+ )++ try:+ counts = sync_calendar_integration(input.integration_id, input.team_id)+ except CalendarSyncError as e:+ # A dead refresh token can't heal by retrying; the user must reconnect.+ raise ApplicationError(str(e), non_retryable="refresh failed" in str(e).lower()) from e+ return CalendarSyncOutput(+ fetched=counts.fetched,+ upserted=counts.upserted,+ cancelled=counts.cancelled,+ skipped=counts.skipped,+ matched=counts.matched,+ unmatched=len(counts.unmatched_emails),+ )+++async def calendar_sync_integration_activity(input: CalendarSyncInput) -> CalendarSyncOutput:+ """Sync one connected calendar: backfill or incremental, filter, upsert, match."""+ async with Heartbeater():+ return await database_sync_to_async(_run_calendar_sync, thread_sensitive=False)(input)++[email protected](name="customer-analytics-calendar-sync")+class CalendarSyncWorkflow:+ """Single-activity sync of one calendar. Event payloads never cross the activity+ boundary; only counters return."""++ @staticmethod+ def parse_inputs(inputs: list[str]) -> CalendarSyncInput:+ return CalendarSyncInput(**json.loads(inputs[0]))++ @workflow.run+ async def run(self, input: CalendarSyncInput) -> CalendarSyncOutput:+ return await workflow.execute_activity(+ calendar_sync_integration_activity,+ input,+ start_to_close_timeout=timedelta(minutes=30),+ heartbeat_timeout=timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=3, initial_interval=timedelta(seconds=10)),+ )++[email protected](name=CALENDAR_SYNC_COORDINATOR_WORKFLOW_NAME)+class CalendarSyncCoordinatorWorkflow:+ """Hourly coordinator: one child per connected calendar.++ Child ids are deterministic per integration, so overlapping ticks can't sync the+ same calendar concurrently (start fails with WorkflowAlreadyStartedError while a+ child runs). ALLOW_DUPLICATE lets the next tick start a fresh run once the+ previous one closed - syncs are cursor-based and idempotent, so reruns are safe.+ """++ @staticmethod+ def parse_inputs(inputs: list[str]) -> CalendarSyncCoordinatorInput:+ if not inputs:+ return CalendarSyncCoordinatorInput()+ return CalendarSyncCoordinatorInput(**json.loads(inputs[0]))++ @workflow.run+ async def run(self, _input: CalendarSyncCoordinatorInput) -> CalendarSyncCoordinatorOutput:+ result = await workflow.execute_activity(+ calendar_sync_collect_integrations_activity,+ _input,+ start_to_close_timeout=timedelta(minutes=5),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )++ started = 0+ skipped = 0+ for item in result.integrations:+ child_id = f"google-calendar-sync-{item.integration_id}"+ try:+ await workflow.start_child_workflow(+ CalendarSyncWorkflow.run,+ item,+ id=child_id,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ parent_close_policy=workflow.ParentClosePolicy.ABANDON,+ )+ started += 1+ except WorkflowAlreadyStartedError:+ workflow.logger.info(+ "calendar_sync coordinator: child already running",+ extra={"child_id": child_id},+ )+ skipped += 1++ return CalendarSyncCoordinatorOutput(+ due_count=len(result.integrations), started_count=started, skipped_count=skipped+ )+++async def create_calendar_sync_coordinator_schedule(client: Client) -> None:+ schedule = Schedule(+ action=ScheduleActionStartWorkflow(+ CALENDAR_SYNC_COORDINATOR_WORKFLOW_NAME,+ CalendarSyncCoordinatorInput(),+ id=f"{CALENDAR_SYNC_COORDINATOR_WORKFLOW_NAME}-workflow",+ task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,+ ),+ spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=timedelta(minutes=COORDINATOR_INTERVAL_MINUTES))]),+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),+ )+ if await a_schedule_exists(client, CALENDAR_SYNC_COORDINATOR_SCHEDULE_ID):+ await a_update_schedule(client, CALENDAR_SYNC_COORDINATOR_SCHEDULE_ID, schedule)+ else:+ await a_create_schedule(client, CALENDAR_SYNC_COORDINATOR_SCHEDULE_ID, schedule, trigger_immediately=False)diff --git a/products/customer_analytics/backend/test/test_calendar_sync.py b/products/customer_analytics/backend/test/test_calendar_sync.pynew file mode 100644index 000000000000..a0ad0f484d87--- /dev/null+++ b/products/customer_analytics/backend/test/test_calendar_sync.py@@ -0,0 +1,160 @@+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from products.customer_analytics.backend.logic import calendar_sync+from products.customer_analytics.backend.models import Account, Meeting, MeetingParticipant, MeetingStatus+++def _event(**overrides) -> dict:+ event = {+ "iCalUID": "[email protected]",+ "status": "confirmed",+ "summary": "Quarterly review",+ "start": {"dateTime": "2026-08-04T15:00:00+00:00"},+ "end": {"dateTime": "2026-08-04T16:00:00+00:00"},+ "organizer": {"email": "[email protected]"},+ "attendees": [+ {"email": "[email protected]", "responseStatus": "accepted"},+ {"email": "[email protected]", "responseStatus": "accepted", "displayName": "Jane"},+ ],+ }+ event.update(overrides)+ return event+++def _pages_response(events: list[dict], sync_token: str = "token-1") -> MagicMock:+ response = MagicMock()+ response.status_code = 200+ response.json.return_value = {"items": events, "nextSyncToken": sync_token}+ return response+++class TestCalendarSync(BaseTest):+ def setUp(self):+ super().setUp()+ self.integration = self._create_integration()++ def _create_integration(self):+ from posthog.models.integration import Integration++ return Integration.objects.create(+ team=self.team,+ kind="google-calendar",+ integration_id="google-sub-1",+ config={"email": "[email protected]", "refreshed_at": 9999999999, "expires_in": 3600},+ sensitive_config={"access_token": "ACCESS", "refresh_token": "REFRESH"},+ )++ def _sync(self, responses: list[MagicMock]) -> calendar_sync.CalendarSyncCounts:+ with (+ patch.object(calendar_sync, "_group_keys_via_persons", return_value={}),+ patch.object(calendar_sync.requests, "get", side_effect=responses),+ ):+ return calendar_sync.sync_calendar_integration(self.integration.id, self.team.id)++ def test_upserts_meeting_with_participants_and_matches_by_email_domain(self):+ account = Account.objects.for_team(self.team.id).create(team=self.team, name="Acme", external_id="acme")+ account.properties = {"email_domains": ["acme.com"]}+ account.save()++ counts = self._sync([_pages_response([_event()])])++ meeting = Meeting.objects.for_team(self.team.id).get()+ assert meeting.account_id == account.id+ assert meeting.title == "Quarterly review"+ assert meeting.status == MeetingStatus.CONFIRMED+ participants = {p.email: p for p in MeetingParticipant.objects.for_team(self.team.id)}+ assert set(participants) == {"[email protected]", "[email protected]"}+ assert participants["[email protected]"].response_status == "accepted"+ assert counts.matched == 1+ self.integration.refresh_from_db()+ assert self.integration.config["calendar_sync_token"] == "token-1"++ def test_resync_of_same_event_updates_one_row(self):+ self._sync([_pages_response([_event()])])+ self._sync([_pages_response([_event(summary="Renamed")])])++ meeting = Meeting.objects.for_team(self.team.id).get()+ assert meeting.title == "Renamed"++ def test_recurring_instances_get_separate_rows(self):+ instances = [+ _event(+ id="series_20260804",+ recurringEventId="series",+ originalStartTime={"dateTime": "2026-08-04T15:00:00+00:00"},+ ),+ _event(+ id="series_20260811",+ recurringEventId="series",+ originalStartTime={"dateTime": "2026-08-11T15:00:00+00:00"},+ start={"dateTime": "2026-08-11T15:00:00+00:00"},+ ),+ ]+ self._sync([_pages_response(instances)])+ assert Meeting.objects.for_team(self.team.id).count() == 2++ def test_private_and_internal_only_events_are_never_stored(self):+ events = [+ _event(visibility="private"),+ _event(+ iCalUID="[email protected]",+ attendees=[+ {"email": "[email protected]", "responseStatus": "accepted"},+ {"email": "[email protected]", "responseStatus": "accepted"},+ ],+ ),+ ]+ counts = self._sync([_pages_response(events)])+ assert Meeting.objects.for_team(self.team.id).count() == 0+ assert counts.skipped == 2++ def test_event_made_private_after_storage_is_deleted(self):+ self._sync([_pages_response([_event()])])+ assert Meeting.objects.for_team(self.team.id).count() == 1++ self._sync([_pages_response([_event(visibility="private")])])+ assert Meeting.objects.for_team(self.team.id).count() == 0++ def test_cancelled_event_keeps_row_flagged_cancelled(self):+ self._sync([_pages_response([_event()])])+ counts = self._sync([_pages_response([{"iCalUID": "[email protected]", "status": "cancelled"}])])++ meeting = Meeting.objects.for_team(self.team.id).get()+ assert meeting.status == MeetingStatus.CANCELLED+ assert counts.cancelled == 1++ def test_stale_sync_token_falls_back_to_full_relist(self):+ self.integration.config["calendar_sync_token"] = "stale"+ self.integration.save()+ gone = MagicMock(status_code=410)+ counts = self._sync([gone, _pages_response([_event()], sync_token="fresh")])++ assert counts.upserted == 1+ self.integration.refresh_from_db()+ assert self.integration.config["calendar_sync_token"] == "fresh"++ def test_known_email_matches_account_on_personal_domain(self):+ account = Account.objects.for_team(self.team.id).create(team=self.team, name="Kwak Bros", external_id="kwak")+ account.properties = {"known_emails": ["[email protected]"]}+ account.save()++ event = _event(+ attendees=[+ {"email": "[email protected]", "responseStatus": "accepted"},+ {"email": "[email protected]", "responseStatus": "accepted"},+ ]+ )+ self._sync([_pages_response([event])])+ assert Meeting.objects.for_team(self.team.id).get().account_id == account.id++ def test_ambiguous_email_domain_matches_nothing(self):+ for name in ("Acme US", "Acme EU"):+ account = Account.objects.for_team(self.team.id).create(+ team=self.team, name=name, external_id=name.lower().replace(" ", "-")+ )+ account.properties = {"email_domains": ["acme.com"]}+ account.save()++ self._sync([_pages_response([_event()])])+ assert Meeting.objects.for_team(self.team.id).get().account_id is Nonediff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.pyindex cc311d7e9c90..c4bec20c78a0 100644--- a/products/customer_analytics/backend/test/test_views.py+++ b/products/customer_analytics/backend/test/test_views.py@@ -31,6 +31,8 @@ from products.customer_analytics.backend.models import (CustomPropertyDefinition,CustomPropertySource,DisplayType,+ Meeting,+ MeetingParticipant,TargetType,)from products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition@@ -2662,3 +2664,31 @@ class TestAccountSupportTicketViewSet(APIBaseTest):self.client.force_login(viewer)self.assertEqual(status.HTTP_403_FORBIDDEN, self.client.get(self.endpoint).status_code)+++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")+ other = Account.objects.unscoped().create(team=self.team, name="Other", external_id="other-1")+ older = Meeting.objects.unscoped().create(+ team=self.team, account=account, ical_uid="uid-old", start_time="2026-08-01T15:00:00Z", title="Kickoff"+ )+ newer = Meeting.objects.unscoped().create(+ team=self.team, account=account, ical_uid="uid-new", start_time="2026-08-03T15:00:00Z", title="Review"+ )+ Meeting.objects.unscoped().create(+ team=self.team, account=other, ical_uid="uid-other", start_time="2026-08-02T15:00:00Z"+ )+ MeetingParticipant.objects.unscoped().create(+ team=self.team, meeting=newer, email="[email protected]", response_status="accepted"+ )++ 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()+ 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}],+ )diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex 65fd5c9efe4c..d37962edf2b5 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -25,7 +25,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc│ AccountsOverviewTilesButton + AccountsColumnConfigurator on the right├── AccountsOverviewTiles metric tiles across the filtered set└── AccountsHogQLTable the DataTable; per-column renderers; controlled row expansion- └── AccountNotebooksExpansion expanded row: sidebar (Useful links + active-relationships summary) + LemonTabs(Notes/Users/Relationships/Usage/Spend/Opportunities/Summaries/Support tickets/Event stream)+ └── AccountNotebooksExpansion expanded row: sidebar (Useful links + active-relationships summary) + LemonTabs(Notes/Users/Relationships/Usage/Spend/Opportunities/Summaries/Support tickets/Meetings/Event stream)├── (notes) paginated/searchable/sortable LemonTable + "New note" button (accountNotebooksLogic, keyed by accountId)├── (users) AccountRelatedUsersExpansion (accountRelatedUsersLogic, keyed by externalId)├── (relationships) AccountRelationshipsExpansion (accountRelationshipsLogic, keyed by accountId — full assignment timeline, paginated; assign/end controls + definition filter, current assignments sorted on top)@@ -34,26 +34,28 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc└── (opportunities) AccountOpportunitiesExpansion (accountOpportunitiesLogic, keyed by accountId — DWH Salesforce opportunities)└── (summaries) AccountSummariesExpansion (accountSummariesLogic, keyed by accountId — periodic AI summaries of the account's Slack channel, plus the cadence opt-in)└── (support_tickets) AccountSupportTicketsExpansion (accountSupportTicketsLogic, keyed by accountId — conversations support tickets, via the accounts/:id/support_tickets endpoint)+ └── (meetings) AccountMeetingsExpansion (accountMeetingsLogic, keyed by accountId — synced Google Calendar meetings via the accounts/:id/meetings endpoint, plus the matching editor; flag-gated tab, CUSTOMER_ANALYTICS_CSP)└── (event_stream) AccountEventStreamToggle (`../EventStream/`) flag-gated tab (CUSTOMER_ANALYTICS_CSP); membership toggle for the Slack event stream```### Logics and what each owns-| Logic | Owns |-| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `accountsLogic` | The hub. Search (debounced), tag / assigned-to/unassigned / custom-property filters, sort, inline role assignment, the `hogqlQuery` selector, shareable URL-hash view state, and `openAccount` (the Max entry point). `connect`s column-config, overview-tiles, and expansion logics. |-| `accountsViewsLogic` | Saved-views lifecycle (list/create/update/delete/select). Connects to `accountsLogic`, `accountsColumnConfigLogic`, and `accountsOverviewTilesLogic`; is the single owner of reading and writing the `ColumnConfiguration` rows for this area. |-| `accountsColumnConfigLogic` | Selected columns (`selectColumns` / `visibleColumnNames`), the column-picker groups built from the DB schema + data-warehouse joins, and the per-team saved column config (`columnConfigurations` API), and the custom-property definitions: it loads them, seeds `propertyDefinitionsModel` (so the filter UI resolves per-type operator sets), and exposes `customPropertyTaxonomicOptions` / `customPropertyDefinitionsById`. |-| `accountsExpansionLogic` | Which rows are expanded (`expandedAccountIds`) and the active tab per account (`activeTabByAccount`). Pure state — no DOM, no data fetching. |-| `accountsOverviewTilesLogic` | The overview metric tiles (saved in views via `properties.tiles`); its `metrics` feed `accountsLogic.metricsQuery`, the separate metrics-only data node (key `ACCOUNTS_METRICS_DATA_NODE_KEY`) it reads `response`/`responseLoading` back from — independent of the list rows. Reads legacy per-team localStorage tiles **read-only** on mount + emits an `OverviewTilesLocalStorageRead` tombstone; never writes localStorage. |-| `accountNotebooksLogic` | Notes/notebooks linked to one account (keyed by `accountId`): server-side pagination (`page`/`notebooksCount`), debounced title+content search (`searchTerm`), sort (`sorting` by created date/author), and `createNote` (creates an internal account notebook and opens it in the side panel). |-| `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). US-region orgs come from the org-members endpoint; when it returns no members, the logic falls back to the `eu_org_members` data warehouse view (a materialized pre-join of the EU postgres sync, prod-only, refreshed daily), fetched once per expansion and paginated client-side. A missing view (local dev) degrades to the normal empty state. |-| `accountRelationshipsLogic` | Relationship assignments for one account (keyed by `accountId`): fetches the full timeline once (`include_history=true` on the nested relationships endpoint) — the `displayedRelationships` selector (current assignments first, newest first, optionally narrowed by `definitionFilter`) feeds the (paginated) history tab, the `activeRelationships` selector feeds the sidebar summary. Also owns the tab's mutations: `assignRelationship` (definition picker + `MemberSelect`, POSTs the assign endpoint) and `endRelationship` (per active row, POSTs the end endpoint) — both guarded by a shared `relationshipSaving` flag, reload the timeline, and force-refresh the list's data nodes so relationship columns stay in sync. |-| `accountBillingLogic` | Billing data behind the Usage and Spend tabs (keyed by `accountId:kind`); injects the account's org + date range into saved billing insights' SQL variables, and owns the per-view hidden-series state (`ephemeralHiddenSeriesKeysByShortId`) behind the chart chips. |-| `accountOpportunitiesLogic` | Salesforce opportunities behind the Opportunities tab (keyed by `accountId`): fetches the account's `sfdc_id`, then queries the data-warehouse `salesforce.opportunity` table via HogQL. Degrades to an empty state (not an error) when the table is absent — it's production-only. |-| `accountSummariesLogic` | The Summaries tab (keyed by `accountId`): fetches the account (for its linked `slack_channel_id` and `slack_summary_cadence`) plus the first page of the `accountsSummariesList` endpoint, navigates server pages via `loadSummariesPage` (5 per page, `page` reducer; each page replaces the last), holds per-summary collapse state (`expandedSummaryIds` / `toggleSummaryExpanded`), and owns the cadence opt-in (`setCadence` PATCHes the account through `accountsPartialUpdate`, guarded by a `cadenceSaving` flag). Distinguishes not-loaded / no-channel-linked / loaded-empty / load-failed; captures unexpected failures. |-| `accountSupportTicketsLogic` | Conversations support tickets behind the Support tickets tab (keyed by `accountId`): fetches the account's tickets from the generated `accountsSupportTicketsList` endpoint (backed by the customer-analytics facade → conversations facade → `Ticket`s matched on `organization_id = external_id`). Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. |-| `accountLinksLogic` | The "Useful links" sidebar for one account (keyed by `accountId`). |+| Logic | Owns |+| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `accountsLogic` | The hub. Search (debounced), tag / assigned-to/unassigned / custom-property filters, sort, inline role assignment, the `hogqlQuery` selector, shareable URL-hash view state, and `openAccount` (the Max entry point). `connect`s column-config, overview-tiles, and expansion logics. |+| `accountsViewsLogic` | Saved-views lifecycle (list/create/update/delete/select). Connects to `accountsLogic`, `accountsColumnConfigLogic`, and `accountsOverviewTilesLogic`; is the single owner of reading and writing the `ColumnConfiguration` rows for this area. |+| `accountsColumnConfigLogic` | Selected columns (`selectColumns` / `visibleColumnNames`), the column-picker groups built from the DB schema + data-warehouse joins, and the per-team saved column config (`columnConfigurations` API), and the custom-property definitions: it loads them, seeds `propertyDefinitionsModel` (so the filter UI resolves per-type operator sets), and exposes `customPropertyTaxonomicOptions` / `customPropertyDefinitionsById`. |+| `accountsExpansionLogic` | Which rows are expanded (`expandedAccountIds`) and the active tab per account (`activeTabByAccount`). Pure state — no DOM, no data fetching. |+| `accountsOverviewTilesLogic` | The overview metric tiles (saved in views via `properties.tiles`); its `metrics` feed `accountsLogic.metricsQuery`, the separate metrics-only data node (key `ACCOUNTS_METRICS_DATA_NODE_KEY`) it reads `response`/`responseLoading` back from — independent of the list rows. Reads legacy per-team localStorage tiles **read-only** on mount + emits an `OverviewTilesLocalStorageRead` tombstone; never writes localStorage. |+| `accountNotebooksLogic` | Notes/notebooks linked to one account (keyed by `accountId`): server-side pagination (`page`/`notebooksCount`), debounced title+content search (`searchTerm`), sort (`sorting` by created date/author), and `createNote` (creates an internal account notebook and opens it in the side panel). |+| `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). US-region orgs come from the org-members endpoint; when it returns no members, the logic falls back to the `eu_org_members` data warehouse view (a materialized pre-join of the EU postgres sync, prod-only, refreshed daily), fetched once per expansion and paginated client-side. A missing view (local dev) degrades to the normal empty state. |+| `accountRelationshipsLogic` | Relationship assignments for one account (keyed by `accountId`): fetches the full timeline once (`include_history=true` on the nested relationships endpoint) — the `displayedRelationships` selector (current assignments first, newest first, optionally narrowed by `definitionFilter`) feeds the (paginated) history tab, the `activeRelationships` selector feeds the sidebar summary. Also owns the tab's mutations: `assignRelationship` (definition picker + `MemberSelect`, POSTs the assign endpoint) and `endRelationship` (per active row, POSTs the end endpoint) — both guarded by a shared `relationshipSaving` flag, reload the timeline, and force-refresh the list's data nodes so relationship columns stay in sync. |+| `accountBillingLogic` | Billing data behind the Usage and Spend tabs (keyed by `accountId:kind`); injects the account's org + date range into saved billing insights' SQL variables, and owns the per-view hidden-series state (`ephemeralHiddenSeriesKeysByShortId`) behind the chart chips. |+| `accountOpportunitiesLogic` | Salesforce opportunities behind the Opportunities tab (keyed by `accountId`): fetches the account's `sfdc_id`, then queries the data-warehouse `salesforce.opportunity` table via HogQL. Degrades to an empty state (not an error) when the table is absent — it's production-only. |+| `accountSummariesLogic` | The Summaries tab (keyed by `accountId`): fetches the account (for its linked `slack_channel_id` and `slack_summary_cadence`) plus the first page of the `accountsSummariesList` endpoint, navigates server pages via `loadSummariesPage` (5 per page, `page` reducer; each page replaces the last), holds per-summary collapse state (`expandedSummaryIds` / `toggleSummaryExpanded`), and owns the cadence opt-in (`setCadence` PATCHes the account through `accountsPartialUpdate`, guarded by a `cadenceSaving` flag). Distinguishes not-loaded / no-channel-linked / loaded-empty / load-failed; captures unexpected failures. |+| `accountSupportTicketsLogic` | Conversations support tickets behind the Support tickets tab (keyed by `accountId`): fetches the account's tickets from the generated `accountsSupportTicketsList` endpoint (backed by the customer-analytics facade → conversations facade → `Ticket`s matched on `organization_id = external_id`). Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. |+| `accountMeetingsLogic` | The Meetings tab (keyed by `accountId`): fetches synced calendar meetings from the generated `accountsMeetingsList` endpoint (customer-analytics facade `get_account_meetings` over the `Meeting` model, populated by the Google Calendar Temporal sync). Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. Also owns the "Edit matching" editor: `email_domains` / `known_emails` drafts, normalization (trim, lowercase, strip a leading `@`, dedupe), and `saveMatching` — merges them into the account's `properties` via `accountsPartialUpdate` (guarded by `savingMatching`) and propagates the updated account through `accountLinksLogic.loadAccountSuccess` (it connects to that logic for the account instead of fetching its own copy). |+| `accountLinksLogic` | The "Useful links" sidebar for one account (keyed by `accountId`). |## Data & query model@@ -108,7 +110,7 @@ Sort safety: removing the sorted column drops the sort (`clearSortIfColumnRemove`AccountsHogQLTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. The body is `AccountNotebooksExpansion`, a `LemonTabs` over `notes` / `users` / `relationships` / `usage` / `spend` / `opportunities` / `summaries` / `support_tickets` / `event_stream` (`AccountExpansionTab`; the `event_stream` tab is gated by the `CUSTOMER_ANALYTICS_CSP` flag) plus the sidebar (Useful links + an active-relationships summary, `ActiveRelationships`, hidden when nothing is assigned). Active tab comes from `activeTabFor(accountId)` (defaults to `notes`).-**Tab data is cached for the row's expanded lifetime, not refetched per tab switch.** `LemonTabs` only renders the active tab's content (keyed by `activeKey`), so a tab's logic would normally unmount the moment you switch away and refetch on return. To avoid that, `AccountNotebooksExpansion` holds a mount reference to each per-tab logic via `useMountedLogic` — `accountRelatedUsersLogic({ externalId })`, `accountRelationshipsLogic({ accountId })`, `accountBillingLogic` for both `kind: 'usage'` and `kind: 'spend'`, `accountOpportunitiesLogic({ accountId })`, `accountSummariesLogic({ accountId })`, and `accountSupportTicketsLogic({ accountId })`. Since `AccountNotebooksExpansion` stays mounted for as long as the row is expanded (it's the `expandedRowRender` body), those keyed instances survive tab switches and only tear down when the row collapses. The `useMountedLogic` props must stay identical to the `useValues` props in the tab components (`AccountRelatedUsersExpansion`, `AccountRelationshipsExpansion`, `AccountBillingExpansion`, `AccountOpportunitiesExpansion`, `AccountSummariesExpansion`, `AccountSupportTicketsExpansion`) so both resolve to the same keyed instance. `accountNotebooksLogic` and `accountLinksLogic` already mount at this level (Notes content and the always-rendered sidebar), so they need no explicit mount reference. Data is loaded once on mount and not auto-refreshed while the row stays open — acceptable since this data needn't be live.+**Tab data is cached for the row's expanded lifetime, not refetched per tab switch.** `LemonTabs` only renders the active tab's content (keyed by `activeKey`), so a tab's logic would normally unmount the moment you switch away and refetch on return. To avoid that, `AccountNotebooksExpansion` holds a mount reference to each per-tab logic via `useMountedLogic` — `accountRelatedUsersLogic({ externalId })`, `accountRelationshipsLogic({ accountId })`, `accountBillingLogic` for both `kind: 'usage'` and `kind: 'spend'`, `accountOpportunitiesLogic({ accountId })`, `accountSummariesLogic({ accountId })`, `accountSupportTicketsLogic({ accountId })`, and `accountMeetingsLogic({ accountId })`. Since `AccountNotebooksExpansion` stays mounted for as long as the row is expanded (it's the `expandedRowRender` body), those keyed instances survive tab switches and only tear down when the row collapses. The `useMountedLogic` props must stay identical to the `useValues` props in the tab components (`AccountRelatedUsersExpansion`, `AccountRelationshipsExpansion`, `AccountBillingExpansion`, `AccountOpportunitiesExpansion`, `AccountSummariesExpansion`, `AccountSupportTicketsExpansion`, `AccountMeetingsExpansion`) so both resolve to the same keyed instance. `accountNotebooksLogic` and `accountLinksLogic` already mount at this level (Notes content and the always-rendered sidebar), so they need no explicit mount reference. Data is loaded once on mount and not auto-refreshed while the row stays open — acceptable since this data needn't be live.The Users tab reads its loaded data straight off `accountRelatedUsersLogic`, so the root mount above keeps it cached. The **Usage/Spend** tabs are different: `accountBillingLogic` only holds the saved-insight _metadata_ — the actual insight **results** live in the `dataNodeLogic`/`dataVisualizationLogic` mounted inside the tab body, which the root mount does **not** keep alive. So the tab body attaches those data logics to the (root-mounted) `accountBillingLogic` via `useAttachedLogic` — `AccountBillingChart` does this for the chart it renders, and the fallback `<Query>` path does it via `attachTo={accountBillingLogic-instance}` — so they outlive the tab body unmounting on tab switch and only detach when the row collapses. Without that attachment, usage/spend refetch on every return to the tab even with the metadata logic mounted. (The Opportunities tab loads its data in `accountOpportunitiesLogic` directly, not via an embedded query, so the root `useMountedLogic` above is enough — it needs no attachment.)@@ -132,6 +134,11 @@ An account with no `external_id` simply returns an empty list (the backend shortEach ticket row links to the ticket in the conversations UI via the `deep_link` the backend builds (`{SITE_URL}/project/<team>/support/tickets/<ticket_number>`), firing `SupportTicketClicked`.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`).+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.+Clicking a note in the Notes tab opens it in the global notebook **side panel** (`notebookPanelLogic.selectNotebook`), keeping the Accounts list mounted — not the full `NotebookScene`. The note `<Link>` still points at `urls.notebook(shortId)` so cmd/ctrl-click opens the full page in a new tab; a plain click `preventDefault()`s the router push and opens the panel instead.The Notes tab is server-paginated, searchable, and sortable (all via `accountNotebooksLogic`, which sends `limit`/`offset`/`search`/`ordering` to `accountsNotebooksList`). Search is full-text over title **and** content (mirrors the main Notebooks page); the **Created by** and **Created at** columns sort server-side (whitelisted `ordering`, default `-created_at`). The **New note** button creates an internal notebook linked to the account (via `accountsNotebooksCreate`) and opens it in the side panel — it persists immediately like normal notebook creation (no empty-cleanup). The backend chain threading `search`/`order` is: `AccountNotebookViewSet.list` (whitelists `ordering`) → customer-analytics facade `api.list_account_notebooks` → notebooks facade → `notebooks/backend/logic.list_account_notebooks`.@@ -258,7 +265,7 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions| `customer analytics accounts note created` | `accountNotebooksLogic` `createNoteSuccess` listener | `notebook_short_id` || `customer analytics accounts notes searched` | `accountNotebooksLogic` `setSearchTerm` listener (post-debounce) | `has_query`, `query_length` (no raw text) || `customer analytics accounts notes sorted` | `accountNotebooksLogic` `setSorting` listener | `column` (`created_at` \| `created_by` \| null), `direction` (`asc` \| `desc` \| `cleared`) |-| `customer analytics account tab viewed` | `accountsExpansionLogic` `setActiveTab` listener (genuine tab clicks only; programmatic `openAccountTab` navigation does not fire it) | `tab` (`notes` \| `users` \| `relationships` \| `usage` \| `spend` \| `opportunities` \| `summaries` \| `support_tickets` \| `event_stream`) |+| `customer analytics account tab viewed` | `accountsExpansionLogic` `setActiveTab` listener (genuine tab clicks only; programmatic `openAccountTab` navigation does not fire it) | `tab` (`notes` \| `users` \| `relationships` \| `usage` \| `spend` \| `opportunities` \| `summaries` \| `support_tickets` \| `meetings` \| `event_stream`) || `customer analytics account usage series toggled` | `accountBillingLogic` `toggleHiddenSeriesKey` listener (dispatched by the `AccountBillingSeriesToggle` chips) | `kind` (`usage` \| `spend`), `is_hidden` (the post-click state), `series_count` (no series label / no PII) || `customer analytics account usage series bulk toggled` | `accountBillingLogic` `setAllSeriesHidden` listener (dispatched by the Select all / Clear all buttons in `AccountBillingSeriesToggle`) | `kind` (`usage` \| `spend`), `is_hidden` (`true` when hiding all, `false` when showing all), `series_count` (no series label / no PII) || `customer analytics account related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ |@@ -267,6 +274,7 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions| `customer analytics account summary expanded` | `accountSummariesLogic` `toggleSummaryExpanded` listener (only when the toggle opens a summary, not on collapse) | _(none — summary content/period is customer data and kept out)_ || `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 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.tsxnew file mode 100644index 000000000000..f91dc8a922ab--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsx@@ -0,0 +1,194 @@+import { useActions, useValues } from 'kea'++import { IconPencil } from '@posthog/icons'+import {+ LemonButton,+ LemonDivider,+ LemonDropdown,+ LemonInputSelect,+ LemonSkeleton,+ LemonTable,+ LemonTableColumns,+ LemonTag,+} from '@posthog/lemon-ui'++import { BigLeaguesHog } from 'lib/components/hedgehogs'+import { TZLabel } from 'lib/components/TZLabel'++import { MeetingApi } from 'products/customer_analytics/frontend/generated/api.schemas'++import { accountMeetingsLogic, NOT_LOADED } from './accountMeetingsLogic'++// Matches the Support tickets tab, the other client-side-paginated account tab.+const PAGE_SIZE = 10++function EditMeetingMatchingButton({ accountId }: { accountId: string }): JSX.Element {+ const logic = accountMeetingsLogic({ accountId })+ const { matchingEditorOpen, domainsDraft, emailsDraft, savingMatching } = useValues(logic)+ const { openMatchingEditor, 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>+ }+ >+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconPencil />}+ data-attr="edit-meeting-matching"+ onClick={openMatchingEditor}+ >+ Edit matching+ </LemonButton>+ </LemonDropdown>+ )+}++function MeetingsEmptyState({ title, detail }: { title: string; detail: string }): JSX.Element {+ return (+ <div className="flex flex-col items-center justify-center gap-2 p-8 text-center">+ <BigLeaguesHog className="w-24 h-24" />+ <h4 className="mb-0">{title}</h4>+ <p className="text-secondary max-w-sm mb-0">{detail}</p>+ </div>+ )+}++const STATUS_TAG_TYPE = {+ confirmed: 'success',+ tentative: 'default',+ 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 }))++ if (meetingsResultLoading || meetingsResult === NOT_LOADED) {+ return <LemonSkeleton className="h-64 w-full" />+ }++ const { meetings, loadFailed } = meetingsResult++ let content: JSX.Element+ if (loadFailed) {+ content = (+ <MeetingsEmptyState+ title="Couldn't load meetings"+ detail="Something went wrong loading this account's meetings. Try refreshing the page."+ />+ )+ } else if (!meetings || meetings.length === 0) {+ content = (+ <MeetingsEmptyState+ title="No meetings yet"+ detail="Meetings from connected Google Calendars that include people from this account show up here. Use 'Edit matching' to add the email domains and addresses that identify this account."+ />+ )+ } else {+ content = (+ <LemonTable<MeetingApi>+ size="small"+ embedded+ dataSource={meetings}+ columns={columns}+ rowKey="id"+ pagination={{ pageSize: PAGE_SIZE }}+ />+ )+ }++ return (+ <div className="flex flex-col gap-2">+ <div className="flex justify-end">+ <EditMeetingMatchingButton accountId={accountId} />+ </div>+ {content}+ </div>+ )+}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsxindex b9f508d79ee0..c6afda8950d6 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx@@ -38,6 +38,8 @@ import { AccountEventStreamToggle } from '../EventStream/AccountEventStreamTogglimport { AccountBillingExpansion } from './AccountBillingExpansion'import { accountBillingLogic } from './accountBillingLogic'import { accountLinksLogic } from './accountLinksLogic'+import { AccountMeetingsExpansion } from './AccountMeetingsExpansion'+import { accountMeetingsLogic } from './accountMeetingsLogic'import { accountNotebooksLogic } from './accountNotebooksLogic'import { AccountOpportunitiesExpansion } from './AccountOpportunitiesExpansion'import { accountOpportunitiesLogic } from './accountOpportunitiesLogic'@@ -178,6 +180,7 @@ export function AccountNotebooksExpansion({useMountedLogic(accountOpportunitiesLogic({ accountId }))useMountedLogic(accountSummariesLogic({ accountId }))useMountedLogic(accountSupportTicketsLogic({ accountId }))+ useMountedLogic(accountMeetingsLogic({ accountId }))const { setSearchTerm, setSorting, createNote } = useActions(logic)const { featureFlags } = useValues(featureFlagLogic)const { activeTabFor } = useValues(accountsExpansionLogic)@@ -355,6 +358,11 @@ export function AccountNotebooksExpansion({content: <AccountSupportTicketsExpansion accountId={accountId} />,},// Flag-gated here (not just inside the component) so the tab label hides too.+ !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP] && {+ key: 'meetings' as const,+ label: 'Meetings',+ content: <AccountMeetingsExpansion accountId={accountId} />,+ },!!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP] && {key: 'event_stream' as const,label: 'Event stream',diff --git a/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.test.tsnew file mode 100644index 000000000000..e29e7d193b8a--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.test.ts@@ -0,0 +1,91 @@+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { initKeaTests } from '~/test/init'++import {+ accountsMeetingsList,+ accountsPartialUpdate,+ accountsRetrieve,+} from 'products/customer_analytics/frontend/generated/api'+import type { AccountApi, MeetingApi } from 'products/customer_analytics/frontend/generated/api.schemas'++import { accountMeetingsLogic } from './accountMeetingsLogic'++jest.mock('products/customer_analytics/frontend/generated/api', () => ({+ // Keep the real module for everything else — connected logics call other generated+ // functions on mount, and an absent export makes their loaders throw on every test.+ ...jest.requireActual('products/customer_analytics/frontend/generated/api'),+ accountsMeetingsList: jest.fn(),+ accountsRetrieve: jest.fn(),+ accountsPartialUpdate: jest.fn(),+}))++const mockList = accountsMeetingsList as jest.MockedFunction<typeof accountsMeetingsList>+const mockRetrieve = accountsRetrieve as jest.MockedFunction<typeof accountsRetrieve>+const mockPartialUpdate = accountsPartialUpdate as jest.MockedFunction<typeof accountsPartialUpdate>++describe('accountMeetingsLogic', () => {+ let logic: ReturnType<typeof accountMeetingsLogic.build>++ beforeEach(() => {+ initKeaTests()+ jest.resetAllMocks()+ jest.spyOn(posthog, 'captureException').mockReturnValue(undefined as any)+ jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)+ mockRetrieve.mockResolvedValue({ id: 'acc-1', properties: {} } as AccountApi)+ })++ afterEach(() => {+ logic?.unmount()+ })++ const mount = async (): Promise<void> => {+ logic = accountMeetingsLogic({ accountId: 'acc-1' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ }++ it('loads the account meetings', async () => {+ const meetings = [{ id: 'm-1', title: 'Kickoff', status: 'confirmed' }] as MeetingApi[]+ mockList.mockResolvedValue(meetings)++ await mount()++ expect(logic.values.meetingsResult).toEqual({ meetings })+ })++ it('surfaces a load-failed result (not an infinite skeleton) and captures the error when the fetch throws', async () => {+ mockList.mockRejectedValue(new Error('network'))++ await mount()++ expect(logic.values.meetingsResult).toEqual({ meetings: null, loadFailed: true })+ expect(posthog.captureException).toHaveBeenCalledTimes(1)+ })++ it('saves normalized matching values without clobbering other account properties', async () => {+ mockList.mockResolvedValue([])+ mockRetrieve.mockResolvedValue({+ id: 'acc-1',+ properties: { billing_id: 'cus_123', email_domains: ['old.com'] },+ } as AccountApi)+ mockPartialUpdate.mockResolvedValue({ id: 'acc-1', properties: {} } as AccountApi)++ await mount()+ logic.actions.setDomainsDraft(['@Acme.com', 'acme.com', ' '])+ logic.actions.setEmailsDraft(['[email protected]'])+ logic.actions.saveMatching()+ await expectLogic(logic).toFinishAllListeners()++ expect(mockPartialUpdate).toHaveBeenCalledWith(expect.any(String), 'acc-1', {+ properties: {+ billing_id: 'cus_123',+ email_domains: ['acme.com'],+ known_emails: ['[email protected]'],+ },+ })+ expect(logic.values.matchingEditorOpen).toBe(false)+ expect(logic.values.savingMatching).toBe(false)+ })+})diff --git a/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.tsnew file mode 100644index 000000000000..80779da29ea5--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.ts@@ -0,0 +1,216 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers } 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 {+ accountsMeetingsList,+ accountsPartialUpdate,+ accountsRetrieve,+} from 'products/customer_analytics/frontend/generated/api'+import type {+ AccountApi,+ MeetingApi,+ PatchedAccountApiProperties,+} from 'products/customer_analytics/frontend/generated/api.schemas'++import { accountLinksLogic } from './accountLinksLogic'+import { AccountsEvents } from './constants'++export interface AccountMeetingsLogicProps {+ accountId: string+}++export interface AccountMeetingsResult {+ meetings: MeetingApi[] | null+ loadFailed?: 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 }++function cleanEmails(values: string[]): string[] {+ return Array.from(new Set(values.map((value) => value.trim().toLowerCase()).filter(Boolean)))+}++function cleanDomains(values: string[]): string[] {+ return cleanEmails(values.map((value) => value.replace(/^@/, '')))+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface accountMeetingsLogicValues {+ account: AccountApi | null // accountLinksLogic+ currentTeamId: number | null // teamLogic+ domainsDraft: string[]+ emailsDraft: string[]+ matchingEditorOpen: boolean+ meetingsResult: AccountMeetingsResult+ meetingsResultLoading: boolean+ savingMatching: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface accountMeetingsLogicActions {+ loadAccountSuccess: (+ account: AccountApi | null,+ payload?: any+ ) => {+ account: AccountApi | null+ payload?: any+ } // accountLinksLogic+ closeMatchingEditor: () => {+ value: true+ }+ loadMeetings: () => any+ loadMeetingsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadMeetingsSuccess: (+ meetingsResult: AccountMeetingsResult,+ payload?: any+ ) => {+ meetingsResult: AccountMeetingsResult+ payload?: any+ }+ openMatchingEditor: () => {+ value: true+ }+ saveMatching: () => {+ value: true+ }+ saveMatchingFinished: () => {+ value: true+ }+ saveMatchingStarted: () => {+ value: true+ }+ setDomainsDraft: (domains: string[]) => {+ domains: string[]+ }+ setEmailsDraft: (emails: string[]) => {+ emails: string[]+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface accountMeetingsLogicMeta {+ key: string+}++export type accountMeetingsLogicType = MakeLogicType<+ accountMeetingsLogicValues,+ accountMeetingsLogicActions,+ AccountMeetingsLogicProps,+ accountMeetingsLogicMeta+>++export const accountMeetingsLogic = kea<accountMeetingsLogicType>([+ path((key) => ['scenes', 'customerAnalytics', 'accounts', 'accountMeetingsLogic', key]),+ props({} as AccountMeetingsLogicProps),+ key((props) => props.accountId),+ connect((props: AccountMeetingsLogicProps) => ({+ values: [teamLogic, ['currentTeamId'], accountLinksLogic({ accountId: props.accountId }), ['account']],+ actions: [accountLinksLogic({ accountId: props.accountId }), ['loadAccountSuccess']],+ })),+ actions({+ openMatchingEditor: true,+ closeMatchingEditor: true,+ setDomainsDraft: (domains: string[]) => ({ domains }),+ setEmailsDraft: (emails: string[]) => ({ emails }),+ saveMatching: true,+ saveMatchingStarted: true,+ saveMatchingFinished: true,+ }),+ loaders(({ props, values }) => ({+ meetingsResult: [+ NOT_LOADED,+ {+ loadMeetings: async (): Promise<AccountMeetingsResult> => {+ try {+ const meetings = await accountsMeetingsList(String(values.currentTeamId), props.accountId)+ return { meetings }+ } catch (error) {+ posthog.captureException(error as Error, {+ scope: 'accountMeetingsLogic.loadMeetings',+ })+ return { meetings: null, loadFailed: true }+ }+ },+ },+ ],+ })),+ reducers({+ matchingEditorOpen: [+ false,+ {+ openMatchingEditor: () => true,+ closeMatchingEditor: () => false,+ },+ ],+ domainsDraft: [+ [] as string[],+ {+ setDomainsDraft: (_, { domains }) => domains,+ },+ ],+ emailsDraft: [+ [] as string[],+ {+ setEmailsDraft: (_, { emails }) => emails,+ },+ ],+ savingMatching: [+ false,+ {+ saveMatchingStarted: () => true,+ saveMatchingFinished: () => false,+ },+ ],+ }),+ listeners(({ actions, values, props }) => ({+ openMatchingEditor: () => {+ actions.setDomainsDraft(values.account?.properties?.email_domains ?? [])+ actions.setEmailsDraft(values.account?.properties?.known_emails ?? [])+ },+ saveMatching: async () => {+ if (values.savingMatching) {+ return+ }+ const projectId = String(values.currentTeamId)+ const domains = cleanDomains(values.domainsDraft)+ const emails = cleanEmails(values.emailsDraft)+ actions.saveMatchingStarted()+ try {+ const current = await accountsRetrieve(projectId, props.accountId)+ const updated = await accountsPartialUpdate(projectId, props.accountId, {+ properties: {+ ...current.properties,+ email_domains: domains,+ known_emails: emails,+ } as PatchedAccountApiProperties,+ })+ actions.loadAccountSuccess(updated)+ actions.closeMatchingEditor()+ lemonToast.success('Meeting matching updated')+ posthog.capture(AccountsEvents.MeetingMatchingSaved, {+ domain_count: domains.length,+ email_count: emails.length,+ })+ } catch (error) {+ posthog.captureException(error as Error, { scope: 'accountMeetingsLogic.saveMatching' })+ lemonToast.error('Failed to save meeting matching')+ } finally {+ actions.saveMatchingFinished()+ }+ },+ })),+ afterMount(({ actions }) => {+ actions.loadMeetings()+ }),+])diff --git a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.tsindex d6041e72a7a9..804899831cca 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts@@ -12,6 +12,7 @@ export type AccountExpansionTab =| 'opportunities'| 'summaries'| 'support_tickets'+ | 'meetings'| 'event_stream'export const ACCOUNT_EXPANSION_TABS: AccountExpansionTab[] = [@@ -23,6 +24,7 @@ export const ACCOUNT_EXPANSION_TABS: AccountExpansionTab[] = ['opportunities','summaries','support_tickets',+ 'meetings','event_stream',]diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.tsindex a4a64418586a..fc4fa250599b 100644--- a/products/customer_analytics/frontend/components/Accounts/constants.ts+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts@@ -56,6 +56,7 @@ export const AccountsEvents = {SummaryExpanded: 'customer analytics account summary expanded',SummariesPageChanged: 'customer analytics account summaries page changed',SupportTicketClicked: 'customer analytics account support ticket clicked',+ MeetingMatchingSaved: 'customer analytics account meeting matching saved',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 8adcf0870653..94d43af363bf 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -210,12 +210,14 @@ export const SlackSummaryCadenceEnumApi = {} as const/**- * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) and email_domains (the company's email domains, used to match inbound touchpoints). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.+ * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) plus touchpoint matching lists: email_domains (the company's email domains) and known_emails (individual addresses pinned to the account). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.* @nullable*/export type AccountApiProperties = {/** Email domains owned by this account's company, used to match inbound touchpoints to the account. */email_domains?: string[]+ /** Individual email addresses pinned to this account, matched before the domain fallback. */+ known_emails?: string[]/** @nullable */stripe_customer_id?: string | null/** @nullable */@@ -251,7 +253,7 @@ export interface AccountApi {*/external_id?: string | null/**- * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) and email_domains (the company's email domains, used to match inbound touchpoints). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.+ * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) plus touchpoint matching lists: email_domains (the company's email domains) and known_emails (individual addresses pinned to the account). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.* @nullable*/properties?: AccountApiProperties@@ -380,12 +382,14 @@ export interface AccountRelationshipWriteApi {}/**- * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) and email_domains (the company's email domains, used to match inbound touchpoints). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.+ * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) plus touchpoint matching lists: email_domains (the company's email domains) and known_emails (individual addresses pinned to the account). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.* @nullable*/export type PatchedAccountApiProperties = {/** Email domains owned by this account's company, used to match inbound touchpoints to the account. */email_domains?: string[]+ /** Individual email addresses pinned to this account, matched before the domain fallback. */+ known_emails?: string[]/** @nullable */stripe_customer_id?: string | null/** @nullable */@@ -421,7 +425,7 @@ export interface PatchedAccountApi {*/external_id?: string | null/**- * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) and email_domains (the company's email domains, used to match inbound touchpoints). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.+ * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) plus touchpoint matching lists: email_domains (the company's email domains) and known_emails (individual addresses pinned to the account). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.* @nullable*/properties?: PatchedAccountApiProperties@@ -442,6 +446,43 @@ export interface PatchedAccountApi {readonly updated_at?: string | null}+/**+ * One attendee of a synced calendar meeting (read-only).+ */+export interface MeetingParticipantApi {+ /** Email address of the attendee. */+ readonly email: string+ /** Display name from the calendar event; may be empty. */+ readonly display_name: string+ /** The attendee's RSVP: 'needs_action', 'accepted', 'declined', or 'tentative'. */+ readonly response_status: string+ /** Whether this attendee organized the meeting. */+ readonly is_organizer: boolean+}++/**+ * A calendar meeting synced from a connected employee calendar (read-only).+ */+export interface MeetingApi {+ /** UUID of the meeting. */+ readonly id: string+ /** Meeting title; may be empty. */+ readonly title: string+ /** When the meeting starts. */+ readonly start_time: string+ /**+ * When the meeting ends.+ * @nullable+ */+ readonly end_time: string | null+ /** Email address of the meeting organizer; may be empty. */+ readonly organizer_email: string+ /** Meeting status: 'confirmed', 'tentative', or 'cancelled'. */+ readonly status: string+ /** Attendees of the meeting. */+ readonly participants: readonly MeetingParticipantApi[]+}+/*** Metadata for one message a channel summary covered — never the message text.*/diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.tsindex d9526b1b84db..d29bc7fc9998 100644--- a/products/customer_analytics/frontend/generated/api.ts+++ b/products/customer_analytics/frontend/generated/api.ts@@ -45,6 +45,7 @@ import type {ExternalAccountListPageApi,GroupUsageMetricApi,GroupsTypesMetricsListParams,+ MeetingApi,PaginatedAccountChannelSummaryListApi,PaginatedAccountListApi,PaginatedAccountNoteListApi,@@ -546,6 +547,21 @@ 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 accountsMeetingsList = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<MeetingApi[]> => {+ return apiMutator<MeetingApi[]>(getAccountsMeetingsListUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}+export const getAccountsSummariesListUrl = (projectId: string, id: string, params?: AccountsSummariesListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.tsindex 1e35888fba19..e8fd06e9893f 100644--- a/products/customer_analytics/frontend/generated/api.zod.ts+++ b/products/customer_analytics/frontend/generated/api.zod.ts@@ -107,6 +107,10 @@ export const AccountsCreateBody = /* @__PURE__ */ zod.describe("Email domains owned by this account's company, used to match inbound touchpoints to the account."),+ known_emails: zod+ .array(zod.string())+ .optional()+ .describe('Individual email addresses pinned to this account, matched before the domain fallback.'),stripe_customer_id: zod.string().nullish(),hubspot_deal_id: zod.string().nullish(),billing_id: zod.string().nullish(),@@ -118,7 +122,7 @@ export const AccountsCreateBody = /* @__PURE__ */ zod}).nullish().describe(- "Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) and email_domains (the company's email domains, used to match inbound touchpoints). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here."+ "Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) plus touchpoint matching lists: email_domains (the company's email domains) and known_emails (individual addresses pinned to the account). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here."),tags: zod.array(zod.string())@@ -188,6 +192,10 @@ export const AccountsUpdateBody = /* @__PURE__ */ zod.describe("Email domains owned by this account's company, used to match inbound touchpoints to the account."),+ known_emails: zod+ .array(zod.string())+ .optional()+ .describe('Individual email addresses pinned to this account, matched before the domain fallback.'),stripe_customer_id: zod.string().nullish(),hubspot_deal_id: zod.string().nullish(),billing_id: zod.string().nullish(),@@ -199,7 +207,7 @@ export const AccountsUpdateBody = /* @__PURE__ */ zod}).nullish().describe(- "Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) and email_domains (the company's email domains, used to match inbound touchpoints). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here."+ "Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) plus touchpoint matching lists: email_domains (the company's email domains) and known_emails (individual addresses pinned to the account). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here."),tags: zod.array(zod.string())@@ -245,6 +253,10 @@ export const AccountsPartialUpdateBody = /* @__PURE__ */ zod.describe("Email domains owned by this account's company, used to match inbound touchpoints to the account."),+ known_emails: zod+ .array(zod.string())+ .optional()+ .describe('Individual email addresses pinned to this account, matched before the domain fallback.'),stripe_customer_id: zod.string().nullish(),hubspot_deal_id: zod.string().nullish(),billing_id: zod.string().nullish(),@@ -256,7 +268,7 @@ export const AccountsPartialUpdateBody = /* @__PURE__ */ zod}).nullish().describe(- "Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) and email_domains (the company's email domains, used to match inbound touchpoints). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here."+ "Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) plus touchpoint matching lists: email_domains (the company's email domains) and known_emails (individual addresses pinned to the account). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here."),tags: zod.array(zod.string())diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yamlindex e84a58540567..b6de0858ad70 100644--- a/products/customer_analytics/mcp/tools.yaml+++ b/products/customer_analytics/mcp/tools.yaml@@ -206,6 +206,9 @@ tools:JSON-encoded array of tag names to filter by, e.g. `["enterprise","priority"]`. Returns accountsthat have any of the listed tags.feature_flag: customer-analytics-csp+ accounts-meetings-list:+ operation: accounts_meetings_list+ enabled: falseaccounts-notebooks-create:operation: accounts_notebooks_createenabled: truediff --git a/products/customer_analytics/turbo.json b/products/customer_analytics/turbo.jsonindex bb57633e21e2..e4f5630a3c15 100644--- a/products/customer_analytics/turbo.json+++ b/products/customer_analytics/turbo.json@@ -9,7 +9,8 @@"backend/hogql_queries/**","backend/max_tools.py","backend/models/team_customer_analytics_config.py",- "backend/tasks/**"+ "backend/tasks/**",+ "backend/temporal/**"],"outputs": [],"cache": truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3599fd4c26c5..3861475393da 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -143,12 +143,14 @@ export namespace Schemas {} as const;/**- * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) and email_domains (the company's email domains, used to match inbound touchpoints). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.+ * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) plus touchpoint matching lists: email_domains (the company's email domains) and known_emails (individual addresses pinned to the account). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.* @nullable*/export type AccountProperties = {/** Email domains owned by this account's company, used to match inbound touchpoints to the account. */email_domains?: string[];+ /** Individual email addresses pinned to this account, matched before the domain fallback. */+ known_emails?: string[];/** @nullable */stripe_customer_id?: string | null;/** @nullable */@@ -198,7 +200,7 @@ export namespace Schemas {*/external_id?: string | null;/**- * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) and email_domains (the company's email domains, used to match inbound touchpoints). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.+ * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) plus touchpoint matching lists: email_domains (the company's email domains) and known_emails (individual addresses pinned to the account). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.* @nullable*/properties?: AccountProperties;@@ -43744,6 +43746,43 @@ export namespace Schemas {scraping_status?: ScrapingStatusEnum | BlankEnum | null;}+ /**+ * One attendee of a synced calendar meeting (read-only).+ */+ export interface MeetingParticipant {+ /** Email address of the attendee. */+ readonly email: string;+ /** Display name from the calendar event; may be empty. */+ readonly display_name: string;+ /** The attendee's RSVP: 'needs_action', 'accepted', 'declined', or 'tentative'. */+ readonly response_status: string;+ /** Whether this attendee organized the meeting. */+ readonly is_organizer: boolean;+ }++ /**+ * A calendar meeting synced from a connected employee calendar (read-only).+ */+ export interface Meeting {+ /** UUID of the meeting. */+ readonly id: string;+ /** Meeting title; may be empty. */+ readonly title: string;+ /** When the meeting starts. */+ readonly start_time: string;+ /**+ * When the meeting ends.+ * @nullable+ */+ readonly end_time: string | null;+ /** Email address of the meeting organizer; may be empty. */+ readonly organizer_email: string;+ /** Meeting status: 'confirmed', 'tentative', or 'cancelled'. */+ readonly status: string;+ /** Attendees of the meeting. */+ readonly participants: readonly MeetingParticipant[];+ }+export interface MemberAccessUpdate {/** Gateway server to toggle for the member. */gateway_server_id: string;@@ -51642,12 +51681,14 @@ export namespace Schemas {}/**- * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) and email_domains (the company's email domains, used to match inbound touchpoints). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.+ * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) plus touchpoint matching lists: email_domains (the company's email domains) and known_emails (individual addresses pinned to the account). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.* @nullable*/export type PatchedAccountProperties = {/** Email domains owned by this account's company, used to match inbound touchpoints to the account. */email_domains?: string[];+ /** Individual email addresses pinned to this account, matched before the domain fallback. */+ known_emails?: string[];/** @nullable */stripe_customer_id?: string | null;/** @nullable */@@ -51683,7 +51724,7 @@ export namespace Schemas {*/external_id?: string | null;/**- * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) and email_domains (the company's email domains, used to match inbound touchpoints). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.+ * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) plus touchpoint matching lists: email_domains (the company's email domains) and known_emails (individual addresses pinned to the account). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.* @nullable*/properties?: PatchedAccountProperties;diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.tsindex 10474b0122c7..f72b1cc273f1 100644--- a/services/mcp/src/generated/customer_analytics/api.ts+++ b/services/mcp/src/generated/customer_analytics/api.ts@@ -160,6 +160,10 @@ export const AccountsCreateBody = /* @__PURE__ */ zod.describe("Email domains owned by this account's company, used to match inbound touchpoints to the account."),+ known_emails: zod+ .array(zod.string())+ .optional()+ .describe('Individual email addresses pinned to this account, matched before the domain fallback.'),stripe_customer_id: zod.string().nullish(),hubspot_deal_id: zod.string().nullish(),billing_id: zod.string().nullish(),@@ -171,7 +175,7 @@ export const AccountsCreateBody = /* @__PURE__ */ zod}).nullish().describe(- "Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) and email_domains (the company's email domains, used to match inbound touchpoints). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here."+ "Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) plus touchpoint matching lists: email_domains (the company's email domains) and known_emails (individual addresses pinned to the account). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here."),tags: zod.array(zod.string())@@ -361,6 +365,10 @@ export const AccountsPartialUpdateBody = /* @__PURE__ */ zod.describe("Email domains owned by this account's company, used to match inbound touchpoints to the account."),+ known_emails: zod+ .array(zod.string())+ .optional()+ .describe('Individual email addresses pinned to this account, matched before the domain fallback.'),stripe_customer_id: zod.string().nullish(),hubspot_deal_id: zod.string().nullish(),billing_id: zod.string().nullish(),@@ -372,7 +380,7 @@ export const AccountsPartialUpdateBody = /* @__PURE__ */ zod}).nullish().describe(- "Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) and email_domains (the company's email domains, used to match inbound touchpoints). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here."+ "Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link) plus touchpoint matching lists: email_domains (the company's email domains) and known_emails (individual addresses pinned to the account). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here."),tags: zod.array(zod.string())