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): add opportunities tab to account details (#66172)

Arthur Moreira de Deus5a5f205909f3
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index b9410892893e..d0e672c506c2 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -8,7 +8,7 @@ This file should carry the full context needed to work here — architecture, da
## What this is
-An **Account** is a customer organization. The list is a HogQL-backed table over the `system.accounts` table, with per-row expansion into Notes / Users / Usage, inline role assignment (CSM, AE, owner), configurable columns, overview metric tiles, shareable views, and a Max (AI) contextual tool for opening accounts.
+An **Account** is a customer organization. The list is a HogQL-backed table over the `system.accounts` table, with per-row expansion into Notes / Users / Usage / Spend / Opportunities, inline role assignment (CSM, AE, owner), configurable columns, overview metric tiles, shareable views, and a Max (AI) contextual tool for opening accounts.
`Account.external_id` is the PostHog **group key** — it's how an account joins to its group-analytics data (usage, events, feature flags). Treat it as the account's analytics identity, not a CRM id (CRM/billing ids live in account properties). The account→group bridge lives in the backend query runner and the agent mode, not here — see [Backend touchpoints](#backend-touchpoints). Keep this mechanism out of any user-facing copy (it's a façade — see the agent mode preset).
@@ -23,10 +23,12 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc
│ "my accounts" on the left, AccountsOverviewTilesButton + AccountsColumnConfigurator on the right
├── AccountsOverviewTiles metric tiles across the filtered set
└── AccountsHogQLTable the DataTable; per-column renderers; controlled row expansion
- └── AccountNotebooksExpansion expanded row: Useful links + LemonTabs(Notes/Users/Usage)
- ├── (notes) paginated/searchable/sortable LemonTable + "New note" button (accountNotebooksLogic, keyed by accountId)
- ├── (users) AccountRelatedUsersExpansion (accountRelatedUsersLogic, keyed by externalId)
- └── (usage) AccountBillingExpansion kind="usage" (accountBillingLogic — a saved billing-usage insight)
+ └── AccountNotebooksExpansion expanded row: Useful links + LemonTabs(Notes/Users/Usage/Spend/Opportunities)
+ ├── (notes) paginated/searchable/sortable LemonTable + "New note" button (accountNotebooksLogic, keyed by accountId)
+ ├── (users) AccountRelatedUsersExpansion (accountRelatedUsersLogic, keyed by externalId)
+ ├── (usage) AccountBillingExpansion kind="usage" (accountBillingLogic — a saved billing-usage insight)
+ ├── (spend) AccountBillingExpansion kind="spend" (accountBillingLogic — saved billing-spend insights)
+ └── (opportunities) AccountOpportunitiesExpansion (accountOpportunitiesLogic, keyed by accountId — DWH Salesforce opportunities)
```
### Logics and what each owns
@@ -40,7 +42,8 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc
| `accountsOverviewTilesLogic` | The overview metric tiles (saved in views via `properties.tiles`); feeds `metrics` into the query. 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`). |
-| `accountBillingLogic` | Billing/usage data behind the Usage tab. |
+| `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. |
+| `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. |
| `accountLinksLogic` | The "Useful links" sidebar for one account (keyed by `accountId`). |
## Data & query model
@@ -56,13 +59,15 @@ Sort safety: removing the sorted column drops the sort (`clearSortIfColumnRemove
## The expanded row
-`AccountsHogQLTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. The body is `AccountNotebooksExpansion`, a `LemonTabs` over `notes` / `users` / `usage` (`AccountExpansionTab`) plus the Useful links sidebar. Active tab comes from `activeTabFor(accountId)` (defaults to `notes`).
+`AccountsHogQLTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. The body is `AccountNotebooksExpansion`, a `LemonTabs` over `notes` / `users` / `usage` / `spend` / `opportunities` (`AccountExpansionTab`) plus the Useful links sidebar. 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 })` and `accountBillingLogic` for both `kind: 'usage'` and `kind: 'spend'`. 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`, `AccountBillingExpansion`) 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 })`, `accountBillingLogic` for both `kind: 'usage'` and `kind: 'spend'`, and `accountOpportunitiesLogic({ 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`, `AccountBillingExpansion`, `AccountOpportunitiesExpansion`) 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` that the embedded `<Query>` mounts inside the tab body, which the root mount does **not** keep alive. So `AccountBillingExpansion` passes `attachTo={accountBillingLogic-instance}` to each `<Query>`: `useAttachedLogic` mounts the query's data logics and attaches them to the (root-mounted) `accountBillingLogic`, so they outlive the `<Query>` unmounting on tab switch and only detach when the row collapses. Without `attachTo`, usage/spend refetch on every return to the tab even with the metadata logic mounted.
+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` that the embedded `<Query>` mounts inside the tab body, which the root mount does **not** keep alive. So `AccountBillingExpansion` passes `attachTo={accountBillingLogic-instance}` to each `<Query>`: `useAttachedLogic` mounts the query's data logics and attaches them to the (root-mounted) `accountBillingLogic`, so they outlive the `<Query>` unmounting on tab switch and only detach when the row collapses. Without `attachTo`, 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 `attachTo`.)
-The Usage tab renders an existing saved billing-usage insight — **point users to it, don't rebuild usage as a new insight.**
+The Usage and Spend tabs render existing saved billing insights — **point users to them, don't rebuild billing as new insights.**
+
+The Opportunities tab lists the account's Salesforce opportunities from the data-warehouse `salesforce.opportunity` table (joined by the account's `sfdc_id`). The query runs in `accountOpportunitiesLogic` rather than via a bare `<Query>` so the tab owns every state: a missing `sfdc_id` shows a "not linked to Salesforce" empty state, and because `salesforce.opportunity` is **production-only**, a failed query degrades to a pretty hog empty state (the error is still captured to PostHog) instead of a red error box. Each opportunity name links to its Salesforce record (`SALESFORCE_ORIGIN/<id>` in `constants.ts`, the same origin the Useful links sidebar uses).
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.
@@ -171,8 +176,9 @@ 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` \| `usage`) |
+| `customer analytics account tab viewed` | `accountsExpansionLogic` `setActiveTab` listener (genuine tab clicks only; programmatic `openAccountTab` navigation does not fire it) | `tab` (`notes` \| `users` \| `usage` \| `spend` \| `opportunities`) |
| `customer analytics account related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ |
+| `customer analytics account opportunity clicked` | `AccountOpportunitiesExpansion.tsx` opportunity name `<Link>` `onClick` | _(none — CRM record id/url kept out)_ |
> **Keep this table up to date.** Whenever you add, rename, or remove a `posthog.capture()` event in the Accounts area — or change its properties — update this table in the same change. An agent reading this file should be able to trust it as the source of truth for what the Accounts list reports.
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx
index 5e68953cc024..a51f8f0b7538 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx
@@ -25,6 +25,8 @@ import { AccountBillingExpansion } from './AccountBillingExpansion'
import { accountBillingLogic } from './accountBillingLogic'
import { accountLinksLogic } from './accountLinksLogic'
import { accountNotebooksLogic } from './accountNotebooksLogic'
+import { AccountOpportunitiesExpansion } from './AccountOpportunitiesExpansion'
+import { accountOpportunitiesLogic } from './accountOpportunitiesLogic'
import { AccountRelatedUsersExpansion } from './AccountRelatedUsersExpansion'
import { accountRelatedUsersLogic } from './accountRelatedUsersLogic'
import { accountsExpansionLogic } from './accountsExpansionLogic'
@@ -106,6 +108,7 @@ export function AccountNotebooksExpansion({
useMountedLogic(accountRelatedUsersLogic({ externalId }))
useMountedLogic(accountBillingLogic({ accountId, externalId, kind: 'usage' }))
useMountedLogic(accountBillingLogic({ accountId, externalId, kind: 'spend' }))
+ useMountedLogic(accountOpportunitiesLogic({ accountId }))
const { setSearchTerm, setSorting, createNote } = useActions(logic)
const { activeTabFor } = useValues(accountsExpansionLogic)
const { setActiveTab } = useActions(accountsExpansionLogic)
@@ -257,6 +260,11 @@ export function AccountNotebooksExpansion({
/>
),
},
+ {
+ key: 'opportunities',
+ label: 'Opportunities',
+ content: <AccountOpportunitiesExpansion accountId={accountId} />,
+ },
]}
/>
</div>
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountOpportunitiesExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountOpportunitiesExpansion.tsx
new file mode 100644
index 000000000000..89ed14a3e043
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/AccountOpportunitiesExpansion.tsx
@@ -0,0 +1,118 @@
+import { useValues } from 'kea'
+import posthog from 'posthog-js'
+
+import { LemonSkeleton, LemonTable, LemonTableColumns, Link } from '@posthog/lemon-ui'
+
+import { BigLeaguesHog } from 'lib/components/hedgehogs'
+import { dayjs } from 'lib/dayjs'
+import { humanFriendlyCurrency } from 'lib/utils/numbers'
+
+import { AccountOpportunity, accountOpportunitiesLogic, NOT_LOADED } from './accountOpportunitiesLogic'
+import { AccountsEvents, SALESFORCE_ORIGIN } from './constants'
+
+function OpportunitiesEmptyState({ 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>
+ )
+}
+
+function OpportunityDate({ value }: { value: string | null }): JSX.Element {
+ if (!value) {
+ return <span className="text-muted">—</span>
+ }
+ const parsed = dayjs(value)
+ return <span>{parsed.isValid() ? parsed.format('MMM D, YYYY') : value}</span>
+}
+
+const columns: LemonTableColumns<AccountOpportunity> = [
+ {
+ title: 'Name',
+ key: 'name',
+ render: (_, opportunity) => (
+ <Link
+ to={`${SALESFORCE_ORIGIN}/${opportunity.id}`}
+ target="_blank"
+ className={opportunity.name ? undefined : 'italic'}
+ onClick={() => posthog.capture(AccountsEvents.OpportunityClicked)}
+ >
+ {opportunity.name || 'Unnamed'}
+ </Link>
+ ),
+ sorter: (a, b) => (a.name ?? '').localeCompare(b.name ?? ''),
+ },
+ {
+ title: 'Credit amount',
+ key: 'totalCreditAmount',
+ align: 'right',
+ render: (_, opportunity) =>
+ opportunity.totalCreditAmount != null ? (
+ humanFriendlyCurrency(opportunity.totalCreditAmount)
+ ) : (
+ <span className="text-muted">—</span>
+ ),
+ sorter: (a, b) => (a.totalCreditAmount ?? 0) - (b.totalCreditAmount ?? 0),
+ },
+ {
+ title: 'Close date',
+ key: 'closeDate',
+ render: (_, opportunity) => <OpportunityDate value={opportunity.closeDate} />,
+ sorter: (a, b) => dayjs(a.closeDate ?? 0).valueOf() - dayjs(b.closeDate ?? 0).valueOf(),
+ },
+ {
+ title: 'Contract start',
+ key: 'contractStartDate',
+ render: (_, opportunity) => <OpportunityDate value={opportunity.contractStartDate} />,
+ sorter: (a, b) => dayjs(a.contractStartDate ?? 0).valueOf() - dayjs(b.contractStartDate ?? 0).valueOf(),
+ },
+]
+
+export function AccountOpportunitiesExpansion({ accountId }: { accountId: string }): JSX.Element {
+ const { opportunitiesResult, opportunitiesResultLoading } = useValues(accountOpportunitiesLogic({ accountId }))
+
+ if (opportunitiesResultLoading || opportunitiesResult === NOT_LOADED) {
+ return <LemonSkeleton className="h-64 w-full" />
+ }
+
+ const { sfdcId, opportunities, loadFailed } = opportunitiesResult
+
+ if (loadFailed) {
+ return (
+ <OpportunitiesEmptyState
+ title="Couldn't load opportunities"
+ detail="Something went wrong loading this account's opportunities. Try refreshing the page."
+ />
+ )
+ }
+
+ if (!sfdcId) {
+ return (
+ <OpportunitiesEmptyState
+ title="Not linked to Salesforce"
+ detail="This account doesn't have a Salesforce ID, so there are no opportunities to show."
+ />
+ )
+ }
+
+ if (!opportunities || opportunities.length === 0) {
+ return (
+ <OpportunitiesEmptyState
+ title="No opportunities yet"
+ detail="We couldn't find any Salesforce opportunities for this account."
+ />
+ )
+ }
+
+ return (
+ <LemonTable<AccountOpportunity>
+ size="small"
+ embedded
+ dataSource={opportunities}
+ columns={columns}
+ rowKey="id"
+ />
+ )
+}
diff --git a/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.ts
index 4d4d23a0b481..0779c3982218 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.ts
@@ -15,12 +15,12 @@ import type {
} from 'products/customer_analytics/frontend/generated/api.schemas'
import type { accountLinksLogicType } from './accountLinksLogicType'
+import { SALESFORCE_ORIGIN } from './constants'
const ORGANIZATION_GROUP_TYPE_INDEX = 0
const REVENUE_DASHBOARD_ID = 259114
const BILLING_ADMIN_ORIGIN = 'https://billing.posthog.com'
const SLACK_ARCHIVES_ORIGIN = 'https://posthog.slack.com/archives'
-const SALESFORCE_ORIGIN = 'https://posthog.my.salesforce.com'
export interface AccountLinksLogicProps {
accountId: string
diff --git a/products/customer_analytics/frontend/components/Accounts/accountOpportunitiesLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountOpportunitiesLogic.test.ts
new file mode 100644
index 000000000000..a37df214be95
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/accountOpportunitiesLogic.test.ts
@@ -0,0 +1,95 @@
+import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
+
+import api from 'lib/api'
+
+import { initKeaTests } from '~/test/init'
+
+import { accountsRetrieve } from 'products/customer_analytics/frontend/generated/api'
+import type { AccountApi, AccountApiProperties } from 'products/customer_analytics/frontend/generated/api.schemas'
+
+import { accountOpportunitiesLogic } from './accountOpportunitiesLogic'
+
+jest.mock('products/customer_analytics/frontend/generated/api', () => ({
+ accountsRetrieve: jest.fn(),
+}))
+
+const mockAccountsRetrieve = accountsRetrieve as jest.MockedFunction<typeof accountsRetrieve>
+
+const buildAccount = (properties: AccountApiProperties): AccountApi =>
+ ({ id: 'acc-1', name: 'Acme', external_id: 'ext-1', properties }) as AccountApi
+
+describe('accountOpportunitiesLogic', () => {
+ let logic: ReturnType<typeof accountOpportunitiesLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ jest.resetAllMocks()
+ jest.spyOn(posthog, 'captureException').mockReturnValue(undefined as any)
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ const mount = async (): Promise<void> => {
+ logic = accountOpportunitiesLogic({ accountId: 'acc-1' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ }
+
+ it('shows the not-linked state and runs no warehouse query when the account has no Salesforce id', async () => {
+ mockAccountsRetrieve.mockResolvedValue(buildAccount({}))
+ const queryMock = jest.spyOn(api, 'query')
+
+ await mount()
+
+ expect(logic.values.opportunitiesResult).toEqual({ sfdcId: null, opportunities: null })
+ expect(queryMock).not.toHaveBeenCalled()
+ })
+
+ it('surfaces a load-failed result (not an infinite skeleton) when the account fetch throws', async () => {
+ mockAccountsRetrieve.mockRejectedValue(new Error('network'))
+ const queryMock = jest.spyOn(api, 'query')
+
+ await mount()
+
+ expect(logic.values.opportunitiesResult).toEqual({ sfdcId: null, opportunities: null, loadFailed: true })
+ expect(queryMock).not.toHaveBeenCalled()
+ })
+
+ it('degrades to a null result instead of throwing when the warehouse query fails', async () => {
+ mockAccountsRetrieve.mockResolvedValue(buildAccount({ sfdc_id: 'sfdc-1' }))
+ jest.spyOn(api, 'query').mockRejectedValue(new Error('Unknown table salesforce.opportunity'))
+
+ await mount()
+
+ expect(logic.values.opportunitiesResult).toEqual({ sfdcId: 'sfdc-1', opportunities: null })
+ })
+
+ it('maps warehouse rows to opportunities preserving column order and nulls', async () => {
+ mockAccountsRetrieve.mockResolvedValue(buildAccount({ sfdc_id: 'sfdc-1' }))
+ jest.spyOn(api, 'query').mockResolvedValue({
+ results: [
+ ['op-1', 'Expansion', 50000, '2024-12-31', '2025-01-15'],
+ ['op-2', null, null, null, null],
+ ],
+ } as any)
+
+ await mount()
+
+ expect(logic.values.opportunitiesResult).toEqual({
+ sfdcId: 'sfdc-1',
+ opportunities: [
+ {
+ id: 'op-1',
+ name: 'Expansion',
+ totalCreditAmount: 50000,
+ closeDate: '2024-12-31',
+ contractStartDate: '2025-01-15',
+ },
+ { id: 'op-2', name: null, totalCreditAmount: null, closeDate: null, contractStartDate: null },
+ ],
+ })
+ })
+})
diff --git a/products/customer_analytics/frontend/components/Accounts/accountOpportunitiesLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountOpportunitiesLogic.ts
new file mode 100644
index 000000000000..4b342bf9ac97
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/accountOpportunitiesLogic.ts
@@ -0,0 +1,102 @@
+import { afterMount, connect, kea, key, path, props } from 'kea'
+import { loaders } from 'kea-loaders'
+import posthog from 'posthog-js'
+
+import api from 'lib/api'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'
+import { hogql } from '~/queries/utils'
+
+import { accountsRetrieve } from 'products/customer_analytics/frontend/generated/api'
+
+import { CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS } from '../../constants'
+import type { accountOpportunitiesLogicType } from './accountOpportunitiesLogicType'
+
+export interface AccountOpportunitiesLogicProps {
+ accountId: string
+}
+
+export interface AccountOpportunity {
+ id: string
+ name: string | null
+ totalCreditAmount: number | null
+ closeDate: string | null
+ contractStartDate: string | null
+}
+
+// Outcomes: a null `sfdcId` means the account isn't linked to Salesforce; `opportunities` is null when the
+// query couldn't run (the data warehouse table only exists in production), as opposed to an empty array
+// (linked account with no opportunities). `loadFailed` is set when the load itself errored (e.g. the
+// account fetch failed) — the view shows a "couldn't load" state rather than hanging on the skeleton.
+export interface AccountOpportunitiesResult {
+ sfdcId: string | null
+ opportunities: AccountOpportunity[] | null
+ loadFailed?: boolean
+}
+
+// Identity used as a "not loaded yet" sentinel by the view — every loaded outcome returns a fresh object.
+export const NOT_LOADED: AccountOpportunitiesResult = { sfdcId: null, opportunities: null }
+
+export const accountOpportunitiesLogic = kea<accountOpportunitiesLogicType>([
+ path((key) => ['scenes', 'customerAnalytics', 'accounts', 'accountOpportunitiesLogic', key]),
+ props({} as AccountOpportunitiesLogicProps),
+ key((props) => props.accountId),
+ connect(() => ({
+ values: [teamLogic, ['currentTeamId']],
+ })),
+ loaders(({ props, values }) => ({
+ opportunitiesResult: [
+ NOT_LOADED,
+ {
+ loadOpportunities: async (): Promise<AccountOpportunitiesResult> => {
+ let sfdcId: string | null
+ try {
+ const account = await accountsRetrieve(String(values.currentTeamId), props.accountId)
+ sfdcId = account.properties?.sfdc_id ?? null
+ } catch (error) {
+ posthog.captureException(error as Error, {
+ scope: 'accountOpportunitiesLogic.loadOpportunities',
+ })
+ return { sfdcId: null, opportunities: null, loadFailed: true }
+ }
+ if (!sfdcId) {
+ return { sfdcId: null, opportunities: null }
+ }
+ try {
+ const response = (await api.query({
+ kind: NodeKind.HogQLQuery,
+ tags: CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS,
+ query: hogql`
+ select id, name, total_credit_amount_c, close_date, contract_start_date_c
+ from salesforce.opportunity
+ where account_id = ${sfdcId}
+ order by close_date desc
+ limit 500
+ `,
+ })) as HogQLQueryResponse
+ const rows = (response.results ?? []) as unknown[][]
+ const opportunities: AccountOpportunity[] = rows.map((row) => ({
+ id: String(row[0]),
+ name: (row[1] as string | null) ?? null,
+ totalCreditAmount: (row[2] as number | null) ?? null,
+ closeDate: (row[3] as string | null) ?? null,
+ contractStartDate: (row[4] as string | null) ?? null,
+ }))
+ return { sfdcId, opportunities }
+ } catch (error) {
+ // `salesforce.opportunity` only exists in production. Elsewhere (and on genuine failures,
+ // which we still report) we degrade to the empty state instead of a red query-error box.
+ posthog.captureException(error as Error, {
+ scope: 'accountOpportunitiesLogic.loadOpportunities',
+ })
+ return { sfdcId, opportunities: null }
+ }
+ },
+ },
+ ],
+ })),
+ afterMount(({ actions }) => {
+ actions.loadOpportunities()
+ }),
+])
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts
index 69454761aea0..ff767f3902b5 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts
@@ -4,9 +4,9 @@ import posthog from 'posthog-js'
import type { accountsExpansionLogicType } from './accountsExpansionLogicType'
import { AccountsEvents } from './constants'
-export type AccountExpansionTab = 'notes' | 'users' | 'usage' | 'spend'
+export type AccountExpansionTab = 'notes' | 'users' | 'usage' | 'spend' | 'opportunities'
-export const ACCOUNT_EXPANSION_TABS: AccountExpansionTab[] = ['notes', 'users', 'usage', 'spend']
+export const ACCOUNT_EXPANSION_TABS: AccountExpansionTab[] = ['notes', 'users', 'usage', 'spend', 'opportunities']
export const DEFAULT_ACCOUNT_TAB: AccountExpansionTab = 'notes'
diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.ts
index eb722f9bc7b9..1d69d0808dce 100644
--- a/products/customer_analytics/frontend/components/Accounts/constants.ts
+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts
@@ -1,5 +1,8 @@
import type { AccountsOverviewTile } from './accountsOverviewTilesLogic'
+// PostHog's Salesforce instance origin; append a record id to deep-link to that record (account or opportunity).
+export const SALESFORCE_ORIGIN = 'https://posthog.my.salesforce.com'
+
export const ACCOUNTS_OVERVIEW_THRESHOLD_OPERATORS = ['>', '>=', '<', '<=', '=', '!='] as const
export type AccountsOverviewThresholdOperator = (typeof ACCOUNTS_OVERVIEW_THRESHOLD_OPERATORS)[number]
@@ -44,4 +47,5 @@ export const AccountsEvents = {
NotesSorted: 'customer analytics accounts notes sorted',
TabViewed: 'customer analytics account tab viewed',
RelatedUserClicked: 'customer analytics account related user clicked',
+ OpportunityClicked: 'customer analytics account opportunity clicked',
} as const