:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(marketing): add source connection panels (#113980)
Javier Bahamondes2b63f8d82780
diff --git a/docs/internal/marketing-source-suggestions.md b/docs/internal/marketing-source-suggestions.mdindex 49b3254c1545..8b31a8b1c565 100644--- a/docs/internal/marketing-source-suggestions.md+++ b/docs/internal/marketing-source-suggestions.md@@ -128,5 +128,15 @@ Table resolution uses schema metadata when available and otherwise recognizes soThe setup plan caches event scans for seven days per project. Explicit refresh requests respect a one-hour cooldown.Source health polling refreshes metadata without forcing every dashboard query.Campaign reporting waits for all required schemas to complete their first sync.++## Source connection components++The integration catalog includes a search field and orders native sources by usage.+Connection panels distinguish scanning, errors, pending first sync, and ready sources.+Search connections use a separate card controlled by `marketing-analytics-organic-keywords`.++Review fixes preserve source data after request failures and provide a retry for connection errors.+Blocked required imports show Needs attention with a Manage source link.+Dashboard dismissals use the shared Setup restore controls.Source refresh failures retain the previous list and allow a later retry.Native source readiness checks include required schema failures and paused imports.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex b269783d9c0d..7ebbd97c95aa 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -12510,6 +12510,54 @@ snapshots:hash: v1.k794b7964.b8c97421239d5053d4ae1f01901a73254eee804c8dd722f71062593004d23422.HCopq5hkJ4Ru-bHW4fdMVo0bK3WC_R-Kn5XZ-NYFPKoscenes-app-marketing-analytics-search-performance--unavailable-sources-narrow--light:hash: v1.k794b7964.7f7d654e0ec8b3c7bd0709a979fce22876760760ccc966528354484f84a5f139.A1RAOnCcgSPTsbI7KQYj06cYSVRXK8cRvdT2bk8SvO4+ scenes-app-marketing-analytics-source-setup-panel--checking--dark:+ hash: v1.k794b7964.e2482a45b6bde3c9a25b044c623ac4b7b540537625e6e63015e9442429fd65c4.BTgrXM0JAVqqP9BCAE-Qowi5Do2MrHMpEHxc7vjh7FI+ scenes-app-marketing-analytics-source-setup-panel--checking--light:+ hash: v1.k794b7964.113e4cece977b97a69d10d29f3f599f1dd78c50fa6a47ea07c23abae84d87814.Kkn_59aBtRD-8-brhcNS_KrHcLR2GOC2bx4N1oH75bg+ scenes-app-marketing-analytics-source-setup-panel--connected--dark:+ hash: v1.k794b7964.732be3ea43b7e25dc56b1be27bdd9ed037afb2ddc0b518e174a49605701cc3db.EQ_IZ7AQm96ZEJDbOGzevvP0Ff8jClK3Qd4MfOmABhc+ scenes-app-marketing-analytics-source-setup-panel--connected--light:+ hash: v1.k794b7964.d5fd784c81780c281b2a97dd94fd7b7184d0e7145c9b805a0588b6820f9c2ee3.h603_-skT-m0K7Rs_sXf7e9nyJHMFOrcCnrRo5x4vh0+ scenes-app-marketing-analytics-source-setup-panel--detected-platforms--dark:+ hash: v1.k794b7964.a433d496a1ab755f9bfd7f681cae9a3b5d3fe385be05c0247587e34969c6b704.cxfjqq7SHEDOc_aldIqwVRlWmBvK0-I4EFXKe-QdhsE+ scenes-app-marketing-analytics-source-setup-panel--detected-platforms--light:+ hash: v1.k794b7964.9ed285fe09a96d1e12deea06cd7bc1f411308f39b016c382fab8a4dabc770649.yMyxS3J1dNGA4cPfPA2r5lgguEasXegAo2KNJVO_VKY+ scenes-app-marketing-analytics-source-setup-panel--detected-platforms-with-search-console--dark:+ hash: v1.k794b7964.acdb951650008dbca61f611105ff1eda391a59fa80d5b2ed5431c240e15ceecc.gBQC6IAAOUjgz2tYN07h3dOLW-CPgvBK27D08iUfb4g+ scenes-app-marketing-analytics-source-setup-panel--detected-platforms-with-search-console--light:+ hash: v1.k794b7964.b433b575cc5192efbe0da5999390af50ae3fc117cdd126be6ddd250663c02522.dcC2BUJjdUSuwzPG-Ymxz-ZN7IVJgRguTi9BdTqVup0+ scenes-app-marketing-analytics-source-setup-panel--dismissed-suggestions--dark:+ hash: v1.k794b7964.26660cc63bc0f512a586cb3b0e7413f186ed15f66fabc08d8492133869bc88da.BX_IRLO-T6q5olDELEnAVGxYFUPNq8wy6BneYPYaRkk+ scenes-app-marketing-analytics-source-setup-panel--dismissed-suggestions--light:+ hash: v1.k794b7964.2113f08ed0121d542c8a8b660bcf286658c745f34926876ac356b5fa66e672a9.hMILKeXW3frlSwmwXkcj-z6UQIqNUjw3EuJTkBvK_fQ+ scenes-app-marketing-analytics-source-setup-panel--missing-connection-action--dark:+ hash: v1.k794b7964.54cd11dbce621cb859dc4cb785eca6d814fa4baf75dc380f8cc0e5216ceacd27.z6GrmpdbkV96JN1tMcCOzHqKEgamGsrJen2qw2cnI0s+ scenes-app-marketing-analytics-source-setup-panel--missing-connection-action--light:+ hash: v1.k794b7964.d088ed403193a8ead59fbc4fb98b6cd98ba0abf60c0f5426974790aaf1e10135.O5CkNdKT2yjIOBuJ0WXEgYe8oi0JO-NES0ai8L7aYsg+ scenes-app-marketing-analytics-source-setup-panel--narrow--dark:+ hash: v1.k794b7964.3ff1f138637c8553c1cd70bf0b0e62a6459b113de29c8864061e6e0a8973293e.PVz6sJC6JGtSB9F2VmnKJkEEavwyNRTBEBIOB74_ZVQ+ scenes-app-marketing-analytics-source-setup-panel--narrow--light:+ hash: v1.k794b7964.b3ebf16acd45236faf74aa0ef613ed8b28a0040d9c56a454b5e2fade0bbcd29c.A7FcZpEHnK3z2NPaFv897HE2kc7Pej8hWBOPDOPWMP0+ scenes-app-marketing-analytics-source-setup-panel--no-detected-platforms--dark:+ hash: v1.k794b7964.eb47e0ad96db7b77346ffaa9044c11d65b8b435d54d000d01c4eae53e071de1d.unZeCAS-WR6sQ2EQlu0W-5boaRQ4bPHXOAapPzI10oY+ scenes-app-marketing-analytics-source-setup-panel--no-detected-platforms--light:+ hash: v1.k794b7964.292f893ea689dffcb048ed33c5ebe268b4a17b5af54d89f22693f8ea1fd3dd97.u7w-5xAg1INsS8gB4aARkhu5UfA6HY-8kxAxquaxeeI+ scenes-app-marketing-analytics-source-setup-panel--paused-import--dark:+ hash: v1.k794b7964.8c5a0638f96e39480fa02da9424c4210c6e80f9822be12cb78366838e03e620f.b16hG257B5NMf9DjA9jSJwUpDXL282DuLI-TqD8x7xg+ scenes-app-marketing-analytics-source-setup-panel--paused-import--light:+ hash: v1.k794b7964.7ca3b039d52e3362db68850832c80afa6bb6919c52e3e51ea566c99da06291dd.wfuQwIQhMRBUl8kKNn6A8FylyihQmMKN2lqDh8m_RNM+ scenes-app-marketing-analytics-source-setup-panel--scan-failed--dark:+ hash: v1.k794b7964.721e0975ade171cc9f6b7c99e6ceedb1e60ba689ebaa882d77031b5e897818a8.7hKx6cAXmesI_Roz5KjggrqjCEFv2r9brpCIRSGBU1w+ scenes-app-marketing-analytics-source-setup-panel--scan-failed--light:+ hash: v1.k794b7964.3f066ce224fb02b6e496b91bdbd43f933a5e5ace031d32df2e52947600f81ebe.XNtWDbjrUrWGUxqtKnLF9A4wIV0ZqUorJ5yTrA3zO3Q+ scenes-app-marketing-analytics-source-setup-panel--scanning--dark:+ hash: v1.k794b7964.fa8710349969f0a6b889e959b38c9f5d8e1f3afb2a5adbf8a07f89efe618a439.5l0L1traRPl_2LQVzJt23bVvn-bO2n9L3Q_rrbko6xw+ scenes-app-marketing-analytics-source-setup-panel--scanning--light:+ hash: v1.k794b7964.000639e282c974aa4126a628b7650c8ed62d0d0647e5fbe91d40ef8ae6b55732.XQgUutlUjFgA1LQvwbTUQt39Xu5rmU4xqzjBgq3LXcE+ scenes-app-marketing-analytics-source-setup-panel--syncing--dark:+ hash: v1.k794b7964.0e2e8e96522bab33a4e9f4811ba33371dbd9b7fe2b7cf2b5300b5a9cde678b9c.gK-Ox4DSZNCsrnf6NSLxvgbSMZU0xYoC-PiGqQWQNUY+ scenes-app-marketing-analytics-source-setup-panel--syncing--light:+ hash: v1.k794b7964.c5730531ed4e733d97f26776040dd18a79139365266f37e3d7c6a99e86f02450.INDn_3RmPnM2E1qJWNKPz6RYhOai_wWahPwnQZ5cGT8scenes-app-marketing-analytics-source-status--source-issues--dark:hash: v1.k794b7964.f387ac40dbf399676c91b2f6de86c2b169e9aaa86205af692abf51a141ead5d7.3PpHqWiSeMKvXuYLv4lU1yM_tqF38xD4NiUkUX6XW2Uscenes-app-marketing-analytics-source-status--source-issues--light:diff --git a/frontend/src/scenes/marketing-analytics/Setup/SetupTab.tsx b/frontend/src/scenes/marketing-analytics/Setup/SetupTab.tsxindex 63421aee77d0..1020116e5d57 100644--- a/frontend/src/scenes/marketing-analytics/Setup/SetupTab.tsx+++ b/frontend/src/scenes/marketing-analytics/Setup/SetupTab.tsx@@ -46,9 +46,17 @@ export function SetupTab(): JSX.Element {const { featureFlags } = useValues(featureFlagLogic)const { setupSection } = useValues(marketingAnalyticsLogic)const { setSetupSection } = useActions(marketingAnalyticsLogic)- const { setupPlan, visibleSuggestions, reviewingSuggestion, isReviewingBatch, safeBatch, applyingIds } =- useValues(setupPlanLogic)- const { loadSetupPlan, reviewSuggestion, confirmReviewedSuggestion, confirmReviewedBatch } =+ const {+ setupPlan,+ setupPlanLoading,+ sourceScanDisabledReason,+ visibleSuggestions,+ reviewingSuggestion,+ isReviewingBatch,+ safeBatch,+ applyingIds,+ } = useValues(setupPlanLogic)+ const { loadSetupPlan, rescanSources, reviewSuggestion, confirmReviewedSuggestion, confirmReviewedBatch } =useActions(setupPlanLogic)const { integrationSettingsModal, setupEntryPointLabel } = useValues(marketingAnalyticsSettingsLogic)const { closeIntegrationSettingsModal } = useActions(marketingAnalyticsSettingsLogic)@@ -113,6 +121,17 @@ export function SetupTab(): JSX.Element {{/* Skipped for "Suggested setup", which renders the whole ranked listitself and would otherwise show everything twice. */}{active.key !== SetupSection.SUGGESTIONS && <SectionSuggestions section={active.key} />}+ {active.key === SetupSection.SOURCES && (+ <LemonButton+ size="small"+ loading={setupPlanLoading}+ onClick={rescanSources}+ disabledReason={sourceScanDisabledReason}+ data-attr="marketing-sources-rescan"+ >+ Scan events again+ </LemonButton>+ )}{active.content}</div>diff --git a/products/marketing_analytics/frontend/dashboard/SearchConsoleSource.tsx b/products/marketing_analytics/frontend/dashboard/SearchConsoleSource.tsxnew file mode 100644index 000000000000..6d7ba649c60b--- /dev/null+++ b/products/marketing_analytics/frontend/dashboard/SearchConsoleSource.tsx@@ -0,0 +1,107 @@+import { useActions, useValues } from 'kea'++import * as magnifyingGlass from '@posthog/brand/hoggies/png/magnifying-glass'+import { LemonBanner, LemonButton, LemonCard, LemonTag, Spinner } from '@posthog/lemon-ui'++import { pngHoggie } from 'lib/brand/hoggies'+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'+import { FEATURE_FLAGS, TeamMembershipLevel } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { urls } from 'scenes/urls'+import { marketingAnalyticsLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'++import { SourceIcon } from 'products/data_warehouse/frontend/shared/components/SourceIcon'+import { sourcesDataLogic } from 'products/data_warehouse/frontend/shared/logics/sourcesDataLogic'++const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlass)++export function SearchConsoleSource(): JSX.Element | null {+ const { featureFlags } = useValues(featureFlagLogic)+ const { dataWarehouseSources } = useValues(marketingAnalyticsLogic)+ const { sourcesLoadError, dataWarehouseSourcesLoading } = useValues(sourcesDataLogic)+ const { loadSources } = useActions(sourcesDataLogic)+ const restrictedReason = useRestrictedArea({+ scope: RestrictionScope.Project,+ minimumAccessLevel: TeamMembershipLevel.Admin,+ })+ if (!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]) {+ return null+ }+ if (!dataWarehouseSources) {+ return (+ <section className="max-w-3xl w-full mx-auto mt-8 mb-6">+ <h2 className="mb-4">Search performance</h2>+ {sourcesLoadError ? (+ <LemonBanner+ type="error"+ action={{ children: 'Try again', onClick: loadSources, loading: dataWarehouseSourcesLoading }}+ >+ Could not check your search connections. Try again to load your sources.+ </LemonBanner>+ ) : (+ <LemonCard hoverEffect={false}>+ <div className="flex items-start gap-4" role="status">+ <Spinner className="mt-1 shrink-0" />+ <div className="min-w-0 flex-1">+ <h3 className="mb-2">Checking your search connections</h3>+ <p className="text-secondary mb-0">Looking for connected search sources.</p>+ </div>+ </div>+ </LemonCard>+ )}+ </section>+ )+ }+ const sources = [+ { type: 'GoogleAds', name: 'Google Ads' },+ { type: 'BingAds', name: 'Bing Ads' },+ { type: 'GoogleSearchConsole', name: 'Google Search Console' },+ ].map((source) => ({+ ...source,+ connected: dataWarehouseSources?.results.some((connection) => connection.source_type === source.type),+ }))+ return (+ <section className="max-w-3xl w-full mx-auto mt-8 mb-6">+ <h2 className="mb-4">Search performance</h2>+ <LemonCard hoverEffect={false} className="space-y-4" data-attr="marketing-search-console-extra">+ <div className="flex items-start gap-4">+ <div className="min-w-0 flex-1">+ <h3 className="mb-2">Connect your search sources</h3>+ <p className="text-secondary text-sm mb-0">+ Google Search Console shows organic queries, landing pages and average positions. Connect+ Google Ads or Bing Ads to compare paid keywords with organic queries and use spend and+ conversion data to guide your search ad decisions.+ </p>+ </div>+ <HedgehogMagnifyingGlass className="w-20 shrink-0" />+ </div>+ <div className="divide-y">+ {sources.map((source) => (+ <div key={source.type} className="flex flex-wrap items-center justify-between gap-3 py-2">+ <div className="min-w-0 flex items-center gap-3">+ <SourceIcon type={source.type} size="small" disableTooltip />+ <strong>{source.name}</strong>+ {source.connected && <LemonTag type="info">Connected</LemonTag>}+ </div>+ {!source.connected && (+ <LemonButton+ type="secondary"+ size="small"+ disabledReason={restrictedReason}+ to={urls.dataWarehouseSourceNew(+ source.type,+ urls.marketingAnalyticsApp(),+ 'Marketing analytics'+ )}+ targetBlank+ >+ Connect+ </LemonButton>+ )}+ </div>+ ))}+ </div>+ </LemonCard>+ </section>+ )+}diff --git a/products/marketing_analytics/frontend/dashboard/SourceOnboardingScan.tsx b/products/marketing_analytics/frontend/dashboard/SourceOnboardingScan.tsxnew file mode 100644index 000000000000..3e483b7b355c--- /dev/null+++ b/products/marketing_analytics/frontend/dashboard/SourceOnboardingScan.tsx@@ -0,0 +1,62 @@+import { LemonButton } from '@posthog/lemon-ui'++import type { Suggestion } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'++import { SourceSetupPanel } from './SourceSetupPanel'++export interface SourceOnboardingScanProps {+ dismissed?: boolean+ onRestore?: () => void+ loading: boolean+ failed: boolean+ suggestions: Suggestion[]+ onManual: () => void+ onContinue: () => void+ onRescan: () => void+ rescanLoading?: boolean+ rescanDisabledReason?: string | null+}++export function SourceOnboardingScan({+ dismissed,+ onRestore,+ loading,+ failed,+ suggestions,+ onManual,+ onContinue,+ onRescan,+ rescanLoading,+ rescanDisabledReason,+}: SourceOnboardingScanProps): JSX.Element {+ return (+ <SourceSetupPanel+ state={+ loading+ ? 'scanning'+ : failed+ ? 'error'+ : suggestions.length+ ? 'suggestions'+ : dismissed+ ? 'dismissed'+ : 'empty'+ }+ suggestions={suggestions}+ onRestore={onRestore}+ onRetry={onRescan}+ rescanLoading={rescanLoading}+ rescanDisabledReason={rescanDisabledReason}+ footer={+ <>+ <LemonButton onClick={onManual} data-attr="marketing-onboarding-add-manually">+ Skip and add manually+ </LemonButton>+ <LemonButton type="secondary" onClick={onContinue} data-attr="marketing-onboarding-continue">+ Continue to dashboard+ </LemonButton>+ </>+ }+ />+ )+}diff --git a/products/marketing_analytics/frontend/dashboard/SourceSetupPanel.stories.tsx b/products/marketing_analytics/frontend/dashboard/SourceSetupPanel.stories.tsxnew file mode 100644index 000000000000..ecbb3f211907--- /dev/null+++ b/products/marketing_analytics/frontend/dashboard/SourceSetupPanel.stories.tsx@@ -0,0 +1,158 @@+import type { Meta, StoryObj } from '@storybook/react'+import { within } from '@testing-library/dom'++import { LemonButton } from '@posthog/lemon-ui'++import { FEATURE_FLAGS } from 'lib/constants'++import { mswDecorator } from '~/mocks/browser'++import { expect } from 'storybook/test'++import { SearchConsoleSource } from './SearchConsoleSource'+import { SourceSetupPanel } from './SourceSetupPanel'++const meta: Meta<typeof SourceSetupPanel> = {+ title: 'Scenes-App/Marketing Analytics/Source setup panel',+ component: SourceSetupPanel,+ parameters: { layout: 'padded', mockDate: '2026-10-07', testOptions: { waitForLoadersToDisappear: false } },+ decorators: [+ mswDecorator({+ get: {+ '/api/environments/:team_id/external_data_sources/wizard/': () => [+ 200,+ {+ GoogleAds: { iconPath: '/static/services/google-ads.png' },+ BingAds: { iconPath: '/static/services/bing-ads.svg' },+ MetaAds: { iconPath: '/static/services/meta-ads.png' },+ GoogleSearchConsole: { iconPath: '/static/services/google-search-console.svg' },+ },+ ],+ },+ }),+ ],+}+export default meta++type Story = StoryObj<typeof SourceSetupPanel>+const suggestions = ['GoogleAds', 'MetaAds'].map((kind) => ({+ id: `connect_source:${kind}`,+ kind: 'connect_source' as const,+ integration: kind,+ severity: 'warning' as const,+ confidence: 1,+ source: 'deterministic' as const,+ title: kind === 'GoogleAds' ? 'Connect Google Ads' : 'Connect Meta Ads',+ evidence:+ kind === 'GoogleAds'+ ? 'Events contain Google Ads campaign tracking in utm_source and gclid.'+ : 'Events contain Meta Ads campaign tracking in utm_source and fbclid.',+ unlocks: ['cost' as const],+ apply: { op: 'open_source_wizard' as const, kind },+ also_recommended: [],+ safe_to_batch: false,+ rank_score: 1,+ deep_link: null,+ docs_url: null,+ spend_at_risk: 0,+ event_volume: 12,+}))+const footer = <LemonButton>Browse integrations</LemonButton>+export const Checking: Story = { args: { state: 'checking' } }+export const Scanning: Story = { args: { state: 'scanning', footer } }+export const DetectedPlatforms: Story = { args: { state: 'suggestions', suggestions, footer } }+export const NoDetectedPlatforms: Story = { args: { state: 'empty', footer } }+export const ScanFailed: Story = { args: { state: 'error', onRetry: () => {}, footer } }+export const Connected: Story = {+ args: {+ state: 'waiting',+ connections: [+ {+ id: 'demo-google',+ name: 'Google Ads',+ sourceType: 'GoogleAds',+ status: 'Connected',+ detail: 'Waiting for the first sync to finish.',+ },+ ],+ suggestions: [suggestions[1]],+ footer: <LemonButton>Browse integrations</LemonButton>,+ },+}+export const Syncing: Story = {+ args: {+ state: 'waiting',+ connections: [+ {+ id: 'demo-google',+ name: 'Google Ads',+ sourceType: 'GoogleAds',+ status: 'Syncing',+ detail: 'Your first import is running. Spend data will appear when it finishes.',+ },+ ],+ suggestions: [suggestions[1]],+ footer: <LemonButton>Browse integrations</LemonButton>,+ },+}+export const Narrow: Story = {+ args: DetectedPlatforms.args,+ decorators: [+ (Story) => (+ <div className="max-w-lg">+ <Story />+ </div>+ ),+ ],+}++export const DetectedPlatformsWithSearchConsole: Story = {+ decorators: [+ (Story) => (+ <>+ <Story />+ <SearchConsoleSource />+ </>+ ),+ ],+ args: DetectedPlatforms.args,+ parameters: { featureFlags: [FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS] },+}++export const MissingConnectionAction: Story = {+ args: { state: 'suggestions', suggestions: [{ ...suggestions[0], apply: null }], footer },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ expect(await canvas.findByText('Google Ads')).toBeVisible()+ expect(canvas.queryByRole('link', { name: 'Connect' })).not.toBeInTheDocument()+ },+}++export const DismissedSuggestions: Story = {+ args: { state: 'dismissed', onRestore: () => {}, footer },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ expect(await canvas.findByRole('button', { name: 'Restore suggestions' })).toBeVisible()+ expect(canvas.queryByText(/No ad platforms were detected/)).not.toBeInTheDocument()+ },+}+export const PausedImport: Story = {+ args: {+ state: 'waiting',+ connections: [+ {+ id: 'example-paused',+ name: 'Google Ads',+ sourceType: 'GoogleAds',+ status: 'Needs attention',+ detail: 'The import is paused or canceled. Open setup to resume it.',+ },+ ],+ footer,+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ expect(await canvas.findByText('Some connections need attention')).toBeVisible()+ expect(canvas.getByRole('link', { name: /Manage source/ })).toBeVisible()+ },+}diff --git a/products/marketing_analytics/frontend/dashboard/SourceSetupPanel.tsx b/products/marketing_analytics/frontend/dashboard/SourceSetupPanel.tsxnew file mode 100644index 000000000000..d47506214676--- /dev/null+++ b/products/marketing_analytics/frontend/dashboard/SourceSetupPanel.tsx@@ -0,0 +1,255 @@+import { useValues } from 'kea'+import type { ReactNode } from 'react'++import * as moneyPng from '@posthog/brand/hoggies/png/money'+import { IconCheckCircle, IconInfo } from '@posthog/icons'+import { LemonButton, LemonCard, LemonCollapse, LemonTag, Spinner } from '@posthog/lemon-ui'++import { pngHoggie } from 'lib/brand/hoggies'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { urls } from 'scenes/urls'+import type { Suggestion } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'++import { SourceIcon } from 'products/data_warehouse/frontend/shared/components/SourceIcon'++const HedgehogMoney = pngHoggie(moneyPng)++export interface SourceSetupPanelProps {+ state: 'checking' | 'scanning' | 'suggestions' | 'empty' | 'error' | 'waiting' | 'dismissed'+ suggestions?: Suggestion[]+ connections?: {+ id: string+ name: string+ sourceType: string+ status: 'Connected' | 'Syncing' | 'Needs attention'+ detail: string+ }[]+ compact?: boolean+ footer?: ReactNode+ onRetry?: () => void+ rescanLoading?: boolean+ rescanDisabledReason?: string | null+ onDismiss?: (id: string) => void+ onRestore?: () => void+}++export function SourceSetupPanel({+ state,+ suggestions = [],+ connections = [],+ footer,+ compact = false,+ onRetry,+ rescanLoading = false,+ rescanDisabledReason,+ onDismiss,+ onRestore,+}: SourceSetupPanelProps): JSX.Element {+ const { featureFlags } = useValues(featureFlagLogic)+ const busy = state === 'checking' || state === 'scanning'+ const title =+ state === 'checking'+ ? 'Checking your connections'+ : state === 'scanning'+ ? 'Finding your ad platforms'+ : state === 'dismissed'+ ? 'Your suggestions are hidden'+ : state === 'empty'+ ? 'Choose an ad platform'+ : state === 'error'+ ? 'Could not check your events'+ : state === 'waiting'+ ? connections.some((connection) => connection.status === 'Needs attention')+ ? 'Some connections need attention'+ : 'Your connections are getting ready'+ : 'Connect your ad platforms'+ const description =+ state === 'checking'+ ? 'Looking for connected ad platforms.'+ : state === 'scanning'+ ? 'Checking campaign tracking in events from the last 7 days.'+ : state === 'dismissed'+ ? 'You dismissed the detected platforms. Restore your suggestions or choose an integration manually.'+ : state === 'empty'+ ? 'No ad platforms were detected in your latest 7-day event scan. You can choose an integration manually to import spend data.'+ : state === 'error'+ ? 'Try checking your events again, or choose an integration manually.'+ : state === 'waiting'+ ? connections.some((connection) => connection.status === 'Needs attention')+ ? 'Check the connections below to finish setting up your spend data.'+ : 'Spend and ad performance will appear after the first sync finishes. You can connect other platforms while you wait.'+ : `We found campaign tracking from ${suggestions.length} ${suggestions.length === 1 ? 'platform' : 'platforms'} in your latest event scan.`++ return (+ <LemonCard+ hoverEffect={false}+ className={+ compact ? 'w-full mt-6 !p-0 overflow-hidden' : 'max-w-3xl w-full mx-auto mt-6 !p-0 overflow-hidden'+ }+ >+ <div className={compact ? 'p-4 space-y-3' : 'p-6 space-y-5'}>+ {(state === 'scanning' || state === 'suggestions') && (+ <LemonTag type="muted">7-day event scan</LemonTag>+ )}+ <div className="flex items-start gap-4" role={busy ? 'status' : undefined}>+ {busy ? <Spinner className="mt-1 shrink-0" /> : null}+ <div className="min-w-0 flex-1">+ <h3 className="text-xl mb-2">{title}</h3>+ <p className="text-secondary mb-0 max-w-xl">{description}</p>+ </div>+ {!busy && <HedgehogMoney className={compact ? 'w-12 shrink-0' : 'w-20 shrink-0'} />}+ </div>+ {state === 'empty' && (+ <p className="text-secondary text-sm mb-4">+ Make sure your ad links include UTM parameters, such as utm_source and utm_medium, and that+ PostHog captures them.+ </p>+ )}+ {!busy && !compact && (+ <div className="space-y-1">+ <strong className="text-sm">Your marketing data in one place</strong>+ <p className="text-secondary text-sm mb-0">+ Compare campaign performance across your marketing sources. Use PostHog events as conversion+ goals to measure conversion costs and ROAS.+ </p>+ {featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS] && (+ <p className="text-secondary text-sm mb-0">+ Compare paid keywords and organic search queries to optimize your search ads.+ </p>+ )}+ </div>+ )}+ {connections.length > 0 && (+ <div className="divide-y border-t">+ {connections.map((connection) => (+ <div key={connection.id} className="py-4 space-y-2">+ <div className="flex items-center flex-wrap gap-3">+ <SourceIcon type={connection.sourceType} size="small" disableTooltip />+ <strong>{connection.name}</strong>+ <LemonTag type={connection.status === 'Needs attention' ? 'warning' : 'info'}>+ {connection.status}+ </LemonTag>+ </div>+ <p className="text-secondary text-sm mb-0">{connection.detail}</p>+ {connection.status === 'Needs attention' && (+ <LemonButton+ type="secondary"+ size="small"+ to={urls.dataWarehouseSource(connection.id)}+ targetBlank+ >+ Manage source+ </LemonButton>+ )}+ </div>+ ))}+ </div>+ )}+ {suggestions.length > 0 && !busy && (+ <div className="divide-y border-t">+ {suggestions.map((suggestion) => (+ <div key={suggestion.id} className={compact ? 'py-2' : 'py-4'}>+ <div className="flex items-center justify-between flex-wrap gap-3">+ <div className="flex items-center gap-3 min-w-0">+ <SourceIcon+ type={suggestion.apply?.kind as string}+ size="small"+ disableTooltip+ />+ <div>+ <strong>{suggestion.title.replace(/^Connect /, '')}</strong>+ <p className="text-secondary text-sm mb-0">+ {suggestion.event_volume+ ? `Found in ${suggestion.event_volume} events`+ : 'Found in campaign tracking'}+ </p>+ </div>+ </div>+ <div className="flex items-center gap-2">+ {suggestion.apply?.op === 'open_source_wizard' &&+ typeof suggestion.apply.kind === 'string' &&+ suggestion.apply.kind.length > 0 && (+ <LemonButton+ type="primary"+ size="small"+ to={urls.dataWarehouseSourceNew(+ suggestion.apply.kind,+ urls.marketingAnalyticsApp(),+ 'Marketing analytics'+ )}+ targetBlank+ data-attr="marketing-onboarding-connect-source"+ >+ Connect+ </LemonButton>+ )}+ {onDismiss && (+ <LemonButton+ size="small"+ type="tertiary"+ onClick={() => onDismiss(suggestion.id)}+ >+ Dismiss+ </LemonButton>+ )}+ </div>+ </div>+ {!compact && (+ <LemonCollapse+ embedded+ size="small"+ className="mt-2"+ panels={[+ {+ key: suggestion.id,+ header: 'View detection details',+ content: (+ <p className="text-secondary text-sm mb-0">{suggestion.evidence}</p>+ ),+ },+ ]}+ />+ )}+ </div>+ ))}+ </div>+ )}+ {state === 'dismissed' && onRestore && (+ <LemonButton type="secondary" onClick={onRestore}>+ Restore suggestions+ </LemonButton>+ )}+ {!busy && onRetry && (+ <LemonButton+ type="secondary"+ onClick={onRetry}+ loading={rescanLoading}+ disabledReason={rescanDisabledReason}+ data-attr="marketing-onboarding-rescan"+ >+ {state === 'error' ? 'Try again' : 'Scan again'}+ </LemonButton>+ )}+ {!busy && rescanDisabledReason && <p className="text-secondary text-xs mb-0">{rescanDisabledReason}</p>}+ {!busy && !compact && state !== 'error' && state !== 'waiting' && (+ <div className="flex items-start gap-2 text-secondary text-sm">+ <IconInfo className="shrink-0 mt-0.5" />+ <span>Spend data appears after the first sync finishes.</span>+ </div>+ )}+ {state === 'waiting' && connections.some((connection) => connection.status !== 'Needs attention') && (+ <div className="flex items-start gap-2 text-secondary text-sm">+ <IconCheckCircle className="shrink-0 mt-0.5" />+ <span>You can leave this page. Your import will continue in the background.</span>+ </div>+ )}+ </div>+ {footer && (+ <div className="border-t p-4 flex flex-wrap items-center justify-between gap-3 bg-bg-light">+ {footer}+ </div>+ )}+ </LemonCard>+ )+}diff --git a/products/marketing_analytics/frontend/dashboard/detectedSourcesLogic.ts b/products/marketing_analytics/frontend/dashboard/detectedSourcesLogic.tsnew file mode 100644index 000000000000..a9b20358ec2c--- /dev/null+++ b/products/marketing_analytics/frontend/dashboard/detectedSourcesLogic.ts@@ -0,0 +1,118 @@+import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { marketingAnalyticsLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'+import { setupPlanLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'++import { VALID_NATIVE_MARKETING_SOURCES } from '~/queries/schema/schema-general'++import { sourcesDataLogic } from 'products/data_warehouse/frontend/shared/logics/sourcesDataLogic'++type DetectedSourcesProps = { teamId: number }++function loadSetupPlanIfEnabled(teamId: number): void {+ if (+ featureFlagLogic.values.featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING] &&+ teamId &&+ !setupPlanLogic.values.setupPlan &&+ !setupPlanLogic.values.setupPlanLoading+ ) {+ setupPlanLogic.actions.loadSetupPlan()+ }+}++export const detectedSourcesLogic = kea<+ MakeLogicType<+ { notificationDismissed: boolean; dismissedSourceIds: string[]; showIntegrations: boolean },+ {+ setShowIntegrations: (show: boolean) => { show: boolean }+ dismiss: () => { value: true }+ expand: () => { value: true }+ dismissSource: (id: string) => { id: string }+ clearLegacyDismissals: () => { value: true }+ },+ DetectedSourcesProps+ >+>([+ props({} as DetectedSourcesProps),+ key((props) => props.teamId),+ path((key) => ['products', 'marketingAnalytics', 'detectedSources', key]),+ actions({+ setShowIntegrations: (show: boolean) => ({ show }),+ dismiss: true,+ expand: true,+ dismissSource: (id: string) => ({ id }),+ clearLegacyDismissals: true,+ }),+ reducers(({ props }) => ({+ showIntegrations: [false, { setShowIntegrations: (_, { show }) => show }],+ dismissedSourceIds: [+ [] as string[],+ { persist: true, prefix: `${props.teamId}__` },+ { clearLegacyDismissals: () => [] },+ ],+ notificationDismissed: [+ false,+ { persist: true, prefix: `${props.teamId}__` },+ { dismiss: () => true, expand: () => false },+ ],+ })),+ listeners(({ props }) => ({+ dismissSource: ({ id }) => setupPlanLogic.actions.dismissSuggestion(id),+ [setupPlanLogic.actionTypes.loadSetupPlanSuccess]: () => {+ const logic = detectedSourcesLogic({ teamId: props.teamId })+ for (const id of logic.values.dismissedSourceIds) {+ setupPlanLogic.actions.dismissSuggestion(id)+ }+ logic.actions.clearLegacyDismissals()+ },+ // The app can render on the flag timeout, so the onboarding flag may arrive after mount.+ [featureFlagLogic.actionTypes.setFeatureFlags]: () => loadSetupPlanIfEnabled(props.teamId),+ })),+ afterMount(({ props, cache }) => {+ loadSetupPlanIfEnabled(props.teamId)+ cache.disposables.add(() => {+ const refreshSources = (): void => {+ if (!marketingAnalyticsLogic.values.loading) {+ marketingAnalyticsLogic.actions.loadSources()+ }+ }+ window.addEventListener('focus', refreshSources)+ let failures = 0+ let retryAt = 0+ const interval = window.setInterval(() => {+ const { sourcesLoadError, dataWarehouseSources } = sourcesDataLogic.values+ if (sourcesLoadError) {+ if (Date.now() >= retryAt) {+ refreshSources()+ failures += 1+ retryAt = Date.now() + Math.min(30_000 * 2 ** failures, 300_000)+ }+ return+ }+ failures = 0+ retryAt = 0+ const searchEnabled =+ featureFlagLogic.values.featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]+ if (+ dataWarehouseSources?.results.some(+ (source) =>+ (VALID_NATIVE_MARKETING_SOURCES.includes(+ source.source_type as (typeof VALID_NATIVE_MARKETING_SOURCES)[number]+ ) ||+ (source.source_type === 'GoogleSearchConsole' && searchEnabled)) &&+ (source.status === 'Running' ||+ source.schemas.some((schema) => schema.should_sync && schema.status === 'Running'))+ )+ ) {+ refreshSources()+ }+ }, 30000)+ return () => {+ window.removeEventListener('focus', refreshSources)+ window.clearInterval(interval)+ }+ }, 'source-health')+ }),+])