: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 paid and organic search recommendations (#124156)
Javier Bahamondes3a11664e2925
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 8cf3b36a10e9..80325152dbcf 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -13658,6 +13658,26 @@ snapshots:hash: v1.k794b7964.d0baebcb76e75b79c530d73650dd5208357a9224f87a4109366f080451653707.q9XYNba8hsN8JEhhiUrEvUpZyj7Ou_loKi1b3cSWq8Uscenes-app-marketing-analytics-persisted-conversion-recommendations--updating--light:hash: v1.k794b7964.852abfd71814efc870cb2178a7acf97833babbd13866c0196d6976f8351999fb._dZPb-BB_XLmD7aRG3nBiePMXUZOzSzgVTK6xgccsF4+ scenes-app-marketing-analytics-recommendations--missing-tables--dark:+ hash: v1.k794b7964.6cd24dc5daf11984fdc7d5fec2f6577d57a4da1846027abbb2b8f99884408e01.OwDbp2-r9l5KNAL546-J4K3Ksq_aSDhfu2rs2yRJg1I+ scenes-app-marketing-analytics-recommendations--missing-tables--light:+ hash: v1.k794b7964.bea66197d508f7dd5d6106f9726cc55f8f52538fce96e766c0a3967cc66b26aa.t1F-CkQXi5U5UawohTfwB4sk-eyCTzIv_v1xL0mSC0k+ scenes-app-marketing-analytics-recommendations--missing-tables-in-modal--dark:+ hash: v1.k794b7964.59f9d9ec30012f316fd24ea62da8a371328fa7a3021a1eabe44afacf714894b1.nAfvHCex6xJSzBeIhEFA01rBVoHwgSEAEmIVRCUgBx0+ scenes-app-marketing-analytics-recommendations--missing-tables-in-modal--light:+ hash: v1.k794b7964.f55eda3483c05e05dac78ced086f250a782b4f348291ab4877a5a435f61fb69c.eTpnKZ5Z_2pxJmKaOlMQSD3wgy9HD1d8isRjT7JBq0I+ scenes-app-marketing-analytics-recommendations--modal--dark:+ hash: v1.k794b7964.912485b9ea2606940db74c824e0e19607c42b51099ee2f4a28e0550ed49fd972.iT4FxMcmuLx7AAhxnwWlgIUL-oq_r6S0UiW8UhzpRFM+ scenes-app-marketing-analytics-recommendations--modal--light:+ hash: v1.k794b7964.c04f2966e2cc693edb8a6594142f2b32664619e532b659bb01ceec6a6c71e8a0.10rYCjA5Qfk5wA1lJ_--JIPJDDSGuq-cbUo4OeCGts8+ scenes-app-marketing-analytics-recommendations--no-sources--dark:+ hash: v1.k794b7964.063052d5d1be49433dbfb7c0c4b31c09d493afa2e9d8f138cec2966ac3f71089.OHLVA25PfjtZS0UoPTaX9Zyx3Yy3vbl7oroS6qE3z80+ scenes-app-marketing-analytics-recommendations--no-sources--light:+ hash: v1.k794b7964.a09fe79e42fb5e80c5e70575b17b063e6a36c28604b28239f033c518dae34306.oN5kk1j66wHPWhFR2jj3OD0HE7stuLUjOt3hphnwA-g+ scenes-app-marketing-analytics-recommendations--summary--dark:+ hash: v1.k794b7964.d8298a4f9d01dd6b4b3e4f3331074b39ab6817e3a1bca11442ecea384db2a64d.qAo_hpAMkse_a-zrFehFuowYnTM05M-vGpHkfrIz6gM+ scenes-app-marketing-analytics-recommendations--summary--light:+ hash: v1.k794b7964.7ade10cef1d4fee0d3b46de121b758b0fe5c4e1d8e15b83bcefbdc451223c309.y4U6kSjcFf5eNhcM4-b2VU8ND_bdCUQBb55sZZ9E8qIscenes-app-marketing-analytics-search-performance--awaiting-sync--dark:hash: v1.k794b7964.1513b1be1c9744d4766be40cc7254eb1dc2cf00390a1b33358179f68d1edadcf.J2Wnqww8JoJMcNh3jFisc2vL7YcsF8NUd2MvqVv7yooscenes-app-marketing-analytics-search-performance--awaiting-sync--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 4da3b297e6f0..f18891915b6a 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -409,6 +409,7 @@ export const FEATURE_FLAGS = {MARKETING_ANALYTICS_MULTI_TOUCH_ATTRIBUTION: 'marketing-analytics-multi-touch-attribution', // owner: @jabahamondes #team-web-analyticsMARKETING_ANALYTICS_OPENAI_ADS: 'marketing-analytics-openai-ads', // owner: @jabahamondes #team-web-analyticsMARKETING_ANALYTICS_ORGANIC_KEYWORDS: 'marketing-analytics-organic-keywords', // owner: @jabahamondes #team-web-analytics+ MARKETING_ANALYTICS_RECOMMENDATIONS: 'marketing-analytics-recommendations', // owner: @jabahamondes #team-web-analytics — gates the Recommendations section in Ad performanceMARKETING_ANALYTICS_RETENTION: 'marketing-analytics-retention', // owner: @jabahamondes #team-web-analytics — gates the legacy Retention explorer tab; the new dashboard ignores itMARKETING_ANALYTICS_RETURN_METRICS: 'marketing-analytics-return-metrics', // owner: @jabahamondes #team-web-analytics — gates the ROAS columnMARKETING_ANALYTICS_ROKT_ADS: 'marketing-analytics-rokt-ads', // owner: @jabahamondes #team-web-analyticsdiff --git a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsxindex 8810bfb9d084..3aaed93832b1 100644--- a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx+++ b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx@@ -32,6 +32,7 @@ import { DetectedSources } from 'products/marketing_analytics/frontend/dashboardimport { SearchConsoleSource } from 'products/marketing_analytics/frontend/dashboard/SearchConsoleSource'import { SourceSetupPanel } from 'products/marketing_analytics/frontend/dashboard/SourceSetupPanel'import { marketingAnalyticsEmptyState } from 'products/marketing_analytics/frontend/emptyState/marketingAnalyticsEmptyState'+import { RecommendationsSection } from 'products/marketing_analytics/frontend/recommendations/RecommendationsSection'import { SearchPerformanceTab } from 'products/marketing_analytics/frontend/search/SearchPerformanceTab'import { DashboardConversionRecommendations } from 'products/marketing_analytics/frontend/setup/DashboardConversionRecommendations'import { DashboardSetupPrompt } from 'products/marketing_analytics/frontend/setup/DashboardSetupPrompt'@@ -104,13 +105,17 @@ const LegacySearchConnectionCard = (): JSX.Element | null => {return <SearchConsoleSource />}-const MarketingAnalyticsDashboard = (): JSX.Element => {+interface DashboardProps {+ statusAbove?: boolean+}++const MarketingAnalyticsDashboard = ({ statusAbove = false }: DashboardProps): JSX.Element => {const { featureFlags } = useValues(featureFlagLogic)return featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING] ? (<SourceMarketingAnalyticsDashboard />) : (<>- <LegacyMarketingAnalyticsDashboard />+ <LegacyMarketingAnalyticsDashboard statusAbove={statusAbove} /><LegacySearchConnectionCard /></>)@@ -259,7 +264,7 @@ const MarketingAnalyticsDashboardSkeleton = (): JSX.Element => (</div>)-const LegacyMarketingAnalyticsDashboard = (): JSX.Element => {+const LegacyMarketingAnalyticsDashboard = ({ statusAbove }: DashboardProps): JSX.Element => {const { featureFlags } = useValues(featureFlagLogic)const {hasSources,@@ -364,7 +369,7 @@ const LegacyMarketingAnalyticsDashboard = (): JSX.Element => {/>)}<LegacyOAuthReconnectBanner />- <MarketingAnalyticsSourceStatusBanner />+ {!statusAbove && <MarketingAnalyticsSourceStatusBanner />}<div className="mt-4 grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 gap-x-4 gap-y-12">{marketingTiles?.map((tile, i) => (<QueryTileItem key={i} tile={tile} />@@ -388,6 +393,19 @@ const MarketingAnalyticsContent = (): JSX.Element => {['GoogleAds', 'BingAds', 'GoogleSearchConsole'].includes(source.source_type))+ // With source onboarding on there is no ad performance tab, because the dashboard tab already is that page.+ const hasAdPerformanceTab =+ !featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING] &&+ !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]+ const showRecommendations = !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_RECOMMENDATIONS]+ // Connection problems affect every number on the page, so they go above the recommendations.+ const statusAbove = showRecommendations && !featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING]+ const recommendations = showRecommendations ? (+ <div className="mb-6">+ <RecommendationsSection />+ </div>+ ) : null+const dashboard = (<>{(!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING] ||@@ -402,6 +420,7 @@ const MarketingAnalyticsContent = (): JSX.Element => {}/>)}+ {featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING] && recommendations}<MarketingAnalyticsDashboard />{hasConnectedSearchSource && (<div className="mt-8">@@ -438,8 +457,7 @@ const MarketingAnalyticsContent = (): JSX.Element => {const tabs = [{ key: MarketingAnalyticsTab.DASHBOARD, label: 'Dashboard', content: dashboard },- ...(!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING] &&- featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]+ ...(hasAdPerformanceTab? [{key: MarketingAnalyticsTab.AD_PERFORMANCE,@@ -458,7 +476,9 @@ const MarketingAnalyticsContent = (): JSX.Element => {}/>)}- <MarketingAnalyticsDashboard />+ {statusAbove && <MarketingAnalyticsSourceStatusBanner />}+ {recommendations}+ <MarketingAnalyticsDashboard statusAbove={statusAbove} />{hasConnectedSearchSource && (<div className="mt-8"><SearchPerformanceTab />diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/UtmAuditTab/UtmAuditTab.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/UtmAuditTab/UtmAuditTab.tsxindex e7f67488ab9b..047dfbe82203 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/UtmAuditTab/UtmAuditTab.tsx+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/UtmAuditTab/UtmAuditTab.tsx@@ -24,6 +24,7 @@ import {} from '~/queries/schema/schema-general'import { marketingAnalyticsSettingsLogic } from '../../logic/marketingAnalyticsSettingsLogic'+import { formatMarketingMoney } from '../../logic/utils'import type {AggregatedUtmSource,CampaignAuditResult,@@ -125,10 +126,6 @@ function issueLabel(record: CampaignAuditResult): string {return (kind && ISSUE_LABELS[kind]) || 'Source mismatch'}-function formatCurrency(value: number, currency: string = 'USD'): string {- return new Intl.NumberFormat('en-US', { style: 'currency', currency, maximumFractionDigits: 0 }).format(value)-}-function formatNumber(value: number): string {return new Intl.NumberFormat('en-US').format(value)}@@ -252,7 +249,7 @@ function CampaignTabContent(): JSX.Element {<div className="font-medium">{record.campaign_name}</div><div className="text-xs text-secondary">{record.source_name} · ID: {record.campaign_id} ·{' '}- {formatCurrency(record.spend, baseCurrency)} ·{' '}+ {formatMarketingMoney(record.spend, baseCurrency)} ·{' '}{formatNumber(record.clicks)} clicks</div></div>diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.tsindex ce05b6cde1ee..7c691734883b 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.ts+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.ts@@ -119,6 +119,24 @@ export function nativeSourceDisplayLabel(sourceType: string): string {return NATIVE_SOURCE_DISPLAY_LABELS[sourceType as NativeMarketingSource] ?? sourceType}+// The id suffix tells apart two accounts of one platform that have no prefix.+export function marketingSourceName(source: Pick<ExternalDataSource, 'id' | 'prefix' | 'source_type'>): string {+ return source.prefix || `${nativeSourceDisplayLabel(source.source_type)} (${source.id.slice(0, 8)})`+}++export function formatMarketingMoney(amount: number, currency: string | null | undefined, compact = false): string {+ try {+ return new Intl.NumberFormat('en-US', {+ style: 'currency',+ currency: currency || 'USD',+ maximumFractionDigits: compact ? 1 : 0,+ notation: compact ? 'compact' : 'standard',+ }).format(amount)+ } catch {+ return `${Math.round(amount).toLocaleString('en-US')} ${currency ?? ''}`.trim()+ }+}+// Mirrors the backend `NATIVE_SOURCE_HIERARCHY_SCHEMA_NAMES` derivation (constants.py).export type NativeSourceHierarchySchemaNames = {adset?: stringdiff --git a/products/marketing_analytics/frontend/recommendations/RecommendationDataGapList.tsx b/products/marketing_analytics/frontend/recommendations/RecommendationDataGapList.tsxnew file mode 100644index 000000000000..12824f582018--- /dev/null+++ b/products/marketing_analytics/frontend/recommendations/RecommendationDataGapList.tsx@@ -0,0 +1,40 @@+import { LemonButton } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'++import { RecommendationDataGap } from './recommendations'++export function RecommendationDataGapList({ gaps }: { gaps: RecommendationDataGap[] }): JSX.Element {+ const sourceIds = [...new Set(gaps.map((gap) => gap.sourceId))]+ return (+ <div className="flex w-[28rem] max-w-[90vw] flex-col gap-2 p-1">+ <div className="px-2 pt-1">+ <strong>Improve recommendations</strong>+ <p className="mb-0 text-secondary">Some rules need tables that these sources do not sync yet.</p>+ </div>+ {sourceIds.map((sourceId) => {+ const sourceGaps = gaps.filter((gap) => gap.sourceId === sourceId)+ return (+ <div key={sourceId} className="flex flex-col gap-2 rounded border px-3 py-2">+ <div className="flex items-center justify-between gap-3">+ <span className="font-semibold">{sourceGaps[0].sourceName}</span>+ <LemonButton+ size="xsmall"+ type="secondary"+ to={urls.dataWarehouseSource(`managed-${sourceId}`)}+ data-attr="marketing-recommendations-data-gap-manage-source"+ >+ Manage source+ </LemonButton>+ </div>+ <ul className="m-0 flex list-disc flex-col gap-1 pl-4 text-xs text-secondary">+ {sourceGaps.map((gap) => (+ <li key={gap.table}>{gap.description}</li>+ ))}+ </ul>+ </div>+ )+ })}+ </div>+ )+}diff --git a/products/marketing_analytics/frontend/recommendations/RecommendationsModal.tsx b/products/marketing_analytics/frontend/recommendations/RecommendationsModal.tsxnew file mode 100644index 000000000000..31bc86f72fd2--- /dev/null+++ b/products/marketing_analytics/frontend/recommendations/RecommendationsModal.tsx@@ -0,0 +1,263 @@+import { BindLogic } from 'kea'+import { useRef } from 'react'++import {+ LemonBadge,+ LemonBanner,+ LemonButton,+ LemonModal,+ LemonTable,+ LemonTag,+ LemonTagType,+ Tooltip,+} from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'+import { formatMarketingMoney } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils'++import { DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import { ElapsedTime } from '~/queries/nodes/DataNode/ElapsedTime'+import { Reload } from '~/queries/nodes/DataNode/Reload'+import { MarketingAnalyticsRecommendation } from '~/queries/schema/schema-general'++import {+ IMPACT_DIRECTION_DESCRIPTIONS,+ IMPACT_DIRECTION_LABELS,+ RECOMMENDATION_CATEGORY_LABELS,+ RECOMMENDATION_RULE_DESCRIPTIONS,+ RECOMMENDATION_RULE_LABELS,+ RecommendationDataGap,+ RecommendationGroup,+ RecommendationSection,+ RecommendationTotal,+} from './recommendations'++const DIRECTION_TAG: Record<MarketingAnalyticsRecommendation['impactDirection'], LemonTagType> = {+ save: 'success',+ gain: 'info',+ invest: 'warning',+ keep: 'muted',+}++const SUBJECT_NOUNS: Record<MarketingAnalyticsRecommendation['level'], [string, string]> = {+ campaign: ['campaign', 'campaigns'],+ search_term: ['search term', 'search terms'],+}++function subjectCount(group: RecommendationGroup): string {+ const [singular, plural] = SUBJECT_NOUNS[group.level]+ const count = group.recommendations.length+ return `${count} ${count === 1 ? singular : plural}`+}++function ImpactTotals({ totals }: { totals: RecommendationTotal[] }): JSX.Element {+ return (+ <span className="flex flex-wrap items-center gap-1">+ {totals.map((total) => (+ <Tooltip+ key={`${total.direction}-${total.currency}`}+ title={IMPACT_DIRECTION_DESCRIPTIONS[total.direction]}+ >+ <LemonTag type={DIRECTION_TAG[total.direction]}>+ <span translate="no">+ {`${IMPACT_DIRECTION_LABELS[total.direction]} ${formatMarketingMoney(total.amount, total.currency, true)}/mo`}+ </span>+ </LemonTag>+ </Tooltip>+ ))}+ </span>+ )+}++function RecommendationRows({ rows }: { rows: MarketingAnalyticsRecommendation[] }): JSX.Element {+ return (+ <LemonTable<MarketingAnalyticsRecommendation>+ size="small"+ dataSource={rows}+ rowKey={(row, index) => `${row.rule}-${row.subject}-${row.campaign ?? ''}-${index}`}+ columns={[+ {+ title: 'For',+ key: 'subject',+ width: '28%',+ render: (_, row) => (+ <div className="flex flex-col py-1 break-words">+ <span className="font-semibold">{row.subject}</span>+ {row.campaign && <span className="text-xs text-secondary">{row.campaign}</span>}+ </div>+ ),+ },+ {+ title: 'Recommendation',+ key: 'action',+ render: (_, row) => (+ <div className="flex flex-col gap-0.5 py-1">+ <span>{row.action}</span>+ <span className="text-xs text-secondary">{row.reason}</span>+ </div>+ ),+ },+ {+ title: 'Impact',+ key: 'impact',+ align: 'right',+ width: 140,+ render: (_, row) =>+ row.impact == null ? (+ <span className="text-secondary">–</span>+ ) : (+ <div className="flex flex-col items-end gap-0.5 py-1 whitespace-nowrap">+ <span className="font-semibold tabular-nums" translate="no">+ {`${formatMarketingMoney(row.impact, row.currency)}/mo`}+ </span>+ <LemonTag type={DIRECTION_TAG[row.impactDirection]} size="small">+ {row.impactType === 'estimated'+ ? `${IMPACT_DIRECTION_LABELS[row.impactDirection]}, estimated`+ : IMPACT_DIRECTION_LABELS[row.impactDirection]}+ </LemonTag>+ </div>+ ),+ },+ ]}+ />+ )+}++export function RecommendationsModal({+ isOpen,+ onClose,+ total,+ totals,+ sections,+ selectedGroup,+ onSelect,+ dataNodeProps,+ dataGaps,+ disclaimer,+}: {+ isOpen: boolean+ onClose: () => void+ total: number+ totals: RecommendationTotal[]+ sections: RecommendationSection[]+ selectedGroup: RecommendationGroup | undefined+ onSelect: (rule: string) => void+ dataNodeProps: DataNodeLogicProps+ dataGaps: RecommendationDataGap[]+ disclaimer: string | undefined+}): JSX.Element {+ const navRef = useRef<HTMLElement>(null)+ const detailRef = useRef<HTMLElement>(null)+ const selectRule = (rule: string): void => {+ onSelect(rule)+ // In a narrow modal the rule list sits above the table, so the table has to come into view.+ if ((detailRef.current?.offsetTop ?? 0) > (navRef.current?.offsetTop ?? 0) + 8) {+ requestAnimationFrame(() => detailRef.current?.scrollIntoView({ block: 'start', behavior: 'smooth' }))+ }+ }+ return (+ <LemonModal+ isOpen={isOpen}+ onClose={onClose}+ width={1120}+ title={+ <div className="flex flex-wrap items-center justify-between gap-2 pr-8">+ <span>Recommendations</span>+ <BindLogic logic={dataNodeLogic} props={dataNodeProps}>+ <span className="flex items-center gap-2 text-sm font-normal">+ <ElapsedTime />+ <Reload />+ </span>+ </BindLogic>+ </div>+ }+ footer={+ disclaimer ? (+ <p className="mb-0 mr-auto text-xs text-secondary whitespace-normal">{disclaimer}</p>+ ) : undefined+ }+ description={+ <span className="flex flex-wrap items-center gap-2">+ <span>{`${total} for the selected sources and dates`}</span>+ <ImpactTotals totals={totals} />+ </span>+ }+ >+ <div className="@container">+ <div className="grid gap-4 @min-[44rem]:grid-cols-[15rem_minmax(0,1fr)]">+ <nav+ ref={navRef}+ className="flex flex-col self-start @min-[44rem]:sticky @min-[44rem]:top-0 @min-[44rem]:border-r @min-[44rem]:pr-3"+ >+ {sections.map((section) => (+ <div+ key={section.category}+ className="flex flex-col gap-0.5 py-3 first:pt-0 last:pb-0 border-t first:border-t-0"+ >+ <span className="px-2 pb-1.5 text-xs font-semibold uppercase tracking-wide text-tertiary">+ {RECOMMENDATION_CATEGORY_LABELS[section.category]}+ </span>+ {section.groups.map((group) => (+ <LemonButton+ key={group.rule}+ size="small"+ fullWidth+ active={group.rule === selectedGroup?.rule}+ onClick={() => selectRule(group.rule)}+ sideIcon={+ <LemonBadge.Number+ count={group.recommendations.length}+ maxDigits={2}+ status={group.rule === selectedGroup?.rule ? 'primary' : 'muted'}+ />+ }+ data-attr={`marketing-recommendations-group-${group.rule}`}+ >+ {RECOMMENDATION_RULE_LABELS[group.rule]}+ </LemonButton>+ ))}+ </div>+ ))}+ </nav>+ {selectedGroup ? (+ <section ref={detailRef} className="flex flex-col gap-3 min-w-0">+ <div className="flex flex-wrap items-start justify-between gap-2">+ <div className="flex flex-col gap-1 min-w-0">+ <h3 className="mb-0">+ {RECOMMENDATION_RULE_LABELS[selectedGroup.rule]}+ <span className="ml-2 text-sm font-normal text-secondary">+ {subjectCount(selectedGroup)}+ </span>+ </h3>+ <p className="mb-0 text-secondary">+ {RECOMMENDATION_RULE_DESCRIPTIONS[selectedGroup.rule]}+ </p>+ </div>+ <ImpactTotals totals={selectedGroup.totals} />+ </div>+ {dataGaps+ .filter((gap) => gap.rules.includes(selectedGroup.rule))+ .map((gap) => (+ <LemonBanner+ key={`${gap.sourceId}-${gap.table}`}+ type="info"+ action={{+ children: 'Manage source',+ to: urls.dataWarehouseSource(`managed-${gap.sourceId}`),+ 'data-attr': 'marketing-recommendations-rule-data-gap-manage-source',+ }}+ >+ <div className="font-semibold">{gap.sourceName}</div>+ <div>{gap.description}</div>+ </LemonBanner>+ ))}+ <RecommendationRows rows={selectedGroup.recommendations} />+ </section>+ ) : (+ <p className="mb-0 text-secondary">No recommendations for the selected sources and dates.</p>+ )}+ </div>+ </div>+ </LemonModal>+ )+}diff --git a/products/marketing_analytics/frontend/recommendations/RecommendationsSection.stories.tsx b/products/marketing_analytics/frontend/recommendations/RecommendationsSection.stories.tsxnew file mode 100644index 000000000000..40d15059ff6d--- /dev/null+++ b/products/marketing_analytics/frontend/recommendations/RecommendationsSection.stories.tsx@@ -0,0 +1,329 @@+import { Meta, StoryObj } from '@storybook/react'+import { within } from '@testing-library/dom'+import { BindLogic } from 'kea'++import { FEATURE_FLAGS } from 'lib/constants'+import { urls } from 'scenes/urls'+import { MarketingAnalyticsFilters } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/MarketingAnalyticsFilters'+import { MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic'++import { mswDecorator } from '~/mocks/browser'+import { Mocks } from '~/mocks/utils'+import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'+import { MarketingAnalyticsRecommendation } from '~/queries/schema/schema-general'++import IconGoogleAds from 'public/services/google-ads.png'+import IconGoogleSearchConsole from 'public/services/google-search-console.svg'++import { userEvent } from 'storybook/test'++import { RecommendationsSection } from './RecommendationsSection'++function source(+ id: string,+ sourceType: string,+ prefix: string,+ schemas: string[],+ disabled: string[] = []+): Record<string, unknown> {+ return {+ id,+ source_type: sourceType,+ description: prefix,+ prefix,+ status: 'Completed',+ schemas: [+ ...schemas.map((name) => ({+ id: `${id}-${name}`,+ name,+ should_sync: true,+ sync_frequency: '24hour',+ last_synced_at: '2025-02-14T12:00:00Z',+ status: 'Completed',+ table: { name: `${prefix}_${name}`, hogql_name: `${prefix}.${name}` },+ })),+ ...disabled.map((name) => ({ id: `${id}-${name}`, name, should_sync: false, table: null })),+ ],+ }+}++const SOURCES = [+ source('example-ads', 'GoogleAds', 'example', [+ 'campaign',+ 'campaign_stats',+ 'campaign_impression_share_stats',+ 'customer',+ 'search_term_stats',+ 'search_term_keyword_stats',+ ]),+ source('example-organic', 'GoogleSearchConsole', 'example_organic', ['search_analytics_by_query', 'sites']),+]++function recommendation(+ overrides: Partial<MarketingAnalyticsRecommendation> &+ Pick<MarketingAnalyticsRecommendation, 'rule' | 'subject' | 'action' | 'reason'>+): MarketingAnalyticsRecommendation {+ return {+ level: 'search_term',+ impact: null,+ impactDirection: 'save',+ impactType: 'measured',+ currency: 'USD',+ ...overrides,+ }+}++const DISCLAIMER =+ 'These are suggestions generated by fixed rules applied to your synced Google Ads and Search Console data. Impact figures are estimates based on past performance, not predictions or guarantees. You decide what to change, so review each suggestion before editing a campaign.'++const RESULTS: MarketingAnalyticsRecommendation[] = [+ recommendation({+ rule: 'review_campaign',+ level: 'campaign',+ subject: 'Search - Competitors',+ action: 'Review bids, ads and landing page, or pause',+ reason: 'Non-brand CPA of $412, 4.1x the non-brand average of $100.',+ impact: 3100,+ }),+ recommendation({+ rule: 'brand_leak',+ level: 'campaign',+ subject: 'Search - Generic',+ action: 'Add "acme" as a negative keyword',+ reason: '18% of its search term spend is on brand searches. Your brand campaign can serve them at a lower cost.',+ impact: 960,+ }),+ recommendation({+ rule: 'spend_without_conversions',+ subject: 'free analytics template',+ campaign: 'Search - Generic',+ action: 'Add it as a negative, or change the keyword "analytics template" from broad to exact match',+ reason: 'Spent $640 (6.4x the account CPA) on 210 clicks with no conversions',+ impact: 640,+ }),+ recommendation({+ rule: 'spend_without_conversions',+ subject: 'dashboard software jobs',+ campaign: 'Search - Generic',+ action: 'Add it as a negative, or change the keyword "dashboard software" from phrase to exact match',+ reason: 'Spent $380 (3.8x the account CPA) on 95 clicks with no conversions',+ impact: 380,+ }),+ recommendation({+ rule: 'brand_overlap',+ subject: 'acme',+ campaign: 'Search - Brand',+ action: 'Keep the ad: another ad often shows above yours',+ reason: 'Ranks #1.0 organically with 4,200 clicks. Ads cost $2,100 for 1,900 clicks. When your ad shows, another ad is above it 34% of the time.',+ impact: 2100,+ impactDirection: 'keep',+ }),+ recommendation({+ rule: 'brand_overlap',+ subject: 'acme login',+ campaign: 'Search - Brand',+ action: 'Test pausing the ad in alternating weeks and compare total clicks',+ reason: 'Ranks #1.0 organically with 900 clicks. Ads cost $310 for 260 clicks. Your ad is at the very top 96% of the time it shows.',+ impact: 310,+ }),+ recommendation({+ rule: 'brand_overlap',+ subject: 'acme app',+ campaign: 'Search - Brand',+ action: 'Check whether other ads show above yours before you test pausing',+ reason: 'Ranks #1.0 organically with 640 clicks. Ads cost $180 for 150 clicks. Top position data for this term is not synced yet.',+ impact: 180,+ impactType: 'estimated',+ }),+ recommendation({+ rule: 'budget_constrained',+ level: 'campaign',+ subject: 'Search - Brand',+ action: 'Raise the daily budget from $50 to $80',+ reason: 'Google Ads reports this campaign as limited by budget and recommends $80 a day.',+ impact: 900,+ impactDirection: 'invest',+ impactType: 'estimated',+ }),+ recommendation({+ rule: 'scale_campaign',+ level: 'campaign',+ subject: 'Search - Product',+ action: 'Raise the budget',+ reason: 'Non-brand CPA of $62, against $100 across non-brand campaigns. It loses 31% of impressions to budget and 12% to ad rank.',+ impact: 1500,+ impactDirection: 'invest',+ impactType: 'estimated',+ }),+ recommendation({+ rule: 'keyword_gap',+ subject: 'funnel analysis tool',+ action: 'Add it as a keyword in a Search campaign',+ reason: 'Ranks #24.0 organically with 3,800 impressions a month. Its words already convert in your ads.',+ impact: 420,+ impactDirection: 'invest',+ impactType: 'estimated',+ }),+ recommendation({+ rule: 'content_gap',+ subject: 'event tracking setup',+ campaign: 'Search - Product',+ action: 'Create or improve a page for this search',+ reason: 'Converts in Ads at a CPA of $45 (account $100), but does not rank organically',+ impact: 600,+ impactDirection: 'gain',+ }),+ recommendation({+ rule: 'striking_distance',+ subject: 'cohort analysis',+ campaign: 'Search - Product',+ action: 'Improve the ranking page to reach the top 3',+ reason: 'Position 7.4 with 5,100 impressions and 90 clicks. Paid CPC $2.10',+ impact: 450,+ impactDirection: 'gain',+ impactType: 'estimated',+ }),+ recommendation({+ rule: 'policy_limited',+ level: 'campaign',+ subject: 'Performance Max - All products',+ action: 'Check the affected ads in Policy manager',+ reason: 'Some asset groups are limited by policy, so they show less often.',+ }),+]++const MOCKS: Mocks = {+ delete: { '/api/projects/:team_id/query/:query_id/': [204] },+ get: {+ '/api/environments/:team_id/external_data_sources/wizard/': {+ GoogleAds: { name: 'GoogleAds', label: 'Google Ads', iconPath: IconGoogleAds, fields: [] },+ GoogleSearchConsole: {+ name: 'GoogleSearchConsole',+ label: 'Google Search Console',+ iconPath: IconGoogleSearchConsole,+ fields: [],+ },+ },+ '/api/environments/:team_id/external_data_sources/': {+ results: SOURCES,+ count: SOURCES.length,+ next: null,+ previous: null,+ },+ },+ post: {+ '/api/environments/:team_id/query/MarketingAnalyticsRecommendationsQuery/': () => [+ 200,+ { results: RESULTS, disclaimer: DISCLAIMER },+ ],+ },+}++const meta: Meta<typeof RecommendationsSection> = {+ title: 'Scenes-App/Marketing Analytics/Recommendations',+ component: RecommendationsSection,+ beforeEach: () => {+ localStorage.removeItem('997__.scenes.webAnalytics.marketingAnalyticsLogic.integrationFilter')+ const originalNow = performance.now+ performance.now = () => 0+ return () => {+ performance.now = originalNow+ }+ },+ render: () => (+ <>+ <MarketingAnalyticsFilters tabs={<></>} />+ <RecommendationsSection />+ </>+ ),+ decorators: [+ mswDecorator({}),+ (Story) => (+ <BindLogic logic={dataNodeCollectionLogic} props={{ key: MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID }}>+ <Story />+ </BindLogic>+ ),+ ],+ parameters: {+ layout: 'fullscreen',+ mockDate: '2025-02-15T12:00:00Z',+ msw: { mocks: MOCKS },+ pageUrl: `${urls.marketingAnalyticsApp()}?tab=ad-performance&date_from=-30d`,+ featureFlags: [+ FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS,+ FEATURE_FLAGS.MARKETING_ANALYTICS_RECOMMENDATIONS,+ ],+ },+}+export default meta+type Story = StoryObj<typeof meta>++export const Summary: Story = {}++export const Modal: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await userEvent.click(await canvas.findByText('Recommendations', { selector: 'button *' }))+ },+}++export const NoSources: Story = {+ parameters: {+ msw: {+ mocks: {+ ...MOCKS,+ get: {+ ...MOCKS.get,+ '/api/environments/:team_id/external_data_sources/': {+ results: [],+ count: 0,+ next: null,+ previous: null,+ },+ },+ },+ },+ },+}++const SOURCES_WITH_GAPS = [+ source(+ 'example-ads',+ 'GoogleAds',+ 'example',+ ['campaign', 'campaign_stats', 'customer', 'search_term_stats'],+ ['search_term_keyword_stats', 'campaign_impression_share_stats']+ ),+ SOURCES[1],+]++const MOCKS_WITH_GAPS: Mocks = {+ ...MOCKS,+ get: {+ ...MOCKS.get,+ '/api/environments/:team_id/external_data_sources/': {+ results: SOURCES_WITH_GAPS,+ count: SOURCES_WITH_GAPS.length,+ next: null,+ previous: null,+ },+ },+}++export const MissingTables: Story = {+ parameters: { msw: { mocks: MOCKS_WITH_GAPS } },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await userEvent.click(await canvas.findByText('Improve recommendations', { selector: 'button *' }))+ },+}++export const MissingTablesInModal: Story = {+ parameters: { msw: { mocks: MOCKS_WITH_GAPS } },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await userEvent.click(await canvas.findByText('Recommendations', { selector: 'button *' }))+ const modal = within(canvasElement.ownerDocument.body)+ await userEvent.click(await modal.findByText('Spend without conversions', { selector: 'button *' }))+ },+}diff --git a/products/marketing_analytics/frontend/recommendations/RecommendationsSection.tsx b/products/marketing_analytics/frontend/recommendations/RecommendationsSection.tsxnew file mode 100644index 000000000000..2836b623c353--- /dev/null+++ b/products/marketing_analytics/frontend/recommendations/RecommendationsSection.tsx@@ -0,0 +1,211 @@+import { useActions, useValues } from 'kea'++import { IconInfo, IconLightBulb } from '@posthog/icons'+import { LemonBadge, LemonButton, LemonDropdown, LemonSkeleton, Popover, Tooltip } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'+import { formatMarketingMoney } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils'++import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import { MarketingAnalyticsRecommendationsQueryResponse } from '~/queries/schema/schema-general'++import { MarketingQueryError } from '../dashboard/MarketingQueryError'+import { RecommendationDataGapList } from './RecommendationDataGapList'+import {+ IMPACT_DIRECTION_DESCRIPTIONS,+ IMPACT_DIRECTION_LABELS,+ RecommendationTotal,+ groupRecommendations,+ sectionRecommendations,+ sumImpact,+} from './recommendations'+import { recommendationsLogic } from './recommendationsLogic'+import { RecommendationsModal } from './RecommendationsModal'++function ImpactSummary({ totals }: { totals: RecommendationTotal[] }): JSX.Element {+ return (+ <span className="flex flex-wrap items-center gap-x-3 gap-y-1 text-secondary">+ {totals.map((total) => (+ <Tooltip+ key={`${total.direction}-${total.currency}`}+ title={IMPACT_DIRECTION_DESCRIPTIONS[total.direction]}+ >+ <span className="cursor-help">+ {`${IMPACT_DIRECTION_LABELS[total.direction]} `}+ <span className="font-semibold text-primary" translate="no">+ {`${formatMarketingMoney(total.amount, total.currency, true)}/mo`}+ </span>+ </span>+ </Tooltip>+ ))}+ </span>+ )+}++export function RecommendationsSection(): JSX.Element {+ const {+ dataNodeProps,+ dataWarehouseSources,+ sources,+ hasAdsSource,+ dataGaps,+ selectedRule,+ introSeen,+ connectedSourceTypes,+ } = useValues(recommendationsLogic)+ const { setSelectedRule, dismissIntro } = useActions(recommendationsLogic)+ const { response, responseLoading, responseError, queryId } = useValues(dataNodeLogic(dataNodeProps))+ const { loadData } = useActions(dataNodeLogic(dataNodeProps))++ const recommendationsResponse = response as MarketingAnalyticsRecommendationsQueryResponse | null+ const results = recommendationsResponse?.results ?? []+ const groups = groupRecommendations(results)+ const sections = sectionRecommendations(groups)+ const firstRule = sections[0]?.groups[0]?.rule+ // Reloading can drop the open rule, so the modal falls back to the first one instead of closing on its own.+ const selectedGroup =+ selectedRule === null+ ? undefined+ : (groups.find((group) => group.rule === selectedRule) ?? sections[0]?.groups[0])+ const sourcesLoading = !dataWarehouseSources+ const connectGoogleAds = {+ children: 'Connect Google Ads',+ // pinned: entry_point on the source connect events, renaming it splits the attribution+ to: urls.dataWarehouseSourceNew(+ 'GoogleAds',+ urls.marketingAnalyticsApp(),+ 'Marketing analytics',+ undefined,+ 'marketing_analytics_recommendations'+ ),+ 'data-attr': 'marketing-recommendations-connect-google-ads',+ sideIcon: null,+ }++ const showGroups = sources.length > 0 && !responseError && !!firstRule+ const idleMessage =+ connectedSourceTypes.length === 0+ ? 'Connect Google Ads to get recommendations on budgets, search terms and wasted spend.'+ : sources.length === 0+ ? 'Select a Google Ads or Google Search Console source with synced tables to see recommendations.'+ : responseError+ ? null+ : 'No recommendations for this period.'+ const idleReason =+ connectedSourceTypes.length > 0 && sources.length > 0 && !responseError+ ? 'Campaign rules compare active campaigns in the same ad account, so an account with one campaign gets few. Search term rules need synced search term tables, and Google Search Console for the organic ones.'+ : (idleMessage ?? 'Recommendations could not load.')++ return (+ <div className="@container flex flex-col gap-3 pt-2" data-attr="marketing-recommendations">+ <Popover+ visible={showGroups && !introSeen}+ placement="bottom-start"+ showArrow+ overlay={+ <div className="flex max-w-80 flex-col gap-2 p-2">+ <strong>New: recommendations</strong>+ <p className="mb-0">+ Built from your Google Ads and Google Search Console data. They show where to cut wasted+ spend, where to grow, and which pages to improve for organic search. They are suggestions,+ so check each one before you edit a campaign.+ </p>+ <div className="flex justify-end gap-2">+ <LemonButton size="small" onClick={dismissIntro}>+ Got it+ </LemonButton>+ <LemonButton+ type="primary"+ size="small"+ onClick={() => setSelectedRule(firstRule ?? null)}+ data-attr="marketing-recommendations-intro-open"+ >+ See recommendations+ </LemonButton>+ </div>+ </div>+ }+ >+ <div className="flex flex-wrap items-center gap-2 min-w-0">+ {showGroups ? (+ <>+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconLightBulb />}+ sideIcon={<LemonBadge.Number count={results.length} maxDigits={3} />}+ onClick={() => setSelectedRule(firstRule ?? null)}+ data-attr="marketing-recommendations-open"+ >+ Recommendations+ </LemonButton>+ <ImpactSummary totals={sumImpact(results)} />+ {dataGaps.length > 0 && (+ <LemonDropdown+ closeOnClickInside={false}+ overlay={<RecommendationDataGapList gaps={dataGaps} />}+ >+ <LemonButton+ size="small"+ type="tertiary"+ icon={<IconInfo />}+ sideIcon={<LemonBadge.Number count={dataGaps.length} status="muted" />}+ data-attr="marketing-recommendations-data-gaps"+ >+ Improve recommendations+ </LemonButton>+ </LemonDropdown>+ )}+ </>+ ) : sourcesLoading || (responseLoading && sources.length > 0) ? (+ <LemonSkeleton className="h-6 w-60" />+ ) : (+ <>+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconLightBulb />}+ sideIcon={null}+ disabledReason={idleReason}+ >+ Recommendations+ </LemonButton>+ {idleMessage && <span className="text-secondary">{idleMessage}</span>}+ {connectedSourceTypes.length === 0 && (+ <LemonButton type="secondary" size="small" {...connectGoogleAds} />+ )}+ </>+ )}+ {showGroups && !hasAdsSource && (+ <span className="text-secondary">+ Connect Google Ads and sync its campaign tables to also get campaign recommendations.+ </span>+ )}+ {showGroups && !hasAdsSource && !connectedSourceTypes.includes('GoogleAds') && (+ <LemonButton type="tertiary" size="small" {...connectGoogleAds} />+ )}+ </div>+ </Popover>+ {!sourcesLoading && sources.length > 0 && responseError ? (+ <MarketingQueryError+ message="Could not load recommendations. Try again, and contact support if it keeps happening."+ queryId={queryId}+ onRetry={() => loadData('force_async')}+ loading={responseLoading}+ />+ ) : null}+ <RecommendationsModal+ isOpen={selectedRule !== null}+ onClose={() => setSelectedRule(null)}+ total={results.length}+ totals={sumImpact(results)}+ sections={sections}+ selectedGroup={selectedGroup}+ onSelect={setSelectedRule}+ dataNodeProps={dataNodeProps}+ dataGaps={dataGaps}+ disclaimer={recommendationsResponse?.disclaimer}+ />+ </div>+ )+}diff --git a/products/marketing_analytics/frontend/recommendations/recommendations.test.ts b/products/marketing_analytics/frontend/recommendations/recommendations.test.tsnew file mode 100644index 000000000000..d999675541d5--- /dev/null+++ b/products/marketing_analytics/frontend/recommendations/recommendations.test.ts@@ -0,0 +1,40 @@+import { MarketingAnalyticsRecommendation } from '~/queries/schema/schema-general'++import { groupRecommendations } from './recommendations'++function recommendation(overrides: Partial<MarketingAnalyticsRecommendation>): MarketingAnalyticsRecommendation {+ return {+ rule: 'spend_without_conversions',+ level: 'search_term',+ subject: 'term',+ action: 'Add it as a negative',+ reason: 'No conversions',+ impact: 100,+ impactDirection: 'save',+ impactType: 'measured',+ currency: 'USD',+ ...overrides,+ }+}++describe('groupRecommendations', () => {+ it('puts groups that only say keep last and sums impact per currency', () => {+ const groups = groupRecommendations([+ recommendation({ rule: 'brand_overlap', impactDirection: 'keep', impact: 5000 }),+ recommendation({ subject: 'a', impact: 100, currency: 'USD' }),+ recommendation({ subject: 'b', impact: 50, currency: 'USD' }),+ recommendation({ subject: 'c', impact: 90000, currency: 'EUR' }),+ ])++ expect(groups.map((group) => [group.rule, group.totals])).toEqual([+ [+ 'spend_without_conversions',+ [+ { direction: 'save', currency: 'USD', amount: 150 },+ { direction: 'save', currency: 'EUR', amount: 90000 },+ ],+ ],+ ['brand_overlap', [{ direction: 'keep', currency: 'USD', amount: 5000 }]],+ ])+ })+})diff --git a/products/marketing_analytics/frontend/recommendations/recommendations.ts b/products/marketing_analytics/frontend/recommendations/recommendations.tsnew file mode 100644index 000000000000..5ac523dfa58e--- /dev/null+++ b/products/marketing_analytics/frontend/recommendations/recommendations.ts@@ -0,0 +1,221 @@+import { marketingSourceName } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils'++import {+ MarketingAnalyticsRecommendation,+ MarketingAnalyticsRecommendationRule,+ MarketingAnalyticsRecommendationsSource,+} from '~/queries/schema/schema-general'+import { ExternalDataSource } from '~/types'++export const RECOMMENDATIONS_QUERY_KEY = 'marketing-recommendations'++export const RECOMMENDATION_RULE_LABELS: Record<MarketingAnalyticsRecommendationRule, string> = {+ budget_constrained: 'Limited by budget',+ brand_leak: 'Brand searches',+ scale_campaign: 'Room to grow',+ review_campaign: 'High cost per conversion',+ policy_limited: 'Ads limited by policy',+ brand_overlap: 'Brand overlap',+ content_gap: 'Content gap',+ keyword_gap: 'Keyword gap',+ spend_without_conversions: 'Spend without conversions',+ striking_distance: 'Striking distance',+}++export const RECOMMENDATION_RULE_DESCRIPTIONS: Record<MarketingAnalyticsRecommendationRule, string> = {+ budget_constrained: 'Google Ads limits these campaigns by budget and suggests a higher daily budget.',+ brand_leak: 'Campaigns that are not about your brand spend on searches for your brand name.',+ scale_campaign: 'Conversions cost less than your average, but the campaign loses impressions to budget or ad rank.',+ review_campaign: 'Conversions cost much more than your average across campaigns that are not about your brand.',+ policy_limited: 'Google limits some ads in these campaigns for policy reasons, so they show less often.',+ brand_overlap: 'You pay for brand searches where your site already ranks in the top 3 organically.',+ content_gap: 'Searches that convert cheaply in ads, where your site ranks below position 10 or not at all.',+ keyword_gap: 'Popular organic searches you do not bid on, made of words that already convert in your ads.',+ spend_without_conversions:+ 'Search terms that cost at least twice your average cost per conversion and never converted.',+ striking_distance: 'Searches where your site ranks between positions 5 and 20. The top 3 gets most of the clicks.',+}++export type RecommendationCategory = 'waste' | 'grow' | 'organic' | 'fix'++const RULE_CATEGORIES: Record<MarketingAnalyticsRecommendationRule, RecommendationCategory> = {+ spend_without_conversions: 'waste',+ brand_leak: 'waste',+ review_campaign: 'waste',+ brand_overlap: 'waste',+ budget_constrained: 'grow',+ scale_campaign: 'grow',+ keyword_gap: 'grow',+ content_gap: 'organic',+ striking_distance: 'organic',+ policy_limited: 'fix',+}++export const RECOMMENDATION_CATEGORY_LABELS: Record<RecommendationCategory, string> = {+ waste: 'Cut wasted spend',+ grow: 'Grow',+ organic: 'Improve organic search',+ fix: 'Fix issues',+}++export interface RecommendationSection {+ category: RecommendationCategory+ groups: RecommendationGroup[]+}++export function sectionRecommendations(groups: RecommendationGroup[]): RecommendationSection[] {+ return (Object.keys(RECOMMENDATION_CATEGORY_LABELS) as RecommendationCategory[])+ .map((category) => ({ category, groups: groups.filter((group) => RULE_CATEGORIES[group.rule] === category) }))+ .filter((section) => section.groups.length > 0)+}++export const IMPACT_DIRECTION_LABELS: Record<MarketingAnalyticsRecommendation['impactDirection'], string> = {+ save: 'Save',+ gain: 'Gain',+ invest: 'Invest',+ keep: 'Keep',+}++export const IMPACT_DIRECTION_DESCRIPTIONS: Record<MarketingAnalyticsRecommendation['impactDirection'], string> = {+ save: 'Spend you can cut each month',+ gain: 'Value you can add each month, from more conversions or organic clicks',+ invest: 'Extra spend these recommendations suggest each month, at most',+ keep: 'Spend these recommendations advise you to keep each month',+}++const DIRECTION_ORDER: MarketingAnalyticsRecommendation['impactDirection'][] = ['save', 'gain', 'invest', 'keep']++export interface RecommendationTotal {+ direction: MarketingAnalyticsRecommendation['impactDirection']+ currency: string | null+ amount: number+}++export interface RecommendationGroup {+ rule: MarketingAnalyticsRecommendationRule+ level: MarketingAnalyticsRecommendation['level']+ recommendations: MarketingAnalyticsRecommendation[]+ totals: RecommendationTotal[]+}++// Accounts can use different currencies, so amounts only add up within one currency.+export function sumImpact(recommendations: MarketingAnalyticsRecommendation[]): RecommendationTotal[] {+ const totals = new Map<string, RecommendationTotal>()+ for (const recommendation of recommendations) {+ if (recommendation.impact == null) {+ continue+ }+ const currency = recommendation.currency ?? null+ const key = `${recommendation.impactDirection}|${currency}`+ const total = totals.get(key) ?? { direction: recommendation.impactDirection, currency, amount: 0 }+ total.amount += recommendation.impact+ totals.set(key, total)+ }+ return [...totals.values()].sort(+ (a, b) => DIRECTION_ORDER.indexOf(a.direction) - DIRECTION_ORDER.indexOf(b.direction)+ )+}++export function groupRecommendations(recommendations: MarketingAnalyticsRecommendation[]): RecommendationGroup[] {+ const byRule = new Map<MarketingAnalyticsRecommendationRule, MarketingAnalyticsRecommendation[]>()+ for (const recommendation of recommendations) {+ byRule.set(recommendation.rule, [...(byRule.get(recommendation.rule) ?? []), recommendation])+ }+ const groups = [...byRule.entries()].map(([rule, rows]) => ({+ rule,+ level: rows[0].level,+ recommendations: rows,+ totals: sumImpact(rows),+ }))+ // The backend already orders rules by impact. Groups that only say "keep" need no action, so they go last.+ const needsAction = (group: RecommendationGroup): boolean =>+ group.recommendations.some((row) => row.impactDirection !== 'keep')+ return [...groups.filter(needsAction), ...groups.filter((group) => !needsAction(group))]+}++function syncedTable(source: ExternalDataSource, name: string): string | undefined {+ const schema = source.schemas.find((schema) => schema.name === name)+ if (!schema?.should_sync || !schema.table) {+ return undefined+ }+ return schema.table.hogql_name ?? schema.table.name+}++export interface RecommendationDataGap {+ sourceId: string+ sourceName: string+ table: string+ description: string+ rules: MarketingAnalyticsRecommendationRule[]+}++const DATA_GAP_TABLES: Omit<RecommendationDataGap, 'sourceId' | 'sourceName'>[] = [+ {+ table: 'search_term_stats',+ description: 'Turn on the search terms table to get recommendations about the searches that trigger your ads.',+ rules: [+ 'brand_leak',+ 'brand_overlap',+ 'content_gap',+ 'keyword_gap',+ 'spend_without_conversions',+ 'striking_distance',+ ],+ },+ {+ table: 'search_term_keyword_stats',+ description:+ 'Turn on the search term keywords table to see which keyword matched each search term that wastes spend.',+ rules: ['spend_without_conversions'],+ },+ {+ table: 'campaign_impression_share_stats',+ description: 'Turn on the campaign impression share table to tell budget limits from ad rank limits.',+ rules: ['budget_constrained', 'scale_campaign'],+ },+]++// Tables a Google Ads source could turn on to get more or better recommendations. A table that is on but has+// not synced yet, or that the source does not list, gives the person nothing to do, so it is left out.+export function recommendationDataGaps(source: ExternalDataSource): RecommendationDataGap[] {+ if (source.source_type !== 'GoogleAds' || !recommendationsSource(source)) {+ return []+ }+ return DATA_GAP_TABLES.filter((gap) => {+ const schema = source.schemas.find((schema) => schema.name === gap.table)+ return !!schema && !schema.should_sync+ }).map((gap) => ({+ ...gap,+ sourceId: source.id,+ sourceName: marketingSourceName(source),+ }))+}++export function recommendationsSource(source: ExternalDataSource): MarketingAnalyticsRecommendationsSource | null {+ if (source.source_type === 'GoogleAds') {+ const campaignTable = syncedTable(source, 'campaign')+ const campaignStatsTable = syncedTable(source, 'campaign_stats')+ if (!campaignTable || !campaignStatsTable) {+ return null+ }+ return {+ sourceType: 'GoogleAds',+ campaignTable,+ campaignStatsTable,+ campaignImpressionShareTable: syncedTable(source, 'campaign_impression_share_stats'),+ customerTable: syncedTable(source, 'customer'),+ searchTermTable: syncedTable(source, 'search_term_stats'),+ searchTermKeywordTable: syncedTable(source, 'search_term_keyword_stats'),+ performanceMaxSearchTermTable: syncedTable(source, 'performance_max_search_term_stats'),+ }+ }+ if (source.source_type === 'GoogleSearchConsole') {+ const queryTable =+ syncedTable(source, 'search_analytics_by_query') ?? syncedTable(source, 'search_analytics_by_query_page')+ if (!queryTable) {+ return null+ }+ return { sourceType: 'GoogleSearchConsole', queryTable, sitesTable: syncedTable(source, 'sites') }+ }+ return null+}diff --git a/products/marketing_analytics/frontend/recommendations/recommendationsLogic.ts b/products/marketing_analytics/frontend/recommendations/recommendationsLogic.tsnew file mode 100644index 000000000000..bd420e3e7302--- /dev/null+++ b/products/marketing_analytics/frontend/recommendations/recommendationsLogic.ts@@ -0,0 +1,132 @@+import { MakeLogicType, actions, afterMount, connect, kea, path, reducers, selectors } from 'kea'++import { marketingAnalyticsLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'+import { MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic'++import { DataNodeLogicProps } from '~/queries/nodes/DataNode/dataNodeLogic'+import {+ IntegrationFilter,+ MarketingAnalyticsRecommendationsQuery,+ MarketingAnalyticsRecommendationsSource,+ NodeKind,+} from '~/queries/schema/schema-general'+import { ExternalDataSource } from '~/types'++import { selectedSearchSources } from '../search/searchPerformance'+import {+ RECOMMENDATIONS_QUERY_KEY,+ RecommendationDataGap,+ recommendationDataGaps,+ recommendationsSource,+} from './recommendations'++const RECOMMENDATION_SOURCE_TYPES = ['GoogleAds', 'GoogleSearchConsole']++interface DateFilter {+ dateFrom: string | null+ dateTo: string | null+}++export interface recommendationsLogicValues {+ dataWarehouseSources: { results: ExternalDataSource[] } | null+ integrationFilter: IntegrationFilter+ dateFilter: DateFilter+ selectedSources: ExternalDataSource[]+ sources: MarketingAnalyticsRecommendationsSource[]+ dataGaps: RecommendationDataGap[]+ hasAdsSource: boolean+ connectedSourceTypes: string[]+ query: MarketingAnalyticsRecommendationsQuery+ dataNodeProps: DataNodeLogicProps+ selectedRule: string | null+ introSeen: boolean+}++export interface recommendationsLogicActions {+ loadSources: () => void+ setSelectedRule: (rule: string | null) => { rule: string | null }+ dismissIntro: () => { value: true }+}++export type recommendationsLogicType = MakeLogicType<recommendationsLogicValues, recommendationsLogicActions>++export const recommendationsLogic = kea<recommendationsLogicType>([+ path(['products', 'marketingAnalytics', 'recommendationsLogic']),+ connect(() => ({+ values: [marketingAnalyticsLogic, ['dataWarehouseSources', 'integrationFilter', 'dateFilter']],+ actions: [marketingAnalyticsLogic, ['loadSources']],+ })),+ actions({+ setSelectedRule: (rule: string | null) => ({ rule }),+ dismissIntro: true,+ }),+ reducers({+ selectedRule: [null as string | null, { setSelectedRule: (_, { rule }) => rule }],+ // pinned: persisted under this reducer name, renaming it shows the intro again to everyone who closed it+ introSeen: [+ false,+ { persist: true },+ { dismissIntro: () => true, setSelectedRule: (seen, { rule }) => seen || rule !== null },+ ],+ }),+ selectors({+ selectedSources: [+ (s) => [s.dataWarehouseSources, s.integrationFilter],+ (+ dataWarehouseSources: { results: ExternalDataSource[] } | null,+ integrationFilter: IntegrationFilter+ ): ExternalDataSource[] =>+ selectedSearchSources(+ dataWarehouseSources?.results ?? [],+ integrationFilter.integrationSourceIds ?? [],+ RECOMMENDATION_SOURCE_TYPES+ ),+ ],+ sources: [+ (s) => [s.selectedSources],+ (selectedSources: ExternalDataSource[]): MarketingAnalyticsRecommendationsSource[] =>+ selectedSources.flatMap((source) => recommendationsSource(source) ?? []),+ ],+ dataGaps: [+ (s) => [s.selectedSources],+ (selectedSources: ExternalDataSource[]): RecommendationDataGap[] =>+ selectedSources.flatMap(recommendationDataGaps),+ ],+ connectedSourceTypes: [+ (s) => [s.dataWarehouseSources],+ (dataWarehouseSources: { results: ExternalDataSource[] } | null): string[] =>+ (dataWarehouseSources?.results ?? [])+ .map((source) => source.source_type)+ .filter((type) => RECOMMENDATION_SOURCE_TYPES.includes(type)),+ ],+ hasAdsSource: [+ (s) => [s.sources],+ (sources: MarketingAnalyticsRecommendationsSource[]): boolean =>+ sources.some((source) => source.sourceType === 'GoogleAds'),+ ],+ query: [+ (s) => [s.sources, s.dateFilter],+ (+ sources: MarketingAnalyticsRecommendationsSource[],+ dateFilter: DateFilter+ ): MarketingAnalyticsRecommendationsQuery => ({+ kind: NodeKind.MarketingAnalyticsRecommendationsQuery,+ sources,+ dateRange: { date_from: dateFilter.dateFrom, date_to: dateFilter.dateTo },+ }),+ ],+ dataNodeProps: [+ (s) => [s.query],+ (query: MarketingAnalyticsRecommendationsQuery): DataNodeLogicProps => ({+ key: RECOMMENDATIONS_QUERY_KEY,+ query,+ dataNodeCollectionId: MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID,+ }),+ ],+ }),+ afterMount(({ values, actions }) => {+ if (!values.dataWarehouseSources) {+ actions.loadSources()+ }+ }),+])diff --git a/products/marketing_analytics/frontend/search/searchPerformance.ts b/products/marketing_analytics/frontend/search/searchPerformance.tsindex d9f5eca687e8..43f4bd04a23b 100644--- a/products/marketing_analytics/frontend/search/searchPerformance.ts+++ b/products/marketing_analytics/frontend/search/searchPerformance.ts@@ -308,8 +308,12 @@ export function searchPerformanceSourceNotice(export const SEARCH_SOURCE_TYPES = ['GoogleAds', 'BingAds', 'GoogleSearchConsole']-export function selectedSearchSources(sources: ExternalDataSource[], selectedIds: string[]): ExternalDataSource[] {- const searchSources = sources.filter((source) => SEARCH_SOURCE_TYPES.includes(source.source_type))+export function selectedSearchSources(+ sources: ExternalDataSource[],+ selectedIds: string[],+ types: string[] = SEARCH_SOURCE_TYPES+): ExternalDataSource[] {+ const searchSources = sources.filter((source) => types.includes(source.source_type))const selected = searchSources.filter((source) => selectedIds.includes(source.id))return selectedIds.length > 0 ? selected : searchSources}