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(web-analytics): suggest marketing analytics for paid traffic (#110267)

Javier Bahamondes9fc672ec4df2
diff --git a/docs/internal/web-analytics-query-serving.md b/docs/internal/web-analytics-query-serving.md
index da1e37ae801d..2232779310f9 100644
--- a/docs/internal/web-analytics-query-serving.md
+++ b/docs/internal/web-analytics-query-serving.md
@@ -205,3 +205,37 @@ Percentage series contain fractions: a value of `0.42` displays as `42.0%` in th
The chart keeps existing data visible while refreshing and replaces it with the supplied error if the refresh fails.
Storybook covers loading, refreshing, empty results, errors, and a 520 px scene.
The component does not activate the five-section dashboard or change its queries.
+
+## Marketing analytics suggestion
+
+The Sources table can show a dismissible Marketing analytics suggestion behind `web-analytics-marketing-cross-sell`.
+The gate precedes the query and connection loaders, so disabled users incur no additional requests.
+The Channel and all existing UTM table views (source, medium, campaign, content, term, and combined source/medium/campaign) share the dashboard's Channels data node, including its date range, filters, test-account exclusion, comparison and query cache.
+Channel therefore adds no analytics request; a direct visit to a UTM table may load Channels once through the normal optimized query runner.
+The suggestion requires a recognized paid channel with visitors in the current period.
+Organic source names and comparison-only traffic do not qualify.
+This is positive evidence from the returned top channels, not an exhaustive census: paid traffic below the table limit or under an arbitrary custom channel name may not trigger the suggestion.
+
+Connection metadata loads only after that evidence exists, without mounting the Marketing analytics dashboard or running its report queries.
+An enabled native ad integration or an existing external source mapping leads to Marketing analytics; otherwise the link opens source setup when that interface is enabled, or the existing dashboard onboarding flow.
+Sync health remains the destination's responsibility, so a failed integration does not prompt a duplicate connection.
+These table views share the same copy: Connect ad sources for projects without a connection, or Analyze in Marketing analytics for connected projects.
+Loading and failed metadata requests leave the suggestion hidden.
+The destination keeps the date range; Web analytics property filters are not forwarded because Marketing analytics uses a different filter schema.
+An explicit open end date clears any end date saved during a previous Marketing analytics visit.
+Dismissal persists per project in the browser.
+
+### Cross-sell attribution
+
+`web analytics marketing cross sell clicked` records `cross_sell_id`, `cross_sell_clicked_at` (Unix milliseconds), `team_id`, the table breakdown, and whether ad sources were already connected.
+`web analytics marketing cross sell source created` records the same attribution plus `source_id` and `source_type`, only after the source creation API succeeds.
+The model is the first Advertising source created after the latest click within 24 hours, in the same browser tab, project and identified user.
+Session storage preserves the click across a same-tab OAuth redirect and reload; a successful connection consumes it.
+A failed connection retains it for retry. Non-ad connections and flag-off users do not read or consume it.
+Storage restrictions, switching devices or tabs, and later connections can leave conversions unattributed.
+These events use the existing analytics SDK and add no eligibility queries.
+
+Join the attributed `source_id` to source sync usage and the project's billing customer to estimate its share of billed Data warehouse revenue.
+Use billable usage and actual invoice amounts, including free allowances and adjustments; a created source or a click is not revenue.
+Deduplicate source IDs before allocating revenue and keep acquisition (`has_connected_sources = false`) separate from expansion.
+This is click attribution, not proof of incremental revenue. Measure incrementality with a randomized holdout at the billing-customer level so projects from one customer do not appear in both groups.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index bb124fac17fb..a4aed0ee235e 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -14226,6 +14226,30 @@ snapshots:
hash: v1.k794b7964.037f022d2a360a741442b7a7c02748c85c3dfbf3704b127b8c71156e76295083.noiQbmitnbvh8r5QfNWY12cyIEdP8cStss8pv9seKjo
web-analytics-heatmaps-screenshot-cookie-settings--needs-approval--light:
hash: v1.k794b7964.790f27ad4199e77064df360d80709c6f2c6cae2206b587a3aeba135632d66d7e.ffn1fvTuAAz2_7YzsCrcb9VIyMp0THxWP4sLOrkGGNs
+ web-analytics-marketing-cross-sell--campaign--dark:
+ hash: v1.k794b7964.edd43a7156a06c12ceec8ea71c9718327f3167929d3b7ab50dcd10e300b9d04f.5kqj_KsgiThoduLqpsjEDwRs2QS6H64Yq95zqII7sVY
+ web-analytics-marketing-cross-sell--campaign--light:
+ hash: v1.k794b7964.ef64d1faa1a83d051f37ed0644a90b85a773a595f5612e6388d80f2cbc6e34a1.QSJYs-4vsRa0CseVfEwOEz9BoawEy0k6BZC3FGL2ik8
+ web-analytics-marketing-cross-sell--channel--dark:
+ hash: v1.k794b7964.e69c1b9845edf69d54af7325b61a151e0f12ca9eb28f84648bbc5ba1ad85e67d.K-pzHjRE2C0RCBWrXm_10FqwSEoM7rC_FwXcOAeRias
+ web-analytics-marketing-cross-sell--channel--light:
+ hash: v1.k794b7964.723c6519f3d344aa04c195ae7581c6ba82b0110212d8f8815850160bba40c4d4.bcukm2TyFhs8eTjnU3gPVs9TsGTGhL6Bu2ZRPvB0oSA
+ web-analytics-marketing-cross-sell--connected--dark:
+ hash: v1.k794b7964.fc2fef442f4345ba422e637eb3dc0d68fef7e72f6b358f16e51134c20c1008a1.2ES51rrTuzudNi0LmAifk-2KK743-SFCkP1Wvu2Ckeg
+ web-analytics-marketing-cross-sell--connected--light:
+ hash: v1.k794b7964.8a8a90308f0be2d1bd80c4c5347bcd8d3aea9dc22013ed298b79c0526d48b02b.Z4HEZQF-xdUni5ICr1obsxhv22HjJRfbCGNx84vhLec
+ web-analytics-marketing-cross-sell--flag-off--dark:
+ hash: v1.k794b7964.1e9feff8b1812f020d1371412628be1177fb72a3ae4e410e7cd2f54e091bd4dd.dAcvucDrtO-cCd3rYhv3_vSKHNBuM0YPossfojLBU20
+ web-analytics-marketing-cross-sell--flag-off--light:
+ hash: v1.k794b7964.331413229370d9694ab89ec075cc6ed9684b79b2865f65420b7c0ee9b62b5550.BnnflM695jVBZe9LvgqLBL4TRY-leOpd4MyFDhfDuMM
+ web-analytics-marketing-cross-sell--narrow--dark:
+ hash: v1.k794b7964.b9a83798a5b1a438484e5b441f44f609a0b6ae1e40fff93feff341fc948c836a.hb52n0c-0XxcqJONb02W5525mxB13P9ytjDgn826F_8
+ web-analytics-marketing-cross-sell--narrow--light:
+ hash: v1.k794b7964.094424f9b76df8b38ee9b51f81fb179306770369853350d3b678861b4a590c31.QkoIIdNsD89us_lyi5EQ-eAXOva9kVWpcDfMpky7qNY
+ web-analytics-marketing-cross-sell--source--dark:
+ hash: v1.k794b7964.83d29ddaa67d14337789881b7bf81a197f55860fb090a4a720642639bc12fa1a.a2wl_GXLua_s1sEa95lvieBxxe2CrDqxHugdIYS58QA
+ web-analytics-marketing-cross-sell--source--light:
+ hash: v1.k794b7964.d0c0ba256c4baded9b011f6e4fcf2f14025c0f1c51cfa0c7f62b0591b0748c1c.b0FfB_mnvTqcB8OQLrMy2rD_viTA0RhT4uFrpRpILK4
web-analytics-overview-metric-cards--conversion-goal--dark:
hash: v1.k794b7964.0a6a29eef1c3d6ef3a287b530d4bdd7dbcc8cfbf503d54e02bfb5ab96473b6c3.-DSdM2UYxNQisb23WDltH1M71pRcQt2-_YiAhigLzIw
web-analytics-overview-metric-cards--conversion-goal--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 693aa372accb..ad329df5fa22 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -589,6 +589,7 @@ export const FEATURE_FLAGS = {
WEB_ANALYTICS_LIVE_MAP: 'web-analytics-live-map', // owner: @jordanm-posthog #team-web-analytics
WEB_ANALYTICS_LIVE_PERSON_DRILLDOWN: 'web-analytics-live-person-drilldown', // owner: @jordanm-posthog #team-web-analytics
WEB_ANALYTICS_MARKETING: 'marketing-analytics', // owner: @jabahamondes #team-web-analytics
+ WEB_ANALYTICS_MARKETING_CROSS_SELL: 'web-analytics-marketing-cross-sell', // owner: @jabahamondes #team-web-analytics
WEB_ANALYTICS_OPEN_URL: 'web-analytics-open-url', // owner: @lricoy #team-web-analytics
WEB_ANALYTICS_PAGE_PERFORMANCE: 'web-analytics-page-performance', // owner: @jordanm-posthog #team-web-analytics
WEB_ANALYTICS_PRECOMPUTE_TOGGLE: 'web-analytics-precompute-toggle', // owner: @lricoy #team-web-analytics
diff --git a/frontend/src/lib/marketingCrossSell.test.ts b/frontend/src/lib/marketingCrossSell.test.ts
new file mode 100644
index 000000000000..a057b9399f8c
--- /dev/null
+++ b/frontend/src/lib/marketingCrossSell.test.ts
@@ -0,0 +1,73 @@
+import posthog from 'posthog-js'
+
+import { WebStatsBreakdown } from '~/queries/schema/schema-general'
+
+import {
+ captureMarketingCrossSellClick,
+ captureMarketingCrossSellSourceCreated,
+ getMarketingCrossSellAttribution,
+} from './marketingCrossSell'
+
+describe('Marketing cross-sell attribution', () => {
+ beforeEach(() => {
+ sessionStorage.clear()
+ jest.spyOn(posthog, 'get_distinct_id').mockReturnValue('test-user')
+ jest.spyOn(posthog, 'capture').mockClear()
+ jest.spyOn(Date, 'now').mockReturnValue(100000000)
+ })
+ afterEach(() => {
+ jest.restoreAllMocks()
+ sessionStorage.clear()
+ })
+
+ it('links the first source to the latest click and consumes the attribution', () => {
+ captureMarketingCrossSellClick(42, WebStatsBreakdown.InitialChannelType, false)
+ const first = getMarketingCrossSellAttribution(42)!
+ captureMarketingCrossSellClick(42, WebStatsBreakdown.InitialUTMCampaign, true)
+ const latest = getMarketingCrossSellAttribution(42)!
+ expect(latest.cross_sell_id).not.toBe(first.cross_sell_id)
+ captureMarketingCrossSellSourceCreated(first, 'outdated-source', 'GoogleAds')
+ expect(getMarketingCrossSellAttribution(42)).toEqual(latest)
+ captureMarketingCrossSellSourceCreated(latest, 'source-42', 'GoogleAds')
+ captureMarketingCrossSellSourceCreated(latest, 'another-source', 'MetaAds')
+ const conversions = jest
+ .mocked(posthog.capture)
+ .mock.calls.filter(([name]) => name === 'web analytics marketing cross sell source created')
+ expect(conversions).toEqual([
+ [
+ 'web analytics marketing cross sell source created',
+ expect.objectContaining({
+ cross_sell_id: latest.cross_sell_id,
+ team_id: 42,
+ has_connected_sources: true,
+ source_id: 'source-42',
+ source_type: 'GoogleAds',
+ }),
+ ],
+ ])
+ expect(getMarketingCrossSellAttribution(42)).toBeNull()
+ })
+
+ it.each(['another project', 'another user', 'expired', 'future'])('rejects %s attribution', (reason) => {
+ captureMarketingCrossSellClick(42, WebStatsBreakdown.InitialUTMSource, false)
+ if (reason === 'another user') {
+ jest.mocked(posthog.get_distinct_id).mockReturnValue('other-user')
+ } else if (reason === 'expired') {
+ jest.mocked(Date.now).mockReturnValue(100000000 + 24 * 60 * 60 * 1000 + 1)
+ } else if (reason === 'future') {
+ jest.mocked(Date.now).mockReturnValue(99999999)
+ }
+ expect(getMarketingCrossSellAttribution(reason === 'another project' ? 43 : 42)).toBeNull()
+ })
+
+ it('still captures a click when browser storage is unavailable', () => {
+ jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
+ throw new Error('Storage disabled')
+ })
+ expect(() => captureMarketingCrossSellClick(42, WebStatsBreakdown.InitialChannelType, false)).not.toThrow()
+ expect(posthog.capture).toHaveBeenCalledWith(
+ 'web analytics marketing cross sell clicked',
+ expect.objectContaining({ team_id: 42 })
+ )
+ })
+})
diff --git a/frontend/src/lib/marketingCrossSell.ts b/frontend/src/lib/marketingCrossSell.ts
new file mode 100644
index 000000000000..d09f6a0345ca
--- /dev/null
+++ b/frontend/src/lib/marketingCrossSell.ts
@@ -0,0 +1,111 @@
+import posthog from 'posthog-js'
+
+import { uuid } from 'lib/utils/dom'
+
+import { WebStatsBreakdown } from '~/queries/schema/schema-general'
+
+const STORAGE_KEY = 'web-analytics-marketing-cross-sell'
+const ATTRIBUTION_WINDOW_MS = 24 * 60 * 60 * 1000
+const CROSS_SELL_PROPERTIES = {
+ cross_sell_from: 'web_analytics',
+ cross_sell_to: 'marketing_analytics',
+ cross_sell_placement: 'sources_table',
+ cross_sell_variant: 'contextual_card',
+ cross_sell_attribution_model: 'first_ad_source_after_last_click_24h_same_tab',
+}
+
+export interface MarketingCrossSellAttribution {
+ cross_sell_id: string
+ cross_sell_clicked_at: number
+ breakdown: WebStatsBreakdown
+ has_connected_sources: boolean
+ team_id: number
+ distinct_id: string
+}
+
+export function supportsMarketingCrossSell(breakdown: WebStatsBreakdown): boolean {
+ return [
+ WebStatsBreakdown.InitialChannelType,
+ WebStatsBreakdown.InitialUTMSource,
+ WebStatsBreakdown.InitialUTMMedium,
+ WebStatsBreakdown.InitialUTMCampaign,
+ WebStatsBreakdown.InitialUTMContent,
+ WebStatsBreakdown.InitialUTMTerm,
+ WebStatsBreakdown.InitialUTMSourceMediumCampaign,
+ ].includes(breakdown)
+}
+
+export function captureMarketingCrossSellClick(
+ teamId: number,
+ breakdown: WebStatsBreakdown,
+ hasConnectedSources: boolean
+): void {
+ const attribution: MarketingCrossSellAttribution = {
+ cross_sell_id: uuid(),
+ cross_sell_clicked_at: Date.now(),
+ breakdown,
+ has_connected_sources: hasConnectedSources,
+ team_id: teamId,
+ distinct_id: posthog.get_distinct_id(),
+ }
+ try {
+ sessionStorage.setItem(STORAGE_KEY, JSON.stringify(attribution))
+ } catch {
+ // Storage restrictions must not prevent navigation to Marketing analytics.
+ }
+ const { distinct_id: _, ...properties } = attribution
+ posthog.capture('web analytics marketing cross sell clicked', { ...CROSS_SELL_PROPERTIES, ...properties })
+}
+
+export function getMarketingCrossSellAttribution(teamId: number): MarketingCrossSellAttribution | null {
+ try {
+ const saved: Partial<MarketingCrossSellAttribution> = JSON.parse(sessionStorage.getItem(STORAGE_KEY) || 'null')
+ if (
+ !saved ||
+ saved.team_id !== teamId ||
+ saved.distinct_id !== posthog.get_distinct_id() ||
+ typeof saved.cross_sell_id !== 'string' ||
+ typeof saved.cross_sell_clicked_at !== 'number' ||
+ typeof saved.has_connected_sources !== 'boolean' ||
+ !saved.breakdown ||
+ !supportsMarketingCrossSell(saved.breakdown) ||
+ Date.now() < saved.cross_sell_clicked_at ||
+ Date.now() - saved.cross_sell_clicked_at > ATTRIBUTION_WINDOW_MS
+ ) {
+ return null
+ }
+ return {
+ cross_sell_id: saved.cross_sell_id,
+ cross_sell_clicked_at: saved.cross_sell_clicked_at,
+ breakdown: saved.breakdown,
+ has_connected_sources: saved.has_connected_sources,
+ team_id: teamId,
+ distinct_id: saved.distinct_id,
+ }
+ } catch {
+ return null
+ }
+}
+
+export function captureMarketingCrossSellSourceCreated(
+ attribution: MarketingCrossSellAttribution,
+ sourceId: string,
+ sourceType: string
+): void {
+ const current = getMarketingCrossSellAttribution(attribution.team_id)
+ if (current?.cross_sell_id !== attribution.cross_sell_id) {
+ return
+ }
+ try {
+ sessionStorage.removeItem(STORAGE_KEY)
+ } catch {
+ // A successful source connection must not depend on browser storage.
+ }
+ const { distinct_id: _, ...properties } = attribution
+ posthog.capture('web analytics marketing cross sell source created', {
+ ...CROSS_SELL_PROPERTIES,
+ ...properties,
+ source_id: sourceId,
+ source_type: sourceType,
+ })
+}
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts
index ea0f21c34ba1..dcd29564cbd2 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts
@@ -606,6 +606,7 @@ describe('marketingAnalyticsLogic', () => {
await expectLogic(logic, () => logic.actions.setDates('-30d', null)).toFinishAllListeners()
expect(router.values.searchParams).not.toHaveProperty('view')
expect(router.values.searchParams).not.toHaveProperty('breakdown')
+ expect(new URLSearchParams(router.values.location.search).get('date_to')).toBe('')
const filters: WebAnalyticsPropertyFilters = [
{
@@ -633,6 +634,7 @@ describe('marketingAnalyticsLogic', () => {
logic.actions.setDashboardBreakdown(MarketingAnalyticsAttributionBreakdown.Channel)
await expectLogic(logic).toFinishAllListeners()
expect(router.values.searchParams).toMatchObject({ view: 'overview', breakdown: 'channel' })
+ expect(new URLSearchParams(router.values.location.search).get('date_to')).toBe('')
await expectLogic(logic, () =>
router.actions.push(urls.marketingAnalyticsApp(), { view: 'retention', breakdown: 'source' })
@@ -698,6 +700,24 @@ describe('marketingAnalyticsLogic', () => {
}
)
+ it.each([
+ ['?date_from=-7d&date_to=', { dateFrom: '-7d', dateTo: null }],
+ ['?date_from=-7d&date_to=&tab=setup&section=sources', { dateFrom: '-7d', dateTo: null }],
+ ['?date_from=-7d&date_to=-1d', { dateFrom: '-7d', dateTo: '-1d' }],
+ ['', { dateFrom: '-30d', dateTo: '2026-08-31' }],
+ ])('hydrates the date range from "%s" over a saved range', async (search, expected) => {
+ localStorage.setItem(
+ `${MOCK_TEAM_ID}__.scenes.webAnalytics.marketingAnalyticsLogic.dateFilter`,
+ JSON.stringify({ dateFrom: '-30d', dateTo: '2026-08-31', interval: 'day' })
+ )
+ router.actions.push(`${urls.marketingAnalyticsApp()}${search}`)
+
+ logic = marketingAnalyticsLogic()
+ logic.mount()
+
+ await expectLogic(logic).toMatchValues({ dateFilter: expect.objectContaining(expected) })
+ })
+
it.each([
['AppleSearchAds', FEATURE_FLAGS.MARKETING_ANALYTICS_APPLE_ADS],
['OpenAIAds', FEATURE_FLAGS.MARKETING_ANALYTICS_OPENAI_ADS],
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
index e1ddf2a00e72..b9e2e93b5ed1 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
@@ -1029,7 +1029,7 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
return state
}
const dateFrom = params.dateFrom ?? state.dateFrom
- const dateTo = params.dateTo ?? state.dateTo
+ const dateTo = params.dateTo !== undefined ? params.dateTo : state.dateTo
const interval = params.interval ?? state.interval
return { dateFrom, dateTo, interval }
},
@@ -1579,9 +1579,7 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
if (values.dateFilter.dateFrom) {
searchParams.set('date_from', values.dateFilter.dateFrom)
}
- if (values.dateFilter.dateTo) {
- searchParams.set('date_to', values.dateFilter.dateTo)
- }
+ searchParams.set('date_to', values.dateFilter.dateTo ?? '')
if (values.dateFilter.interval) {
searchParams.set('interval', values.dateFilter.interval)
}
@@ -1806,9 +1804,10 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
if (dateFrom) {
params.dateFrom = dateFrom
}
+ // Web analytics writes an open-ended range as an empty `date_to`, which must clear a saved end date.
const dateTo = searchParams.get('date_to')
- if (dateTo) {
- params.dateTo = dateTo
+ if (dateTo !== null) {
+ params.dateTo = dateTo || null
}
const interval = searchParams.get('interval') as IntervalType | null
if (interval) {
diff --git a/frontend/src/scenes/web-analytics/tiles/MarketingAnalyticsCrossSell.test.tsx b/frontend/src/scenes/web-analytics/tiles/MarketingAnalyticsCrossSell.test.tsx
new file mode 100644
index 000000000000..301b793612d8
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/tiles/MarketingAnalyticsCrossSell.test.tsx
@@ -0,0 +1,172 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import posthog from 'posthog-js'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { SourceTab, TileId } from 'scenes/web-analytics/common'
+import { buildDataTableTileDataNodeLogicProps } from 'scenes/web-analytics/tiles/skeletons/useTileSkeletonLoading'
+import { webAnalyticsLogic } from 'scenes/web-analytics/webAnalyticsLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+import { NodeKind, WebStatsBreakdown } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+
+import { MarketingAnalyticsCrossSell } from 'products/web_analytics/frontend/marketing/MarketingAnalyticsCrossSell'
+
+describe('Marketing analytics cross sell', () => {
+ let queries: jest.Mock
+ let sources: jest.Mock
+ let channel = 'Paid Search'
+ let unmount: () => void
+
+ beforeEach(() => {
+ localStorage.clear()
+ posthog.setPersonProperties = jest.fn()
+ channel = 'Paid Search'
+ initKeaTests(true, { ...MOCK_DEFAULT_TEAM, marketing_analytics_config: {} })
+ featureFlagLogic.mount()
+ unmount = webAnalyticsLogic.mount()
+ queries = jest.fn(() => [
+ 200,
+ {
+ columns: ['context.columns.breakdown_value', 'context.columns.visitors'],
+ results: [[channel, [10, null]]],
+ },
+ ])
+ sources = jest.fn(() => [200, { results: [], next: null, count: 0 }])
+ useMocks({
+ post: { '/api/environments/:team_id/query/:kind/': queries },
+ get: { '/api/projects/:team_id/external_data_sources/': sources },
+ })
+ })
+ afterEach(() => {
+ cleanup()
+ unmount()
+ })
+
+ const enable = (setup = false): void => {
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.WEB_ANALYTICS_MARKETING_CROSS_SELL]: true,
+ [FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP]: setup,
+ })
+ }
+
+ const getChannelsNode = (): ReturnType<typeof dataNodeLogic> => {
+ const tile = webAnalyticsLogic.values.tiles.find((tile) => tile.tileId === TileId.SOURCES)
+ const channel = tile?.kind === 'tabs' ? tile.tabs.find((tab) => tab.id === SourceTab.CHANNEL) : undefined
+ if (!channel || channel.query.kind !== NodeKind.DataTableNode) {
+ throw new Error('Sources must contain a Channels table')
+ }
+ return dataNodeLogic(
+ buildDataTableTileDataNodeLogicProps({
+ query: channel.query,
+ insightProps: channel.insightProps,
+ context: { insightProps: channel.insightProps },
+ uniqueKey: `WebAnalytics.${TileId.SOURCES}.${SourceTab.CHANNEL}`,
+ })
+ )
+ }
+
+ it.each([
+ [false, WebStatsBreakdown.InitialChannelType],
+ [true, WebStatsBreakdown.InitialReferringDomain],
+ ])('does no eligibility work with enabled=%s and breakdown=%s', async (enabled, breakdown) => {
+ if (enabled) {
+ enable()
+ }
+ render(<MarketingAnalyticsCrossSell breakdown={breakdown} />)
+ await act(async () => {})
+ expect(screen.queryByText('Connect ad sources')).toBeNull()
+ expect(queries).not.toHaveBeenCalled()
+ expect(sources).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ [false, WebStatsBreakdown.InitialUTMSource],
+ [true, WebStatsBreakdown.InitialUTMMedium],
+ ])('offers source connection with setup flag=%s on %s', async (setup, breakdown) => {
+ enable(setup)
+ render(<MarketingAnalyticsCrossSell breakdown={breakdown} />)
+ const link = (await screen.findByText('Connect ad sources')).closest('a')!
+ const destination = new URL(link.href)
+ expect(destination.searchParams.get('date_from')).toBe('-7d')
+ expect(destination.searchParams.get('date_to')).toBe('')
+ expect(link.getAttribute('href')).toContain('/marketing?')
+ expect(link.getAttribute('href')?.includes('tab=setup')).toBe(setup)
+ expect(queries).toHaveBeenCalledTimes(1)
+ expect(sources).toHaveBeenCalledTimes(1)
+ fireEvent.click(screen.getByLabelText('Dismiss Marketing analytics suggestion'))
+ expect(screen.queryByText('Connect ad sources')).toBeNull()
+ expect(webAnalyticsLogic.values.marketingCrossSellDismissed).toBe(true)
+ })
+
+ it('reuses the mounted Channels query without another analytics request', async () => {
+ enable()
+ const node = getChannelsNode()
+ const unmountNode = node.mount()
+ try {
+ await waitFor(() => expect(node.values.response).not.toBeNull())
+ render(<MarketingAnalyticsCrossSell breakdown={WebStatsBreakdown.InitialChannelType} />)
+ await screen.findByText('Connect ad sources')
+ expect(queries).toHaveBeenCalledTimes(1)
+ } finally {
+ unmountNode()
+ }
+ })
+
+ it('offers analysis for a native ad source on a later page', async () => {
+ enable()
+ sources
+ .mockReturnValueOnce([200, { results: [{ source_type: 'Stripe' }], next: 'next', count: 2 }])
+ .mockReturnValueOnce([200, { results: [{ source_type: 'GoogleAds' }], next: null, count: 2 }])
+ render(<MarketingAnalyticsCrossSell breakdown={WebStatsBreakdown.InitialUTMSourceMediumCampaign} />)
+ const link = (await screen.findByText('Analyze in Marketing analytics')).closest('a')!
+ const destination = new URL(link.href)
+ expect(destination.searchParams.get('date_from')).toBe('-7d')
+ expect(destination.searchParams.get('date_to')).toBe('')
+ expect(sources).toHaveBeenCalledTimes(2)
+ })
+
+ it('does not look up connections for organic traffic', async () => {
+ enable()
+ channel = 'Organic Search'
+ render(<MarketingAnalyticsCrossSell breakdown={WebStatsBreakdown.InitialChannelType} />)
+ const node = getChannelsNode()
+ await waitFor(() => {
+ expect(node.values.responseLoading).toBe(false)
+ expect(node.values.response).toMatchObject({ results: [['Organic Search', [10, null]]] })
+ })
+ expect(queries).toHaveBeenCalledTimes(1)
+ expect(screen.queryByText('Connect ad sources')).toBeNull()
+ expect(sources).not.toHaveBeenCalled()
+ })
+
+ it('keeps the suggestion hidden when the connection check fails', async () => {
+ enable()
+ sources.mockReturnValue([500, { detail: 'Could not load sources' }])
+ render(<MarketingAnalyticsCrossSell breakdown={WebStatsBreakdown.InitialChannelType} />)
+ await waitFor(() => expect(sources).toHaveBeenCalledTimes(1))
+ await act(async () => {})
+ expect(screen.queryByText('Connect ad sources')).toBeNull()
+ expect(screen.queryByText('Analyze in Marketing analytics')).toBeNull()
+ })
+
+ it('refreshes channel evidence when the date changes on a UTM tab', async () => {
+ enable()
+ render(<MarketingAnalyticsCrossSell breakdown={WebStatsBreakdown.InitialUTMSource} />)
+ await screen.findByText('Connect ad sources')
+ const node = getChannelsNode()
+ channel = 'Organic Search'
+ act(() => webAnalyticsLogic.actions.setDates('-14d', null))
+ await waitFor(() => {
+ expect(node.values.responseLoading).toBe(false)
+ expect(node.values.response).toMatchObject({ results: [['Organic Search', [10, null]]] })
+ })
+ expect(screen.queryByText('Connect ad sources')).toBeNull()
+ expect(queries).toHaveBeenCalledTimes(2)
+ expect(sources).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx b/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx
index 90706898b4c4..d70b58e64078 100644
--- a/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx
+++ b/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx
@@ -77,6 +77,7 @@ import { QueryContext, QueryContextColumnComponent, QueryContextColumnTitleCompo
import { ChartDisplayType, InsightLogicProps, PropertyFilterType, PropertyOperator } from '~/types'
import { NewActionButton } from 'products/actions/frontend/components/NewActionButton'
+import { MarketingAnalyticsCrossSell } from 'products/web_analytics/frontend/marketing/MarketingAnalyticsCrossSell'
import { CreateSurveyButton } from '../CrossSellButtons/CreateSurveyButton'
import { ErrorTrackingButton } from '../CrossSellButtons/ErrorTrackingButton'
@@ -1029,6 +1030,7 @@ export const WebStatsTableTile = ({
headerSlot,
uniqueKey,
enablePagination,
+ tileId,
}: QueryWithInsightProps<DataTableNode> & {
breakdownBy: WebStatsBreakdown
control?: JSX.Element
@@ -1213,6 +1215,9 @@ export const WebStatsTableTile = ({
>
<Query uniqueKey={uniqueKey} attachTo={attachTo} query={query} readOnly={true} context={context} />
</WebAnalyticsTileSkeletonGate>
+ {tileId === TileId.SOURCES &&
+ productTab === ProductTab.ANALYTICS &&
+ uniqueKey.startsWith('WebAnalytics.') && <MarketingAnalyticsCrossSell breakdown={breakdownBy} />}
</div>
)
}
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
index dbe177574452..f5be5e451a4c 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
@@ -227,6 +227,7 @@ export interface webAnalyticsLogicValues {
isFocusModeActive: boolean
isGreaterThanMd: boolean
isPathCleaningEnabled: boolean
+ marketingCrossSellDismissed: boolean
pathTab: string
preZoomDateFilter: {
dateFrom: string | null
@@ -356,6 +357,9 @@ export interface webAnalyticsLogicActions {
dismissFocusModeOnboarding: () => {
value: true
}
+ dismissMarketingCrossSell: () => {
+ value: true
+ }
enterFocusMode: () => {
value: true
}
@@ -832,6 +836,7 @@ export const webAnalyticsLogic: LogicWrapper<webAnalyticsLogicType> = kea<webAna
setWebVitalsTab: (tab: WebVitalsMetric) => ({ tab }),
setTileVisualization: (tileId: TileId, visualization: TileVisualizationOption) => ({ tileId, visualization }),
setTileVisibility: (tileId: TileId, visible: boolean) => ({ tileId, visible }),
+ dismissMarketingCrossSell: true,
setHiddenTiles: (hiddenTiles: TileId[]) => ({ hiddenTiles }),
resetTileVisibility: () => true,
openFocusModeModal: (onboarding: boolean = false) => ({ onboarding }),
@@ -1124,6 +1129,11 @@ export const webAnalyticsLogic: LogicWrapper<webAnalyticsLogicType> = kea<webAna
}),
},
],
+ marketingCrossSellDismissed: [
+ false,
+ buildTeamScopedPersistenceConfig(),
+ { dismissMarketingCrossSell: () => true },
+ ],
hiddenTiles: [
[] as TileId[],
persistConfig,
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
index aecba92bad8b..ecf4b84853b9 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
@@ -12,6 +12,7 @@ import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { captureMarketingCrossSellSourceCreated, getMarketingCrossSellAttribution } from 'lib/marketingCrossSell'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
@@ -2202,6 +2203,13 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
return
}
+ const crossSellAttribution =
+ values.featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_MARKETING_CROSS_SELL] === true &&
+ values.selectedConnector.category === 'Advertising' &&
+ values.currentTeamId
+ ? getMarketingCrossSellAttribution(values.currentTeamId)
+ : null
+
try {
const { id } = await api.externalDataSources.create({
...values.source,
@@ -2229,6 +2237,10 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
hasWebhookSchemas: values.hasWebhookSchemas,
})
+ if (crossSellAttribution) {
+ captureMarketingCrossSellSourceCreated(crossSellAttribution, id, values.selectedConnector.name)
+ }
+
tryShowMCPHint('data_warehouse_sources.create', {
derivedPrompt: `Connect a ${values.selectedConnector.name} source`,
})
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
index 2d62750790b4..2d7c2e613b83 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
@@ -1,10 +1,14 @@
import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
import api from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { captureMarketingCrossSellClick, getMarketingCrossSellAttribution } from 'lib/marketingCrossSell'
-import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
+import { ProductIntentContext, ProductKey, WebStatsBreakdown } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import type { ExternalDataSourceSyncSchema, IncrementalField } from '~/types'
@@ -91,6 +95,109 @@ describe('sourceWizardLogic', () => {
}
})
+ describe('marketing cross-sell conversions', () => {
+ beforeEach(() => {
+ sessionStorage.clear()
+ jest.spyOn(posthog, 'get_distinct_id').mockReturnValue('test-user')
+ jest.spyOn(posthog, 'capture').mockClear()
+ jest.spyOn(api.productIntents, 'update').mockResolvedValue(MOCK_DEFAULT_TEAM)
+ featureFlagLogic.mount()
+ })
+ afterEach(() => {
+ sessionStorage.clear()
+ jest.restoreAllMocks()
+ })
+
+ it.each([
+ { enabled: true, category: 'Advertising', attributed: true },
+ { enabled: false, category: 'Advertising', attributed: false },
+ { enabled: true, category: 'Databases', attributed: false },
+ ] as const)(
+ 'attributes success only for eligible sources: $enabled / $category',
+ async ({ enabled, category, attributed }) => {
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.WEB_ANALYTICS_MARKETING_CROSS_SELL]: enabled,
+ })
+ const source = buildSourceConfig({
+ name: category === 'Advertising' ? 'GoogleAds' : 'Postgres',
+ category,
+ })
+ const logic = sourceWizardLogic({
+ availableSources: { [source.name]: source },
+ onComplete: jest.fn(),
+ requiredTables: [],
+ })
+ const unmount = logic.mount()
+ jest.spyOn(api.externalDataSources, 'create').mockResolvedValue({ id: 'test-ad-source' } as Awaited<
+ ReturnType<typeof api.externalDataSources.create>
+ >)
+ try {
+ await expectLogic(logic, () => logic.actions.selectConnector(source)).toFinishAllListeners()
+ captureMarketingCrossSellClick(MOCK_DEFAULT_TEAM.id, WebStatsBreakdown.InitialChannelType, false)
+ const attribution = getMarketingCrossSellAttribution(MOCK_DEFAULT_TEAM.id)!
+ await expectLogic(logic, () => logic.actions.createSource()).toFinishAllListeners()
+ const conversions = jest
+ .mocked(posthog.capture)
+ .mock.calls.filter(([name]) => name === 'web analytics marketing cross sell source created')
+ expect(conversions).toEqual(
+ attributed
+ ? [
+ [
+ 'web analytics marketing cross sell source created',
+ expect.objectContaining({
+ cross_sell_id: attribution.cross_sell_id,
+ source_id: 'test-ad-source',
+ source_type: 'GoogleAds',
+ }),
+ ],
+ ]
+ : []
+ )
+ } finally {
+ unmount()
+ }
+ }
+ )
+
+ it('retains attribution after failure and records conversion after a successful retry', async () => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.WEB_ANALYTICS_MARKETING_CROSS_SELL]: true })
+ const source = buildSourceConfig({ name: 'GoogleAds', category: 'Advertising' })
+ const logic = sourceWizardLogic({
+ availableSources: { GoogleAds: source },
+ onComplete: jest.fn(),
+ requiredTables: [],
+ })
+ const unmount = logic.mount()
+ jest.spyOn(api.externalDataSources, 'create')
+ .mockRejectedValueOnce({ status: 400, message: 'Invalid credentials' })
+ .mockResolvedValueOnce({ id: 'test-ad-source' } as Awaited<
+ ReturnType<typeof api.externalDataSources.create>
+ >)
+ try {
+ await expectLogic(logic, () => logic.actions.selectConnector(source)).toFinishAllListeners()
+ captureMarketingCrossSellClick(MOCK_DEFAULT_TEAM.id, WebStatsBreakdown.InitialUTMCampaign, false)
+ const attribution = getMarketingCrossSellAttribution(MOCK_DEFAULT_TEAM.id)!
+ await expectLogic(logic, () => logic.actions.createSource()).toFinishAllListeners()
+ expect(posthog.capture).not.toHaveBeenCalledWith(
+ 'web analytics marketing cross sell source created',
+ expect.anything()
+ )
+ expect(getMarketingCrossSellAttribution(MOCK_DEFAULT_TEAM.id)).toEqual(attribution)
+ await expectLogic(logic, () => logic.actions.createSource()).toFinishAllListeners()
+ expect(posthog.capture).toHaveBeenCalledWith(
+ 'web analytics marketing cross sell source created',
+ expect.objectContaining({
+ cross_sell_id: attribution.cross_sell_id,
+ source_id: 'test-ad-source',
+ })
+ )
+ expect(getMarketingCrossSellAttribution(MOCK_DEFAULT_TEAM.id)).toBeNull()
+ } finally {
+ unmount()
+ }
+ })
+ })
+
it('shares a single wizard instance across references with the same props', () => {
const postgresSource = buildSourceConfig({ name: 'Postgres' })
const availableSources = { Postgres: postgresSource }
diff --git a/products/web_analytics/frontend/marketing/MarketingAnalyticsCrossSell.stories.tsx b/products/web_analytics/frontend/marketing/MarketingAnalyticsCrossSell.stories.tsx
new file mode 100644
index 000000000000..c2c5ba6c957a
--- /dev/null
+++ b/products/web_analytics/frontend/marketing/MarketingAnalyticsCrossSell.stories.tsx
@@ -0,0 +1,118 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { useValues } from 'kea'
+
+import { LemonTabs } from '@posthog/lemon-ui'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { SourceTab, TileId } from 'scenes/web-analytics/common'
+import { WebQuery } from 'scenes/web-analytics/tiles/WebAnalyticsTile'
+import { webAnalyticsLogic } from 'scenes/web-analytics/webAnalyticsLogic'
+
+import { mswDecorator } from '~/mocks/browser'
+import { WebStatsBreakdown } from '~/queries/schema/schema-general'
+
+function SourcesExample({ tab = SourceTab.CHANNEL }: { tab?: SourceTab }): JSX.Element | null {
+ const { tiles } = useValues(webAnalyticsLogic)
+ const sources = tiles.find((tile) => tile.tileId === TileId.SOURCES)
+ const selected = sources?.kind === 'tabs' ? sources.tabs.find((item) => item.id === tab) : undefined
+ return selected ? (
+ <WebQuery
+ query={selected.query}
+ insightProps={selected.insightProps}
+ tileId={TileId.SOURCES}
+ uniqueKey={`WebAnalytics.${TileId.SOURCES}.${tab}`}
+ headerSlot={
+ <div className="px-4 pt-4">
+ <h3>Sources</h3>
+ <LemonTabs
+ activeKey={tab}
+ tabs={[
+ { key: SourceTab.CHANNEL, label: 'Channel' },
+ { key: SourceTab.UTM_SOURCE, label: 'UTM source' },
+ { key: SourceTab.UTM_CAMPAIGN, label: 'UTM campaign' },
+ ]}
+ />
+ </div>
+ }
+ />
+ ) : null
+}
+
+const meta: Meta<typeof SourcesExample> = {
+ title: 'Web Analytics/Marketing cross sell',
+ component: SourcesExample,
+ parameters: {
+ layout: 'fullscreen',
+ featureFlags: { [FEATURE_FLAGS.WEB_ANALYTICS_MARKETING_CROSS_SELL]: true },
+ },
+ decorators: [
+ (Story) => (
+ <div className="max-w-160 p-4">
+ <Story />
+ </div>
+ ),
+ mswDecorator({
+ post: {
+ '/api/environments/:team_id/query/:kind/': async ({ request }) => {
+ const { query } = (await request.json()) as { query: { breakdownBy: WebStatsBreakdown } }
+ const names =
+ query.breakdownBy === WebStatsBreakdown.InitialUTMSource
+ ? ['google', 'facebook', 'newsletter']
+ : query.breakdownBy === WebStatsBreakdown.InitialUTMCampaign
+ ? ['brand_search', 'product_launch', 'weekly_newsletter']
+ : ['Organic Search', 'Paid Search', 'Direct']
+ return [
+ 200,
+ {
+ columns: [
+ 'context.columns.breakdown_value',
+ 'context.columns.visitors',
+ 'context.columns.views',
+ ],
+ results: names.map((name, index) => [
+ name,
+ [4800 - index * 1200, null],
+ [7200 - index * 1600, null],
+ ]),
+ hasMore: false,
+ },
+ ]
+ },
+ },
+ get: {
+ '/api/projects/:team_id/external_data_sources/': { results: [], next: null, count: 0 },
+ '/api/projects/:team_id/health_issues/': { results: [], next: null, count: 0 },
+ },
+ }),
+ ],
+}
+export default meta
+type Story = StoryObj<typeof SourcesExample>
+export const Channel: Story = {}
+export const Source: Story = { args: { tab: SourceTab.UTM_SOURCE } }
+export const Campaign: Story = { args: { tab: SourceTab.UTM_CAMPAIGN } }
+export const Connected: Story = {
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/external_data_sources/': {
+ results: [{ id: 'example-google-ads', source_type: 'GoogleAds' }],
+ next: null,
+ count: 1,
+ },
+ },
+ }),
+ ],
+}
+export const Narrow: Story = {
+ decorators: [
+ (Story) => (
+ <div className="w-96">
+ <Story />
+ </div>
+ ),
+ ],
+}
+export const FlagOff: Story = {
+ parameters: { featureFlags: { [FEATURE_FLAGS.WEB_ANALYTICS_MARKETING_CROSS_SELL]: false } },
+}
diff --git a/products/web_analytics/frontend/marketing/MarketingAnalyticsCrossSell.tsx b/products/web_analytics/frontend/marketing/MarketingAnalyticsCrossSell.tsx
new file mode 100644
index 000000000000..9d8d7820c037
--- /dev/null
+++ b/products/web_analytics/frontend/marketing/MarketingAnalyticsCrossSell.tsx
@@ -0,0 +1,47 @@
+import { useActions, useValues } from 'kea'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { supportsMarketingCrossSell } from 'lib/marketingCrossSell'
+import { teamLogic } from 'scenes/teamLogic'
+import { SourceTab, TileId } from 'scenes/web-analytics/common'
+import { buildDataTableTileDataNodeLogicProps } from 'scenes/web-analytics/tiles/skeletons/useTileSkeletonLoading'
+import { webAnalyticsLogic } from 'scenes/web-analytics/webAnalyticsLogic'
+
+import { NodeKind, WebStatsBreakdown } from '~/queries/schema/schema-general'
+
+import { MarketingAnalyticsCrossSellCard } from './MarketingAnalyticsCrossSellCard'
+
+export function MarketingAnalyticsCrossSell({ breakdown }: { breakdown: WebStatsBreakdown }): JSX.Element | null {
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { tiles, marketingCrossSellDismissed } = useValues(webAnalyticsLogic)
+ const { dismissMarketingCrossSell } = useActions(webAnalyticsLogic)
+ const { currentTeamId } = useValues(teamLogic)
+
+ if (
+ featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_MARKETING_CROSS_SELL] !== true ||
+ marketingCrossSellDismissed ||
+ !supportsMarketingCrossSell(breakdown)
+ ) {
+ return null
+ }
+ const sources = tiles.find((tile) => tile.tileId === TileId.SOURCES)
+ const channels = sources?.kind === 'tabs' ? sources.tabs.find((tab) => tab.id === SourceTab.CHANNEL) : undefined
+ if (!channels || channels.query.kind !== NodeKind.DataTableNode || !currentTeamId) {
+ return null
+ }
+
+ return (
+ <MarketingAnalyticsCrossSellCard
+ teamId={currentTeamId}
+ breakdown={breakdown}
+ channels={buildDataTableTileDataNodeLogicProps({
+ query: channels.query,
+ insightProps: channels.insightProps,
+ context: { insightProps: channels.insightProps },
+ uniqueKey: `WebAnalytics.${TileId.SOURCES}.${SourceTab.CHANNEL}`,
+ })}
+ onDismiss={dismissMarketingCrossSell}
+ />
+ )
+}
diff --git a/products/web_analytics/frontend/marketing/MarketingAnalyticsCrossSellCard.tsx b/products/web_analytics/frontend/marketing/MarketingAnalyticsCrossSellCard.tsx
new file mode 100644
index 000000000000..00493cfcee40
--- /dev/null
+++ b/products/web_analytics/frontend/marketing/MarketingAnalyticsCrossSellCard.tsx
@@ -0,0 +1,65 @@
+import { useValues } from 'kea'
+
+import { IconArrowRight, IconMegaphone, IconX } from '@posthog/icons'
+import { LemonButton, LemonCard } from '@posthog/lemon-ui'
+
+import { captureMarketingCrossSellClick } from 'lib/marketingCrossSell'
+
+import { WebStatsBreakdown } from '~/queries/schema/schema-general'
+
+import {
+ MarketingAnalyticsCrossSellLogicProps,
+ marketingAnalyticsCrossSellLogic,
+} from './marketingAnalyticsCrossSellLogic'
+
+export function MarketingAnalyticsCrossSellCard({
+ breakdown,
+ onDismiss,
+ ...props
+}: MarketingAnalyticsCrossSellLogicProps & {
+ breakdown: WebStatsBreakdown
+ onDismiss: () => void
+}): JSX.Element | null {
+ const { hasPaidTraffic, hasConnectedSources, hasConnectedSourcesLoading, destination } = useValues(
+ marketingAnalyticsCrossSellLogic(props)
+ )
+ if (!hasPaidTraffic || hasConnectedSources === null || hasConnectedSourcesLoading) {
+ return null
+ }
+ const description = hasConnectedSources
+ ? 'Compare campaign spend with website conversions in Marketing analytics.'
+ : 'Connect your ad sources in Marketing analytics to compare campaign spend with website conversions.'
+
+ return (
+ <div className="border-t p-4 bg-surface-primary rounded-b" data-attr="web-analytics-marketing-cross-sell">
+ <LemonCard hoverEffect={false} className="p-4">
+ <LemonButton
+ className="absolute top-2 right-2"
+ type="tertiary"
+ size="xsmall"
+ icon={<IconX />}
+ aria-label="Dismiss Marketing analytics suggestion"
+ data-attr="web-analytics-marketing-cross-sell-dismiss"
+ onClick={onDismiss}
+ />
+ <div className="flex items-center gap-2 font-semibold pr-6 mb-2">
+ <IconMegaphone className="shrink-0" />
+ <span>Analyze your paid traffic</span>
+ </div>
+ <p className="text-secondary mb-3">{description}</p>
+ <div className="flex">
+ <LemonButton
+ type="secondary"
+ size="small"
+ sideIcon={<IconArrowRight />}
+ to={destination}
+ data-attr="web-analytics-marketing-cross-sell-open"
+ onClick={() => captureMarketingCrossSellClick(props.teamId, breakdown, hasConnectedSources)}
+ >
+ {hasConnectedSources ? 'Analyze in Marketing analytics' : 'Connect ad sources'}
+ </LemonButton>
+ </div>
+ </LemonCard>
+ </div>
+ )
+}
diff --git a/products/web_analytics/frontend/marketing/marketingAnalyticsCrossSellLogic.ts b/products/web_analytics/frontend/marketing/marketingAnalyticsCrossSellLogic.ts
new file mode 100644
index 000000000000..1d73d2e8a4d3
--- /dev/null
+++ b/products/web_analytics/frontend/marketing/marketingAnalyticsCrossSellLogic.ts
@@ -0,0 +1,298 @@
+import {
+ LogicWrapper,
+ MakeLogicType,
+ afterMount,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ propsChanged,
+ selectors,
+} from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+import { getEnabledNativeMarketingSources } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils'
+
+import { DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+import { NativeMarketingSource, WebStatsTableQueryResponse } from '~/queries/schema/schema-general'
+
+import { externalDataSourcesList } from 'products/warehouse_sources/frontend/generated/api'
+
+import type { FeatureFlagsSet } from '../../../../frontend/src/lib/logic/featureFlagLogic'
+import type {
+ ErrorTrackingQueryResponse,
+ HogQLAutocompleteResponse,
+ HogQLMetadataResponse,
+ HogQLQueryResponse,
+ HogQueryResponse,
+ LogAttributesQueryResponse,
+ LogValuesQueryResponse,
+ MetricsQueryResponse,
+ SessionsQueryResponse,
+ TraceSpansAggregationQueryResponse,
+ TraceSpansAttributeBreakdownQueryResponse,
+ TraceSpansQueryResponse,
+ TraceSpansTreeQueryResponse,
+} from '../../../../frontend/src/queries/schema/schema-general'
+import type { TeamPublicType, TeamType } from '../../../../frontend/src/types'
+import { hasPaidChannelTraffic } from './marketingCrossSellUtils'
+
+export interface MarketingAnalyticsCrossSellLogicProps {
+ teamId: number
+ channels: DataNodeLogicProps
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface marketingAnalyticsCrossSellLogicValues {
+ response:
+ | ErrorTrackingQueryResponse
+ | HogQLAutocompleteResponse
+ | HogQLMetadataResponse
+ | HogQLQueryResponse<any[]>
+ | HogQueryResponse
+ | LogAttributesQueryResponse
+ | LogValuesQueryResponse
+ | MetricsQueryResponse
+ | Record<string, any>
+ | SessionsQueryResponse
+ | TraceSpansAggregationQueryResponse
+ | TraceSpansAttributeBreakdownQueryResponse
+ | TraceSpansQueryResponse
+ | TraceSpansTreeQueryResponse
+ | null // dataNodeLogic
+ responseError: string | null // dataNodeLogic
+ responseLoading: boolean // dataNodeLogic
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ currentTeam: TeamPublicType | TeamType | null // teamLogic
+ destination: string
+ hasConnectedSources: boolean | null
+ hasConnectedSourcesLoading: boolean
+ hasPaidTraffic: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface marketingAnalyticsCrossSellLogicActions {
+ loadDataSuccess: (
+ response:
+ | ErrorTrackingQueryResponse
+ | HogQLAutocompleteResponse
+ | HogQLMetadataResponse
+ | HogQLQueryResponse<any[]>
+ | HogQueryResponse
+ | LogAttributesQueryResponse
+ | LogValuesQueryResponse
+ | MetricsQueryResponse
+ | Record<string, any>
+ | SessionsQueryResponse
+ | TraceSpansAggregationQueryResponse
+ | TraceSpansAttributeBreakdownQueryResponse
+ | TraceSpansQueryResponse
+ | TraceSpansTreeQueryResponse
+ | null
+ | undefined,
+ payload?:
+ | {
+ overrideQuery: import('~/queries/schema').DataNode<Record<string, any>> | undefined
+ pollOnly: boolean
+ queryId: string
+ refresh: import('~/queries/schema').RefreshType | undefined
+ }
+ | undefined
+ ) => {
+ payload?: {
+ overrideQuery: import('~/queries/schema').DataNode<Record<string, any>> | undefined
+ pollOnly: boolean
+ queryId: string
+ refresh: import('~/queries/schema').RefreshType | undefined
+ }
+ response:
+ | ErrorTrackingQueryResponse
+ | HogQLAutocompleteResponse
+ | HogQLMetadataResponse
+ | HogQLQueryResponse<any[]>
+ | HogQueryResponse
+ | LogAttributesQueryResponse
+ | LogValuesQueryResponse
+ | MetricsQueryResponse
+ | Record<string, any>
+ | SessionsQueryResponse
+ | TraceSpansAggregationQueryResponse
+ | TraceSpansAttributeBreakdownQueryResponse
+ | TraceSpansQueryResponse
+ | TraceSpansTreeQueryResponse
+ | null
+ | undefined
+ } // dataNodeLogic
+ loadConnectionState: (_: void) => void
+ loadConnectionStateFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadConnectionStateSuccess: (
+ hasConnectedSources: boolean | null,
+ payload?: void
+ ) => {
+ hasConnectedSources: boolean | null
+ payload?: void
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface marketingAnalyticsCrossSellLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ hasPaidTraffic: (
+ response:
+ | ErrorTrackingQueryResponse
+ | HogQLAutocompleteResponse
+ | HogQLMetadataResponse
+ | HogQLQueryResponse<any[]>
+ | HogQueryResponse
+ | LogAttributesQueryResponse
+ | LogValuesQueryResponse
+ | MetricsQueryResponse
+ | Record<string, any>
+ | SessionsQueryResponse
+ | TraceSpansAggregationQueryResponse
+ | TraceSpansAttributeBreakdownQueryResponse
+ | TraceSpansQueryResponse
+ | TraceSpansTreeQueryResponse
+ | null,
+ responseLoading: boolean,
+ responseError: string | null
+ ) => boolean
+ destination: (hasConnectedSources: boolean | null, featureFlags: FeatureFlagsSet, arg: any) => string
+ }
+}
+
+export type marketingAnalyticsCrossSellLogicType = MakeLogicType<
+ marketingAnalyticsCrossSellLogicValues,
+ marketingAnalyticsCrossSellLogicActions,
+ MarketingAnalyticsCrossSellLogicProps,
+ marketingAnalyticsCrossSellLogicMeta
+>
+
+function loadConnectionsIfNeeded({ values, actions }: marketingAnalyticsCrossSellLogicType): void {
+ if (values.hasPaidTraffic && values.hasConnectedSources === null && !values.hasConnectedSourcesLoading) {
+ actions.loadConnectionState()
+ }
+}
+
+export const marketingAnalyticsCrossSellLogic: LogicWrapper<marketingAnalyticsCrossSellLogicType> =
+ kea<marketingAnalyticsCrossSellLogicType>([
+ props({} as MarketingAnalyticsCrossSellLogicProps),
+ key(({ teamId, channels }) => `${teamId}:${channels.key}`),
+ path((key) => ['products', 'webAnalytics', 'marketingAnalyticsCrossSellLogic', key]),
+ connect((props: MarketingAnalyticsCrossSellLogicProps) => ({
+ values: [
+ dataNodeLogic(props.channels),
+ ['response', 'responseLoading', 'responseError'],
+ teamLogic,
+ ['currentTeam'],
+ featureFlagLogic,
+ ['featureFlags'],
+ ],
+ actions: [dataNodeLogic(props.channels), ['loadDataSuccess']],
+ })),
+ loaders(({ props, values }) => ({
+ hasConnectedSources: [
+ null as boolean | null,
+ {
+ loadConnectionState: async (_: void, breakpoint): Promise<boolean | null> => {
+ const mappings = values.currentTeam?.marketing_analytics_config?.sources_map
+ if (mappings && Object.keys(mappings).length > 0) {
+ return true
+ }
+ const enabledSources = getEnabledNativeMarketingSources(values.featureFlags)
+ let offset = 0
+ while (true) {
+ const page = await externalDataSourcesList(String(props.teamId), {
+ limit: 100,
+ offset,
+ }).catch(() => null)
+ breakpoint()
+ if (!page) {
+ return null
+ }
+ if (
+ page.results.some((source) =>
+ enabledSources.includes(source.source_type as NativeMarketingSource)
+ )
+ ) {
+ return true
+ }
+ if (!page.next || page.results.length === 0) {
+ return false
+ }
+ offset += page.results.length
+ }
+ },
+ },
+ ],
+ })),
+ selectors({
+ hasPaidTraffic: [
+ (s) => [s.response, s.responseLoading, s.responseError],
+ (
+ response:
+ | ErrorTrackingQueryResponse
+ | HogQLAutocompleteResponse
+ | HogQLMetadataResponse
+ | HogQLQueryResponse<any[]>
+ | HogQueryResponse
+ | LogAttributesQueryResponse
+ | LogValuesQueryResponse
+ | MetricsQueryResponse
+ | Record<string, any>
+ | SessionsQueryResponse
+ | TraceSpansAggregationQueryResponse
+ | TraceSpansAttributeBreakdownQueryResponse
+ | TraceSpansQueryResponse
+ | TraceSpansTreeQueryResponse
+ | null,
+ loading: boolean,
+ error: string | null
+ ): boolean =>
+ !loading && !error && hasPaidChannelTraffic(response as WebStatsTableQueryResponse | null),
+ ],
+ destination: [
+ (s) => [s.hasConnectedSources, s.featureFlags, (_, props) => props.channels.query],
+ (hasConnectedSources: boolean | null, featureFlags: FeatureFlagsSet, query): string => {
+ const params = new URLSearchParams()
+ if ('dateRange' in query && query.dateRange) {
+ if (query.dateRange.date_from) {
+ params.set('date_from', query.dateRange.date_from)
+ }
+ // An empty value marks an open-ended range, so Marketing analytics drops a saved end date.
+ params.set('date_to', query.dateRange.date_to ?? '')
+ }
+ if (
+ !hasConnectedSources &&
+ (featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP] ||
+ featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD])
+ ) {
+ params.set('tab', 'setup')
+ params.set('section', 'sources')
+ }
+ return `${urls.marketingAnalyticsApp()}?${params.toString()}`
+ },
+ ],
+ }),
+ listeners((logic) => ({
+ loadDataSuccess: () => loadConnectionsIfNeeded(logic),
+ })),
+ propsChanged(({ props }) => {
+ // The Channels table is unmounted on UTM tabs, so it cannot update this shared node.
+ dataNodeLogic(props.channels)
+ }),
+ afterMount(loadConnectionsIfNeeded),
+ ])
diff --git a/products/web_analytics/frontend/marketing/marketingCrossSellUtils.test.ts b/products/web_analytics/frontend/marketing/marketingCrossSellUtils.test.ts
new file mode 100644
index 000000000000..c03919da8588
--- /dev/null
+++ b/products/web_analytics/frontend/marketing/marketingCrossSellUtils.test.ts
@@ -0,0 +1,32 @@
+import { DefaultChannelTypes, WebStatsTableQueryResponse } from '~/queries/schema/schema-general'
+
+import { hasPaidChannelTraffic } from './marketingCrossSellUtils'
+
+describe('paid channel evidence', () => {
+ it.each([
+ [DefaultChannelTypes.PaidSearch, [1, 0], true],
+ [DefaultChannelTypes.PaidSocial, [10, null], true],
+ [DefaultChannelTypes.CrossNetwork, [2, null], true],
+ [DefaultChannelTypes.PaidUnknown, [5, null], true],
+ [DefaultChannelTypes.OrganicSearch, [100, null], false],
+ [DefaultChannelTypes.Direct, [100, null], false],
+ [DefaultChannelTypes.PaidSearch, [0, 50], false],
+ ['google', [100, null], false],
+ ])('classifies %s with visitors %j as %s', (channel, visitors, expected) => {
+ const response: WebStatsTableQueryResponse = {
+ results: [[channel, visitors]],
+ columns: ['context.columns.channel_type', 'context.columns.visitors'],
+ }
+ expect(hasPaidChannelTraffic(response)).toBe(expected)
+ })
+
+ it('requires visitors in the response rather than treating a different metric as evidence', () => {
+ expect(
+ hasPaidChannelTraffic({
+ results: [[DefaultChannelTypes.PaidSearch, [4, null]]],
+ columns: ['channel', 'views'],
+ })
+ ).toBe(false)
+ expect(hasPaidChannelTraffic(null)).toBe(false)
+ })
+})
diff --git a/products/web_analytics/frontend/marketing/marketingCrossSellUtils.ts b/products/web_analytics/frontend/marketing/marketingCrossSellUtils.ts
new file mode 100644
index 000000000000..4fb85fc4333a
--- /dev/null
+++ b/products/web_analytics/frontend/marketing/marketingCrossSellUtils.ts
@@ -0,0 +1,25 @@
+import { DefaultChannelTypes, WebStatsTableQueryResponse } from '~/queries/schema/schema-general'
+
+const PAID_CHANNELS = new Set<string>([
+ DefaultChannelTypes.PaidSearch,
+ DefaultChannelTypes.PaidSocial,
+ DefaultChannelTypes.PaidVideo,
+ DefaultChannelTypes.PaidShopping,
+ DefaultChannelTypes.PaidUnknown,
+ DefaultChannelTypes.CrossNetwork,
+])
+
+export function hasPaidChannelTraffic(response: WebStatsTableQueryResponse | null): boolean {
+ const visitorsIndex = response?.columns?.indexOf('context.columns.visitors') ?? -1
+ if (visitorsIndex < 0) {
+ return false
+ }
+ return !!response?.results.some((row) => {
+ if (!Array.isArray(row) || !PAID_CHANNELS.has(row[0])) {
+ return false
+ }
+ const visitors = row[visitorsIndex]
+ // Comparison-only rows do not establish paid traffic in the selected period.
+ return Array.isArray(visitors) && typeof visitors[0] === 'number' && visitors[0] > 0
+ })
+}