Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(customer-analytics): open Gong calls from meetings (#89486)

Arthur Moreira de Deus771ef3c9e5e9
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index d588136a642e..e7de041d728c 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -3972,11 +3972,22 @@ def list_account_meetings(
| Q(participants__display_name__icontains=search)
).distinct()
count = queryset.count()
- meetings = queryset.order_by("-start_time").prefetch_related("participants")[offset : offset + limit]
+ meetings = list(queryset.order_by("-start_time").prefetch_related("participants")[offset : offset + limit])
+
+ from products.customer_analytics.backend.logic.gong import ( # noqa: PLC0415 — keeps HogQL off the facade import path
+ get_gong_urls_by_meeting_id,
+ )
+
+ team = user_access_control.team
+ if team is None or team.id != team_id:
+ team = Team.objects.get(id=team_id)
+ gong_urls_by_meeting_id = get_gong_urls_by_meeting_id(team=team, user=user_access_control.user, meetings=meetings)
+
views = [
contracts.MeetingView(
id=meeting.id,
title=meeting.title,
+ gong_url=gong_urls_by_meeting_id.get(meeting.id),
start_time=meeting.start_time,
end_time=meeting.end_time,
organizer_email=meeting.organizer_email,
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index 93bc0cc02cf0..aa0c884a693a 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -167,6 +167,7 @@ class MeetingView:
id: UUID
title: str
+ gong_url: str | None
start_time: datetime
end_time: datetime | None
organizer_email: str
diff --git a/products/customer_analytics/backend/logic/gong.py b/products/customer_analytics/backend/logic/gong.py
new file mode 100644
index 000000000000..fa19efd9cc44
--- /dev/null
+++ b/products/customer_analytics/backend/logic/gong.py
@@ -0,0 +1,109 @@
+from collections.abc import Sequence
+from typing import cast
+from urllib.parse import urlparse
+from uuid import UUID
+
+import structlog
+
+from posthog.hogql import ast
+from posthog.hogql.errors import QueryError
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.models.team import Team
+from posthog.models.user import User
+
+from products.customer_analytics.backend.models import Meeting
+from products.warehouse_sources.backend.facade import (
+ api as warehouse_sources,
+ contracts as warehouse_contracts,
+)
+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
+
+logger = structlog.get_logger(__name__)
+
+
+def _gong_calendar_event_id(meeting: Meeting) -> str:
+ if meeting.recurrence_instance_id:
+ return f"{meeting.ical_uid}_{meeting.recurrence_instance_id}"
+ return meeting.ical_uid
+
+
+def _gong_calls_tables(team_id: int) -> list[warehouse_contracts.DataWarehouseTable]:
+ table_ids = {
+ schema.table_id
+ for source in warehouse_sources.list_sources(team_id)
+ if source.source_type == ExternalDataSourceType.GONG
+ for schema in warehouse_sources.list_schemas_for_source(source.id, team_id)
+ if schema.name == "calls" and schema.should_sync and schema.table_id is not None
+ }
+ tables: list[warehouse_contracts.DataWarehouseTable] = []
+ for table_id in sorted(table_ids, key=str):
+ table = warehouse_sources.get_queryable_table(table_id, team_id)
+ if table is not None and {"calendar_event_id", "url"}.issubset(table.columns):
+ tables.append(table)
+ return tables
+
+
+def _valid_gong_url(value: object) -> str | None:
+ if not isinstance(value, str):
+ return None
+ parsed = urlparse(value)
+ hostname = parsed.hostname or ""
+ if parsed.scheme != "https" or (hostname != "gong.io" and not hostname.endswith(".gong.io")):
+ return None
+ return value
+
+
+def get_gong_urls_by_meeting_id(*, team: Team, user: User, meetings: Sequence[Meeting]) -> dict[UUID, str]:
+ meetings_by_calendar_event_id = {_gong_calendar_event_id(meeting): meeting.id for meeting in meetings}
+ if not meetings_by_calendar_event_id:
+ return {}
+
+ gong_urls: dict[UUID, str] = {}
+ remaining_calendar_event_ids = set(meetings_by_calendar_event_id)
+ for table in _gong_calls_tables(team.id):
+ if not remaining_calendar_event_ids:
+ break
+ query = ast.SelectQuery(
+ select=[ast.Field(chain=["calendar_event_id"]), ast.Field(chain=["url"])],
+ select_from=ast.JoinExpr(table=ast.Field(chain=[table.name])),
+ where=ast.CompareOperation(
+ op=ast.CompareOperationOp.In,
+ left=ast.Field(chain=["calendar_event_id"]),
+ right=ast.Constant(value=sorted(remaining_calendar_event_ids)),
+ ),
+ limit=ast.Constant(value=len(remaining_calendar_event_ids) * 10),
+ )
+ try:
+ tag_queries(product=Product.CUSTOMER_ANALYTICS, feature=Feature.QUERY)
+ response = execute_hogql_query(
+ query=query,
+ team=team,
+ user=user,
+ query_type="customer_analytics_gong_call_lookup",
+ )
+ except QueryError as error:
+ logger.info(
+ "gong_call_lookup_unavailable",
+ team_id=team.id,
+ table_id=str(table.id),
+ error_type=type(error).__name__,
+ )
+ continue
+ except Exception:
+ logger.exception("gong_call_lookup_failed", team_id=team.id, table_id=str(table.id))
+ continue
+
+ rows = cast(list[list[object]], response.results or [])
+ for calendar_event_id_value, url_value, *_ in rows:
+ if not isinstance(calendar_event_id_value, str):
+ continue
+ meeting_id = meetings_by_calendar_event_id.get(calendar_event_id_value)
+ gong_url = _valid_gong_url(url_value)
+ if meeting_id is None or gong_url is None or meeting_id in gong_urls:
+ continue
+ gong_urls[meeting_id] = gong_url
+ remaining_calendar_event_ids.discard(calendar_event_id_value)
+
+ return gong_urls
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index f6f85755ddb1..23d8ff0cdf07 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -1394,6 +1394,11 @@ class MeetingSerializer(DataclassSerializer):
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.")
+ gong_url = serializers.URLField(
+ read_only=True,
+ allow_null=True,
+ help_text="Gong call URL matched through the calendar event id; null when no Gong call is available.",
+ )
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(
@@ -1407,7 +1412,7 @@ class MeetingSerializer(DataclassSerializer):
class Meta:
dataclass = MeetingView
ref_name = "Meeting"
- fields = ["id", "title", "start_time", "end_time", "organizer_email", "status", "participants"]
+ fields = ["id", "title", "gong_url", "start_time", "end_time", "organizer_email", "status", "participants"]
class CustomPropertyReferenceSerializer(DataclassSerializer):
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index a944e66e63a6..98a8b83a9468 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -4,7 +4,7 @@ from uuid import uuid4
import pytest
from freezegun import freeze_time
from posthog.test.base import APIBaseTest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from django.apps import apps
from django.utils import timezone
@@ -52,6 +52,7 @@ from products.notebooks.backend.models import Notebook, ResourceNotebook
from products.product_analytics.backend.facade.models import Insight
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.models.table import DataWarehouseTable
class TestCustomerProfileConfigViewSet(APIBaseTest):
@@ -3147,6 +3148,55 @@ class TestAccountMeetingViewSet(APIBaseTest):
],
)
+ @patch("products.customer_analytics.backend.logic.gong.execute_hogql_query")
+ def test_list_includes_the_gong_url_for_a_matching_calendar_event(
+ self, mock_execute_hogql_query: MagicMock
+ ) -> None:
+ account = Account.objects.unscoped().create(team=self.team, name="Acme Corp", external_id="acme-gong")
+ meeting = Meeting.objects.unscoped().create(
+ team=self.team,
+ account=account,
+ ical_uid="[email protected]",
+ recurrence_instance_id="2026-08-03T15:00:00Z",
+ start_time="2026-08-03T15:00:00Z",
+ title="Review",
+ )
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_id="gong-source",
+ connection_id="gong-connection",
+ status="Completed",
+ source_type="Gong",
+ )
+ table = DataWarehouseTable.objects.create(
+ team=self.team,
+ name="gong_calls",
+ format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,
+ url_pattern="https://example.com/gong_calls/*",
+ external_data_source=source,
+ columns={"calendar_event_id": {}, "url": {}},
+ )
+ ExternalDataSchema.objects.create(
+ team=self.team,
+ source=source,
+ table=table,
+ name="calls",
+ should_sync=True,
+ status="Completed",
+ )
+ mock_execute_hogql_query.return_value.results = [
+ [
+ "[email protected]_2026-08-03T15:00:00Z",
+ "https://app.gong.io/call?id=123",
+ ]
+ ]
+
+ 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())
+ self.assertEqual(response.json()["results"][0]["id"], str(meeting.id))
+ self.assertEqual(response.json()["results"][0]["gong_url"], "https://app.gong.io/call?id=123")
+
def test_search_filters_by_title_or_attendee(self):
account = Account.objects.unscoped().create(team=self.team, name="Acme Corp", external_id="acme-2")
review = Meeting.objects.unscoped().create(
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index 24e7799f06d6..932ee2e8398e 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -34,31 +34,31 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc
├── (spend) AccountBillingExpansion kind="spend" (accountBillingLogic — saved billing-spend insights)
└── (opportunities) AccountOpportunitiesExpansion (accountOpportunitiesLogic, keyed by accountId — DWH Salesforce opportunities)
└── (conversations) AccountConversationsExpansion (accountConversationsLogic, keyed by accountId — combines email threads, accessible Support tickets, and Slack summaries; one failed source leaves the other sources usable; email and Slack counts expose a Load older conversations action; expansions paginate email messages, show the Support thread, and keep Slack message links collapsed by default)
- └── (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)
+ └── (meetings) AccountMeetingsExpansion (accountMeetingsLogic, keyed by accountId; synced Google Calendar meetings plus optional Gong call links from the Gong warehouse source, and 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 / native-field / custom-property filters, sort, inline role assignment, typed Postgres list and metrics queries, shareable URL-hash view state, and `openAccount` (the Max entry point). `accountsTableQueryPlan` translates live, saved-view, and URL-restored state into typed references. `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`), Postgres-backed column-picker groups, the per-team saved column config (`columnConfigurations` API), and custom-property definitions. It seeds `propertyDefinitionsModel` so the filter UI resolves per-type operator sets. Warehouse-backed columns and SQL expressions are not offered. |
-| `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`). It translates supported tile definitions into typed Postgres metrics for `accountsLogic.metricsQuery`, then reads the separate metrics data node. 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 in pages of 20 client-side. Both sources include the member's organization access level. The EU view also includes the source Django user ID. Each member carries its source region so staff admin links open the correct user's detail page in the correct cloud. 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. |
-| `accountFeatureRequestsLogic` | Feature requests for one account (keyed by `accountId`): loads linked requests in server pages of five with debounced search, then searches a bounded server page of accessible, editable active requests for the link picker. Request links carry the account's Feature requests deep link as their origin, so the detail breadcrumb returns to the same account tab. The picker exposes load failures with retry guidance and refreshes stale options after optimistic-concurrency conflicts. |
-| `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, preloads each insight result when the account expands, 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). Turning the cadence on with no summaries yet starts `generatingFirstSummary` polling (`startFirstSummaryPolling` / `stopFirstSummaryPolling`, two `cache.disposables` keys) so the backfill the backend kicks off appears without a refresh; the poll deadline lives in a module-level map keyed by account id, because this logic unmounts whenever its row collapses while the backfill keeps running. Distinguishes not-loaded / no-channel-linked / generating / 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. |
-| `accountEmailThreadsLogic` | Matched email communication used by the Conversations tab (keyed by `accountId`): fetches server-paginated summaries from `accountsEmailThreadsList`, keeps one row expanded, and fetches paginated ordered messages through `accountsEmailThreadMessagesList`. The current message page is cached while the row remains expanded; list and detail failures leave explicit retry guidance instead of an infinite skeleton. |
-| `accountConversationsLogic` | The unified Conversations timeline (keyed by `accountId`): loads email, Support, and Slack independently so one denied or failed source does not blank successful sources; merges them newest-first; owns search, source filters, expansion state, Support message loading, and collapsed Slack message links. It preserves email and Slack response counts and loads older source pages on demand instead of silently limiting search to the first 50 rows. |
-| `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 project-admin-gated "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 and editor for one account (keyed by `accountId`). The editor updates `website_domain` and external links through `accountsPartialUpdate` without replacing unrelated account properties. |
+| Logic | Owns |
+| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `accountsLogic` | The hub. Search (debounced), tag / assigned-to/unassigned / native-field / custom-property filters, sort, inline role assignment, typed Postgres list and metrics queries, shareable URL-hash view state, and `openAccount` (the Max entry point). `accountsTableQueryPlan` translates live, saved-view, and URL-restored state into typed references. `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`), Postgres-backed column-picker groups, the per-team saved column config (`columnConfigurations` API), and custom-property definitions. It seeds `propertyDefinitionsModel` so the filter UI resolves per-type operator sets. Warehouse-backed columns and SQL expressions are not offered. |
+| `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`). It translates supported tile definitions into typed Postgres metrics for `accountsLogic.metricsQuery`, then reads the separate metrics data node. 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 in pages of 20 client-side. Both sources include the member's organization access level. The EU view also includes the source Django user ID. Each member carries its source region so staff admin links open the correct user's detail page in the correct cloud. 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. |
+| `accountFeatureRequestsLogic` | Feature requests for one account (keyed by `accountId`): loads linked requests in server pages of five with debounced search, then searches a bounded server page of accessible, editable active requests for the link picker. Request links carry the account's Feature requests deep link as their origin, so the detail breadcrumb returns to the same account tab. The picker exposes load failures with retry guidance and refreshes stale options after optimistic-concurrency conflicts. |
+| `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, preloads each insight result when the account expands, 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). Turning the cadence on with no summaries yet starts `generatingFirstSummary` polling (`startFirstSummaryPolling` / `stopFirstSummaryPolling`, two `cache.disposables` keys) so the backfill the backend kicks off appears without a refresh; the poll deadline lives in a module-level map keyed by account id, because this logic unmounts whenever its row collapses while the backfill keeps running. Distinguishes not-loaded / no-channel-linked / generating / 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. |
+| `accountEmailThreadsLogic` | Matched email communication used by the Conversations tab (keyed by `accountId`): fetches server-paginated summaries from `accountsEmailThreadsList`, keeps one row expanded, and fetches paginated ordered messages through `accountsEmailThreadMessagesList`. The current message page is cached while the row remains expanded; list and detail failures leave explicit retry guidance instead of an infinite skeleton. |
+| `accountConversationsLogic` | The unified Conversations timeline (keyed by `accountId`): loads email, Support, and Slack independently so one denied or failed source does not blank successful sources; merges them newest-first; owns search, source filters, expansion state, Support message loading, and collapsed Slack message links. It preserves email and Slack response counts and loads older source pages on demand instead of silently limiting search to the first 50 rows. |
+| `accountMeetingsLogic` | The Meetings tab (keyed by `accountId`): fetches synced calendar meetings from the generated `accountsMeetingsList` endpoint (customer-analytics facade `list_account_meetings` over the `Meeting` model, populated by the Google Calendar Temporal sync). The endpoint discovers synced Gong `calls` tables and matches `calendar_event_id` to the meeting's iCal UID plus recurrence instance. Matching rows include a validated `gong_url`; the table shows an "Open in Gong" button and records `GongCallOpened`. Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. Also owns the project-admin-gated "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 and editor for one account (keyed by `accountId`). The editor updates `website_domain` and external links through `accountsPartialUpdate` without replacing unrelated account properties. |
## Data & query model
@@ -164,7 +164,7 @@ Like Opportunities, it loads directly in the logic (no embedded query), so the r
The Email threads tab lists matched customer communication from Conversations. `accountEmailThreadsLogic` fetches paginated summaries that include subject, preview, customer participants, owner, message count, and latest activity. Clicking the subject or a participant toggles the thread; the table does not render a separate expansion control. Expanding one row fetches messages in server-bounded pages and renders them in source-timestamp order. The list endpoint never includes message bodies. Both list and detail endpoints require account viewer access plus ticket viewer access because subjects, previews, addresses, and bodies are customer communication. The logic reports unexpected failures without including any email content in analytics or exception metadata.
-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.
+The Meetings tab (flag-gated, `CUSTOMER_ANALYTICS_CSP`) lists the account's synced Google Calendar meetings from the `accounts/:id/meetings` endpoint. The calendar-sync Temporal workflow (`backend/logic/calendar_sync.py`) writes rows from calendars connected in Customer analytics settings and attaches them to an account through known emails, person resolution, and email domains. For each response page, the endpoint checks queryable `calls` tables from synced Gong sources. It joins `calendar_event_id` to the meeting's `ical_uid`, with `_<recurrence_instance_id>` appended for recurring meetings. A matching HTTPS `gong.io` URL appears as an "Open in Gong" button after the meeting name. The optional lookup respects the viewer's warehouse access and does not fail the meetings response when Gong data is unavailable.
`accountMeetingsLogic` owns three states like the Support tickets tab (skeleton on first load / load-failed / "no meetings yet"), plus **server-side pagination and search** (like the Users tab: `page` + `searchTerm` feed the endpoint's `limit`/`offset`/`search` params; search debounces, resets to page 1, and fires `MeetingsSearched`), the **attendee cell** state (first 3 attendees shown, "+N more"/"show less" toggles `expandedAttendeeMeetingIds`; attendees with a resolved `person_id` — populated by the sync via the same HogQL person-email lookup the account matching uses — get a leading `ProfilePicture` (xs, gravatar-by-email) and link to their person page, firing `MeetingAttendeeClicked`; each attendee carries a minimal RSVP glyph after the name — green check accepted, red x declined, muted "?" tentative, nothing for needs_action), and the project-admin-gated **"Edit matching" inline panel**: two `LemonInputSelect` chip inputs editing the account's `email_domains` and `known_emails` properties (normalized, merged into `properties` via `accountsPartialUpdate`, propagated through `accountLinksLogic.loadAccountSuccess`).
The matching editor is deliberately an inline panel above the table, not a dropdown — the `LemonInputSelect` suggestion popover opens below the inputs and would cover Save/Cancel inside a small overlay, so the buttons sit beside the inputs instead.
Saving fires `MeetingMatchingSaved`. Expanding the matching rules enqueues a post-commit task that applies them to unassigned stored meetings without overwriting existing account assignments.
@@ -323,6 +323,7 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions
| `customer analytics account meeting matching saved` | `accountMeetingsLogic` `saveMatching` listener (after the PATCH succeeds) | `domain_count`, `email_count` (no raw domains/emails — customer PII kept out) |
| `customer analytics account meetings searched` | `accountMeetingsLogic` `setSearchTerm` listener (post-debounce) | `has_query`, `query_length` (no raw text) |
| `customer analytics account meeting attendee clicked` | `AccountMeetingsExpansion.tsx` attendee `<Link>` `onClick` (person links only) | _(none — attendee email/person id is customer PII and kept out)_ |
+| `customer analytics account gong call opened` | `AccountMeetingsExpansion.tsx` "Open in Gong" button | _(none; meeting and Gong identifiers stay 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.test.tsx b/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.test.tsx
new file mode 100644
index 000000000000..54a148d772f7
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.test.tsx
@@ -0,0 +1,74 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { Provider } from 'kea'
+import posthog from 'posthog-js'
+
+import { initKeaTests } from '~/test/init'
+
+import { accountsMeetingsList, accountsRetrieve } from 'products/customer_analytics/frontend/generated/api'
+import type { AccountApi, MeetingApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+
+import { AccountMeetingsExpansion } from './AccountMeetingsExpansion'
+import { AccountsEvents } from './constants'
+
+jest.mock('products/customer_analytics/frontend/generated/api', () => ({
+ ...jest.requireActual('products/customer_analytics/frontend/generated/api'),
+ accountsMeetingsList: jest.fn(),
+ accountsRetrieve: jest.fn(),
+}))
+
+const mockList = accountsMeetingsList as jest.MockedFunction<typeof accountsMeetingsList>
+const mockRetrieve = accountsRetrieve as jest.MockedFunction<typeof accountsRetrieve>
+
+class ResizeObserverMock {
+ observe(): void {}
+ unobserve(): void {}
+ disconnect(): void {}
+}
+
+const meeting: MeetingApi = {
+ id: 'meeting-1',
+ title: 'Quarterly review',
+ gong_url: 'https://app.gong.io/call?id=123',
+ start_time: '2026-08-03T15:00:00Z',
+ end_time: '2026-08-03T15:30:00Z',
+ organizer_email: '[email protected]',
+ status: 'confirmed',
+ participants: [],
+}
+
+describe('AccountMeetingsExpansion', () => {
+ beforeAll(() => {
+ ;(global as typeof globalThis & { ResizeObserver: typeof ResizeObserver }).ResizeObserver =
+ ResizeObserverMock as unknown as typeof ResizeObserver
+ })
+
+ beforeEach(() => {
+ initKeaTests()
+ jest.resetAllMocks()
+ jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)
+ mockRetrieve.mockResolvedValue({ id: 'account-1', properties: {} } as AccountApi)
+ mockList.mockResolvedValue({ count: 1, next: null, previous: null, results: [meeting] })
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('opens a matched meeting in Gong', async () => {
+ render(
+ <Provider>
+ <AccountMeetingsExpansion accountId="account-1" />
+ </Provider>
+ )
+
+ const button = await screen.findByText('Open in Gong')
+ expect(button.closest('a')).toHaveAttribute('href', meeting.gong_url)
+ expect(button.closest('td')).toHaveTextContent('Quarterly review')
+ expect(screen.queryByText('Gong')).not.toBeInTheDocument()
+
+ fireEvent.click(button)
+ expect(posthog.capture).toHaveBeenCalledWith(AccountsEvents.GongCallOpened)
+ })
+})
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsx
index dfe276446fab..8b330c49c48f 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsx
@@ -18,6 +18,8 @@ import { BigLeaguesHog } from 'lib/components/hedgehogs'
import { TZLabel } from 'lib/components/TZLabel'
import { urls } from 'scenes/urls'
+import gongIcon from 'public/services/gong.png'
+
import { MeetingApi, MeetingParticipantApi } from 'products/customer_analytics/frontend/generated/api.schemas'
import { accountMeetingsLogic, NOT_LOADED, PAGE_SIZE } from './accountMeetingsLogic'
@@ -172,12 +174,29 @@ export function AccountMeetingsExpansion({ accountId }: { accountId: string }):
{
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>
- ),
+ render: (_, meeting) => (
+ <div className="flex items-center justify-between gap-2">
+ {meeting.title ? (
+ <span className="font-medium line-clamp-1">{meeting.title}</span>
+ ) : (
+ <span className="text-muted italic">Untitled meeting</span>
+ )}
+ {meeting.gong_url && (
+ <LemonButton
+ type="secondary"
+ size="xsmall"
+ to={meeting.gong_url}
+ targetBlank
+ sideIcon={<img src={gongIcon} alt="" className="size-4 object-contain" />}
+ className="shrink-0"
+ data-attr="open-meeting-in-gong"
+ onClick={() => posthog.capture(AccountsEvents.GongCallOpened)} // [PostHog] Event: dynamic event name
+ >
+ Open in Gong
+ </LemonButton>
+ )}
+ </div>
+ ),
},
{
title: 'When',
diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.ts
index 9aead74dfee2..9073b0bd963c 100644
--- a/products/customer_analytics/frontend/components/Accounts/constants.ts
+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts
@@ -60,6 +60,7 @@ export const AccountsEvents = {
MeetingMatchingSaved: 'customer analytics account meeting matching saved',
MeetingsSearched: 'customer analytics account meetings searched',
MeetingAttendeeClicked: 'customer analytics account meeting attendee clicked',
+ GongCallOpened: 'customer analytics account gong call opened',
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.ts
index 02a5df45cdd8..cf7f1b7a7258 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -793,6 +793,11 @@ export interface MeetingApi {
readonly id: string
/** Meeting title; may be empty. */
readonly title: string
+ /**
+ * Gong call URL matched through the calendar event id; null when no Gong call is available.
+ * @nullable
+ */
+ readonly gong_url: string | null
/** When the meeting starts. */
readonly start_time: string
/**
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5b5f6fcf5836..5d4d993cabfe 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -49802,6 +49802,11 @@ export namespace Schemas {
readonly id: string;
/** Meeting title; may be empty. */
readonly title: string;
+ /**
+ * Gong call URL matched through the calendar event id; null when no Gong call is available.
+ * @nullable
+ */
+ readonly gong_url: string | null;
/** When the meeting starts. */
readonly start_time: string;
/**