: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): show customer goals in acquisition (#100388)
Javier Bahamondese59aa09399e2
diff --git a/docs/internal/marketing-analytics-configuration-writes.md b/docs/internal/marketing-analytics-configuration-writes.mdindex 86e422fbdce6..aa5362b2a119 100644--- a/docs/internal/marketing-analytics-configuration-writes.md+++ b/docs/internal/marketing-analytics-configuration-writes.md@@ -44,6 +44,28 @@ When the main content panel is narrow, Setup provides a section selector in placThe new dashboard opens on Acquisition. Its section tiles show one section at a time while preserving the shared date and comparison filters. Retention, Conversion, and Revenue tiles follow their existing feature flags.-Acquisition and Engagement reuse the Web Analytics stats table with a shared traffic breakdown selector. The Acquisition table shows visitors and pageviews; the Engagement table shows visitors and bounce rate. Summary cards remain visitors, sessions, and pageviews for Acquisition, and session duration and bounce rate for Engagement. Changing sections preserves the selected breakdown, date range, and comparison.+Acquisition and Engagement reuse the Web Analytics stats table with a shared traffic breakdown selector. The Acquisition table shows visitors, sessions and pageviews; the Engagement table shows visitors and bounce rate. Summary cards remain visitors, sessions, and pageviews for Acquisition, and session duration and bounce rate for Engagement. Changing sections preserves the selected breakdown, date range, and comparison.Comparison and Reload summary controls appear only in Acquisition and Engagement, where they affect the displayed traffic data. The comparison selection is retained when visiting other sections.++Acquisition also shows unique visitors completing a selected customer goal and their ratio to visitors, with prior-period comparison and channel/campaign breakdowns. Event and action goals marked as customer-defining are supported; warehouse goals remain in Ad performance. The selected goal's property filters apply only to conversions, preserving the visitor denominator. Multiple goals are selected individually, and removing or unmarking a selection falls back to another eligible goal or the Configure in Setup card.++These are unique converters within the selected period, not a first-ever customer calculation. Choose a once-per-customer event or action to interpret the metric as new customers. The Acquisition table retains visitors, sessions and pageviews, adding customers and their ratio to visitors when a goal is selected. The ratio can exceed 100% when conversion events arrive without pageviews or screenviews. Engagement and the legacy dashboard remain unchanged.++Reload summary stays disabled until both traffic and customer metrics finish loading in Acquisition.++### Acquisition code ownership and verification++The dashboard, customer-goal selection, customer-to-visitor calculation, and traffic column presentation live in `products/marketing_analytics/frontend/dashboard/`. Attribution owns its revenue and attribution controls. Web Analytics owns the reusable query execution, including conversion property filters and optional traffic metrics.++To verify Acquisition, enable `new-marketing-analytics-dashboard` and open `/project/<project_id>/marketing` in a development project with pageviews and a customer event or action:++1. In Setup, mark a conversion goal as a new customer goal. Return to Dashboard → Acquisition.+2. Confirm Visitors, Sessions, Pageviews, New customers, and Customer-to-visitor ratio appear. Select another customer goal and confirm the customer metrics update.+3. Switch the traffic breakdown from Channel to Campaign and enable comparison. Confirm the table and summary use the selected period.+4. Open Engagement, change dates, and return to Acquisition. Confirm the dates and breakdown remain selected and the customer metrics reload.+5. Remove or unmark the selected customer goal in Setup. Confirm Acquisition falls back to another eligible goal, or shows Configure in Setup if none remain.++Customer-goal selection and ratio tests live beside the dashboard. The dashboard suites also cover section gating and source-suggestion navigation.++Click a traffic metric column heading to sort descending; click it again to sort ascending. Acquisition and Engagement retain separate sort selections.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex d25c4c864834..73ff49127096 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5052,6 +5052,30 @@ snapshots:hash: v1.k794b7964.1d690c0916c6cb0e1cd9682b2c2ceaf072907faf864eb9c60708f20b54491d01.CSbDUiLNw1wFHNsYIjr6gY5pqrWGWK_ka7wav_H_zwologs-logsfiltervolumesparkline--with-rate-limit-threshold--light:hash: v1.k794b7964.90511b5879e111bf4d4b3f7b31f5d24159de7590de35e110bc4d510f763cfa1a.l4VDaP9QZZgd9RbT-nWeHb00FGgojPia3OHP-Bq-pfU+ marketing-analytics-customer-acquisition-cards--configuration-loading--dark:+ hash: v1.k794b7964.4e3295796230b8ccc9ce5cb239d9ffe000af9d00324d31584d3fa6fde8550fe9.04jR2iHz7Mn5n3Z6KmK4yt-R520UGYL9im_4Icykhxk+ marketing-analytics-customer-acquisition-cards--configuration-loading--light:+ hash: v1.k794b7964.e0621c392648364dcfd76d6aa207ef3cf5990d9509dd05641e0280e83dbe7f9c.bicYg7JvUWNQ92J9Gge8euSuSBODkAA4EuzwfBFJ1Uk+ marketing-analytics-customer-acquisition-cards--configured--dark:+ hash: v1.k794b7964.1c9446a4d817e8c7835338860f5eb7a237bf7aaed99495dd06ffe6d823ce6b77.6zptp7eX0J7T-Jvx3km58UA6mC7KUhbOXqYKXHKbs60+ marketing-analytics-customer-acquisition-cards--configured--light:+ hash: v1.k794b7964.aa4c113316faef65e68956fbe7f75f8140c552d91cd72e1146561f0105499ee9.-Mpkaw0Y5jpKzByOaiM9Q5NkCg9WapChfdL2GjHyZng+ marketing-analytics-customer-acquisition-cards--error--dark:+ hash: v1.k794b7964.dc409831738ce2b25d5a5fa4b7b31d3310108e0335670f5e93de50b80b9e4d02.aRmpYSiDd_AMCnBTDyRzKgt4Hn1kcX5u-C7wSKMzZYY+ marketing-analytics-customer-acquisition-cards--error--light:+ hash: v1.k794b7964.e80f2eb9c01b27aa8297e6f8644941db5f5dd9665044c4f562418988ebde43a0.-bjEtmLDqxX0XU_k8CZDaZ02knZpPTrijQ44mDhEKEE+ marketing-analytics-customer-acquisition-cards--loading--dark:+ hash: v1.k794b7964.9c7937c5eeebaab82299b1eab7c64e567045df1d8342efabb006f55234f853e7.t1KXV9kOCbgn8aYOuJ0eEJFrAF-bs1Z3VYyADYdHDwM+ marketing-analytics-customer-acquisition-cards--loading--light:+ hash: v1.k794b7964.885cc20f71571a703d9d91afeabf622ca654b97908e4cc3adfd4a9d7d3809185.tXMt6YqMYkUigQXZZyKan4j_hEeb7YL8UDaO4H09u2A+ marketing-analytics-customer-acquisition-cards--no-customers--dark:+ hash: v1.k794b7964.d373fc20fdafc0d07ec36de7a05ae9a67503dea118d04cad304647c25fd3a404.HiqYRZCwBEdtfwWgfgiv5KS5G9Q8fDgue9xC5gxxP_c+ marketing-analytics-customer-acquisition-cards--no-customers--light:+ hash: v1.k794b7964.2c6caa70fd61247a739d507f8d9b57f67e0262165c0fa5ed42ceb1213f2484ad.qshFf-kF2oLF5w2RLB29ntSYfArxj0CvRo8cd0uRqrA+ marketing-analytics-customer-acquisition-cards--unconfigured--dark:+ hash: v1.k794b7964.fda088b86665fa1e7f42ac158d9c5acf12b2afc030a90ad385d3d0fe16170d46.WqmQ9-wSSHQj0J-kUbJKkFI8DhDljOP6queW3e6jxDQ+ marketing-analytics-customer-acquisition-cards--unconfigured--light:+ hash: v1.k794b7964.40240d162f715f3da0d8363e08797fb8a9c131852a5d6356c892424e25dfa35c.yeHaH7ecKHVh7IOwmerxuVPzSGclQrUDBwWnoPV0rmwmcp-apps-actions--list--light:hash: v1.k794b7964.1404bf36ee039ef64d978fb4ff825a04ebe55ea2bc4c04ba6bc2a4252d5b8657.eOwPJ0UYuP-Cwmz1wqPf0gbtNVQx6r-6JTyhx75dhZ8mcp-apps-actions--multi-step--light:diff --git a/frontend/src/queries/nodes/OverviewGrid/OverviewMetricCardGrid.tsx b/frontend/src/queries/nodes/OverviewGrid/OverviewMetricCardGrid.tsxindex b4ffca7a961b..d6b4442a8d33 100644--- a/frontend/src/queries/nodes/OverviewGrid/OverviewMetricCardGrid.tsx+++ b/frontend/src/queries/nodes/OverviewGrid/OverviewMetricCardGrid.tsx@@ -22,16 +22,18 @@ export interface OverviewMetricCardItem extends Omit<OverviewItem, 'value' | 'printerface OverviewMetricCardGridProps {items: OverviewMetricCardItem[]+ layout?: 'grid' | 'contents'loading: booleannumSkeletons: numbersamplingRate?: SamplingRatepreComputeStrategy?: WebAnalyticsPreComputeStrategyonDisablePrecompute?: () => void- labelFromKey: (key: string) => string+ labelFromKey: (key: string) => React.ReactNode}export function OverviewMetricCardGrid({items,+ layout = 'grid',loading,numSkeletons,samplingRate,@@ -41,13 +43,18 @@ export function OverviewMetricCardGrid({}: OverviewMetricCardGridProps): JSX.Element {return (<>- <div className="grid gap-2 grid-cols-[repeat(auto-fit,minmax(10rem,1fr))]">+ <div+ className={+ layout === 'contents' ? 'contents' : 'grid gap-2 grid-cols-[repeat(auto-fit,minmax(10rem,1fr))]'+ }+ >{loading? range(numSkeletons).map((i) => <MetricCardSkeleton key={i} />): items.map((item) => (<MetricCardCellkey={item.key}item={item}+ stretch={layout === 'contents'}preComputeStrategy={preComputeStrategy}onDisablePrecompute={onDisablePrecompute}labelFromKey={labelFromKey}@@ -61,14 +68,16 @@ export function OverviewMetricCardGrid({function MetricCardCell({item,+ stretch,preComputeStrategy,onDisablePrecompute,labelFromKey,}: {item: OverviewMetricCardItem+ stretch?: booleanpreComputeStrategy?: WebAnalyticsPreComputeStrategyonDisablePrecompute?: () => void- labelFromKey: (key: string) => string+ labelFromKey: (key: string) => React.ReactNode}): JSX.Element {const { baseCurrency } = useValues(teamLogic)@@ -110,6 +119,7 @@ function MetricCardCell({<PreAggregatedBadge variant="preagg" position="bottom-right" />) : null}<MetricCard+ className={stretch ? 'h-full [&>div:first-child]:flex-1' : undefined}title={<MetricCardTitle label={labelFromKey(item.key)} item={item} />}value={item.value}change={metricChange(item)}@@ -121,7 +131,7 @@ function MetricCardCell({)}-function MetricCardTitle({ label, item }: { label: string; item: OverviewMetricCardItem }): JSX.Element {+function MetricCardTitle({ label, item }: { label: React.ReactNode; item: OverviewMetricCardItem }): JSX.Element {if (!item.warning) {return <>{label}</>}diff --git a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsxindex fec5a599aa97..d9ad81dd8930 100644--- a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx+++ b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx@@ -24,6 +24,7 @@ import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollecimport { ProductKey } from '~/queries/schema/schema-general'import { sourcesDataLogic } from 'products/data_warehouse/frontend/shared/logics/sourcesDataLogic'+import { NewMarketingAnalyticsDashboard } from 'products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard'import { marketingAnalyticsEmptyState } from 'products/marketing_analytics/frontend/emptyState/marketingAnalyticsEmptyState'import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'@@ -42,7 +43,6 @@ import {marketingAnalyticsTilesLogic,} from '../web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic'import { setupPlanLogic } from '../web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'-import { NewMarketingAnalyticsDashboard } from './NewMarketingAnalyticsDashboard'import { marketingOnboardingLogic } from './Onboarding/marketingOnboardingLogic'import { Onboarding } from './Onboarding/Onboarding'import { SetupTab } from './Setup/SetupTab'diff --git a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.goals.test.tsx b/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.goals.test.tsxindex 57031ab9b35d..2a8285a65fc5 100644--- a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.goals.test.tsx+++ b/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.goals.test.tsx@@ -10,7 +10,7 @@ import { setupPlanLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frimport { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { NewMarketingAnalyticsDashboard } from './NewMarketingAnalyticsDashboard'+import { NewMarketingAnalyticsDashboard } from 'products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard'jest.mock('scenes/web-analytics/tiles/WebAnalyticsTile', () => ({ webAnalyticsDataTableQueryContext: {} }))jest.mock('~/queries/Query/Query', () => ({ Query: () => null }))@@ -79,6 +79,8 @@ describe('Dashboard goal suggestions', () => {await waitFor(() => expect(screen.queryByText('Suggested conversion goals (1)')).toBeNull())} finally {cleanup()+ setupPlanLogic.actions.restoreAllDismissed()+ localStorage.removeItem('marketing-goal-suggestions-expanded')unmountSetup()unmountMarketing()}diff --git a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.sources.test.tsx b/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.sources.test.tsxindex 8b5811d557b1..1059b645428f 100644--- a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.sources.test.tsx+++ b/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.sources.test.tsx@@ -10,7 +10,7 @@ import { setupPlanLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frimport { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { NewMarketingAnalyticsDashboard } from './NewMarketingAnalyticsDashboard'+import { NewMarketingAnalyticsDashboard } from 'products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard'jest.mock('~/queries/Query/Query', () => ({ Query: () => null }))jest.mock('scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTable', () => ({@@ -71,6 +71,8 @@ it('reuses source suggestions, remembers collapse and opens their review in Setuawait waitFor(() => expect(screen.queryByText('Suggested ad sources (1)')).toBeNull())} finally {cleanup()+ setupPlanLogic.actions.restoreAllDismissed()+ localStorage.removeItem('marketing-source-suggestions-expanded')unmountSetup()unmountMarketing()}diff --git a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.test.tsx b/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.test.tsxindex a2949be49a7d..a4ad6713da17 100644--- a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.test.tsx+++ b/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.test.tsx@@ -3,15 +3,16 @@ import { useValues } from 'kea'import { FEATURE_FLAGS } from 'lib/constants'-import { NewMarketingAnalyticsDashboard } from './NewMarketingAnalyticsDashboard'+import { NewMarketingAnalyticsDashboard } from 'products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard'-jest.mock('./Setup/sectionRouting', () => ({ suggestionsForSection: () => [] }))+jest.mock('scenes/marketing-analytics/Setup/sectionRouting', () => ({ suggestionsForSection: () => [] }))-jest.mock('./Setup/SuggestionRow', () => ({ SuggestionRow: () => null }))+jest.mock('scenes/marketing-analytics/Setup/SuggestionRow', () => ({ SuggestionRow: () => null }))jest.mock('kea', () => ({ ...jest.requireActual('kea'), useValues: jest.fn(), useActions: () => ({}) }))jest.mock('@posthog/lemon-ui', () => ({LemonBanner: () => null,+ LemonCard: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,LemonSelect: ({value,onChange,@@ -98,6 +99,7 @@ describe('NewMarketingAnalyticsDashboard', () => {responseLoading: false,setupPlan: {},visibleSuggestions: [],+ trafficOrderBy: {},})render(<NewMarketingAnalyticsDashboard />)diff --git a/frontend/src/scenes/marketing-analytics/marketingAcquisitionLogic.test.ts b/frontend/src/scenes/marketing-analytics/marketingAcquisitionLogic.test.tsnew file mode 100644index 000000000000..311a714916bf--- /dev/null+++ b/frontend/src/scenes/marketing-analytics/marketingAcquisitionLogic.test.ts@@ -0,0 +1,73 @@+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { teamLogic } from 'scenes/teamLogic'++import { ConversionGoalFilter, NodeKind, WebAnalyticsOrderByFields } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'+import { PropertyFilterType, PropertyOperator } from '~/types'++import { marketingAcquisitionLogic } from 'products/marketing_analytics/frontend/dashboard/marketingAcquisitionLogic'++describe('marketingAcquisitionLogic', () => {+ it('keeps customer goal filters and falls back when a selected goal is removed or unmarked', async () => {+ initKeaTests()+ const logic = marketingAcquisitionLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ const goal: ConversionGoalFilter = {+ kind: NodeKind.EventsNode,+ event: 'customer_created',+ conversion_goal_id: 'customer',+ conversion_goal_name: 'New customer',+ schema_map: {},+ counts_as_customer: true,+ properties: [+ { type: PropertyFilterType.Event, key: 'plan', value: 'paid', operator: PropertyOperator.Exact },+ ],+ }+ const loadGoals = async (goals: ConversionGoalFilter[]): Promise<void> => {+ await expectLogic(logic, () =>+ teamLogic.actions.loadCurrentTeamSuccess({+ ...MOCK_DEFAULT_TEAM,+ marketing_analytics_config: { conversion_goals: goals },+ })+ ).toFinishAllListeners()+ }+ await loadGoals([goal, { ...goal, kind: NodeKind.ActionsNode, id: 42, conversion_goal_id: 'action' }])+ expect(logic.values.customerConversionGoal).toEqual({+ customEventName: 'customer_created',+ properties: goal.properties,+ })+ logic.actions.setCustomerGoalId('action')+ expect(logic.values.customerConversionGoal).toEqual({ actionId: 42, properties: goal.properties })+ await loadGoals([goal])+ expect(logic.values.selectedCustomerGoal?.conversion_goal_id).toBe('customer')+ await loadGoals([{ ...goal, counts_as_customer: false }])+ expect(logic.values.customerConversionGoal).toBeNull()+ logic.unmount()+ })++ it('toggles metric sorting independently for acquisition and engagement', () => {+ initKeaTests()+ const logic = marketingAcquisitionLogic()+ logic.mount()+ try {+ logic.actions.toggleTrafficSort('acquisition', WebAnalyticsOrderByFields.Views)+ expect(logic.values.trafficOrderBy.acquisition).toEqual([WebAnalyticsOrderByFields.Views, 'DESC'])+ logic.actions.toggleTrafficSort('acquisition', WebAnalyticsOrderByFields.Views)+ expect(logic.values.trafficOrderBy.acquisition).toEqual([WebAnalyticsOrderByFields.Views, 'ASC'])+ logic.actions.toggleTrafficSort('engagement', WebAnalyticsOrderByFields.BounceRate)+ expect(logic.values.trafficOrderBy.engagement).toEqual([WebAnalyticsOrderByFields.BounceRate, 'DESC'])+ expect(logic.values.trafficOrderBy.acquisition).toEqual([WebAnalyticsOrderByFields.Views, 'ASC'])+ logic.actions.toggleTrafficSort('acquisition', WebAnalyticsOrderByFields.UniqueConversions)+ expect(logic.values.trafficOrderBy.acquisition).toEqual([+ WebAnalyticsOrderByFields.UniqueConversions,+ 'DESC',+ ])+ } finally {+ logic.unmount()+ }+ })+})diff --git a/products/marketing_analytics/frontend/dashboard/CustomerAcquisitionCards.stories.tsx b/products/marketing_analytics/frontend/dashboard/CustomerAcquisitionCards.stories.tsxnew file mode 100644index 000000000000..e0ccff115a6f--- /dev/null+++ b/products/marketing_analytics/frontend/dashboard/CustomerAcquisitionCards.stories.tsx@@ -0,0 +1,43 @@+import { Meta, StoryObj } from '@storybook/react'++import { CustomerAcquisitionCards } from './CustomerAcquisitionCards'++const meta: Meta<typeof CustomerAcquisitionCards> = {+ title: 'Marketing Analytics/Customer acquisition cards',+ component: CustomerAcquisitionCards,+ decorators: [+ (Story) => (+ <div className="grid w-160 max-w-full grid-cols-2 gap-2">+ <Story />+ </div>+ ),+ ],+ args: {+ configurationLoading: false,+ configured: true,+ loading: false,+ error: false,+ customerResults: [{ key: 'unique conversions', kind: 'unit', value: 20, previous: 10 }],+ trafficResults: [{ key: 'visitors', kind: 'unit', value: 100, previous: 100 }],+ onConfigure: () => {},+ onRetry: () => {},+ },+}++export default meta+type Story = StoryObj<typeof CustomerAcquisitionCards>++export const Configured: Story = {}+export const Unconfigured: Story = { args: { configured: false } }+export const Loading: Story = {+ args: { loading: true },+ parameters: { testOptions: { waitForLoadersToDisappear: false } },+}+export const ConfigurationLoading: Story = {+ args: { configurationLoading: true, configured: false },+ parameters: { testOptions: { waitForLoadersToDisappear: false } },+}+export const Error: Story = { args: { error: true } }+export const NoCustomers: Story = {+ args: { customerResults: [{ key: 'unique conversions', kind: 'unit', value: 0, previous: 0 }] },+}diff --git a/products/marketing_analytics/frontend/dashboard/CustomerAcquisitionCards.tsx b/products/marketing_analytics/frontend/dashboard/CustomerAcquisitionCards.tsxnew file mode 100644index 000000000000..414773f5e4b9--- /dev/null+++ b/products/marketing_analytics/frontend/dashboard/CustomerAcquisitionCards.tsx@@ -0,0 +1,92 @@+import { IconInfo } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonCard, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'++import { SamplingRate } from '~/queries/nodes/OverviewGrid/OverviewGrid'+import { OverviewMetricCardGrid } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'+import { WebOverviewItem } from '~/queries/schema/schema-general'++import { customerAcquisitionMetrics } from './customerAcquisitionMetrics'++interface CustomerAcquisitionCardsProps {+ configurationLoading: boolean+ configured: boolean+ loading: boolean+ error: boolean+ customerResults?: WebOverviewItem[]+ trafficResults?: WebOverviewItem[]+ samplingRate?: SamplingRate+ onConfigure: () => void+ onRetry: () => void+}++export function CustomerAcquisitionCards({+ configurationLoading,+ configured,+ loading,+ error,+ customerResults,+ trafficResults,+ samplingRate,+ onConfigure,+ onRetry,+}: CustomerAcquisitionCardsProps): JSX.Element {+ return (+ <div className="contents">+ {configurationLoading ? (+ <>+ <LemonSkeleton className="h-36" />+ <LemonSkeleton className="h-36" />+ </>+ ) : !configured ? (+ <LemonCard hoverEffect={false} className="h-full !p-3 flex flex-col justify-between gap-2">+ <span className="font-semibold">New customers</span>+ <span className="text-secondary">Mark an event or action goal as a new customer goal.</span>+ <LemonButton+ size="small"+ type="secondary"+ onClick={onConfigure}+ data-attr="marketing-configure-customer-goal"+ >+ Configure in Setup+ </LemonButton>+ </LemonCard>+ ) : error ? (+ <LemonBanner+ type="error"+ action={{+ children: 'Retry',+ onClick: onRetry,+ }}+ >+ Could not load new customers.+ </LemonBanner>+ ) : (+ <OverviewMetricCardGrid+ layout="contents"+ items={customerAcquisitionMetrics(customerResults, trafficResults).map((item) => ({+ ...item,+ value: item.value,+ }))}+ loading={loading}+ numSkeletons={2}+ samplingRate={samplingRate}+ labelFromKey={(key) =>+ key === 'unique conversions' ? (+ 'New customers'+ ) : (+ <span className="inline-flex items-center gap-1">+ Customer-to-visitor ratio+ <Tooltip title="Unique people completing the selected customer goal divided by visitors with a pageview or screenview, multiplied by 100. Each row uses its own channel or campaign. This can exceed 100% when goals complete without pageviews or screenviews.">+ <IconInfo+ className="shrink-0 text-secondary"+ aria-label="How customer-to-visitor ratio is calculated"+ />+ </Tooltip>+ </span>+ )+ }+ />+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.tsx b/products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard.tsxsimilarity index 72%rename from frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.tsxrename to products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard.tsxindex f56764a9e5b6..3fa4d0a2ab0a 100644--- a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.tsx+++ b/products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard.tsx@@ -9,6 +9,8 @@ import { DateFilter } from 'lib/components/DateFilter/DateFilter'import { FEATURE_FLAGS } from 'lib/constants'import { useLocalStorage } from 'lib/hooks/useLocalStorage'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { suggestionsForSection } from 'scenes/marketing-analytics/Setup/sectionRouting'+import { SuggestionRow } from 'scenes/marketing-analytics/Setup/SuggestionRow'import { teamLogic } from 'scenes/teamLogic'import { MARKETING_ANALYTICS_DEFAULT_QUERY_TAGS } from 'scenes/web-analytics/common'import { AttributionTab } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTab'@@ -22,7 +24,6 @@ import {import { marketingAttributionLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAttributionLogic'import { BREAKDOWN_LABELS } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown'import { setupPlanLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'-import { webAnalyticsDataTableQueryContext } from 'scenes/web-analytics/tiles/WebAnalyticsTile'import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'import { OverviewMetricCardGrid } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'@@ -35,10 +36,10 @@ import {WebOverviewQueryResponse,WebStatsBreakdown,} from '~/queries/schema/schema-general'-import { QueryContext } from '~/queries/types'-import { suggestionsForSection } from './Setup/sectionRouting'-import { SuggestionRow } from './Setup/SuggestionRow'+import { CustomerAcquisitionCards } from './CustomerAcquisitionCards'+import { marketingAcquisitionLogic } from './marketingAcquisitionLogic'+import { marketingTrafficQueryContext } from './marketingTrafficQueryContext'const TRAFFIC_BREAKDOWNS = [{ value: WebStatsBreakdown.InitialChannelType, label: 'Channel' },@@ -49,16 +50,6 @@ const TRAFFIC_BREAKDOWNS = [{ value: WebStatsBreakdown.InitialPage, label: 'Landing page' },]-const QUERY_CONTEXT: QueryContext = {- ...webAnalyticsDataTableQueryContext,- columns: {- ...webAnalyticsDataTableQueryContext.columns,- visitors: { ...webAnalyticsDataTableQueryContext.columns?.visitors, renderTitle: () => <>Visitors</> },- views: { ...webAnalyticsDataTableQueryContext.columns?.views, renderTitle: () => <>Pageviews</> },- bounce_rate: { ...webAnalyticsDataTableQueryContext.columns?.bounce_rate, renderTitle: () => <>Bounce rate</> },- },-}-// Scaffold for the redesigned marketing analytics dashboard, gated behind the// `new-marketing-analytics-dashboard` feature flag.export function NewMarketingAnalyticsDashboard(): JSX.Element {@@ -110,6 +101,9 @@ export function NewMarketingAnalyticsDashboard(): JSX.Element {const isTraffic = activeSection === 'acquisition' || activeSection === 'engagement'const { revenueGoals, selectedRevenueGoalId, revenueQuery, breakdownBy } = useValues(marketingAttributionLogic)const { setRevenueGoalId, setBreakdownBy } = useActions(marketingAttributionLogic)+ const { customerGoals, selectedCustomerGoal, customerConversionGoal, trafficOrderBy } =+ useValues(marketingAcquisitionLogic)+ const { setCustomerGoalId, toggleTrafficSort } = useActions(marketingAcquisitionLogic)const { dateFilter, compareFilter, shouldFilterTestAccounts } = useValues(marketingAnalyticsLogic)const { setDates, setCompareFilter, setActiveTab, setSetupSection } = useActions(marketingAnalyticsLogic)const { setupPlan, setupPlanLoading, visibleSuggestions } = useValues(setupPlanLogic)@@ -149,6 +143,22 @@ export function NewMarketingAnalyticsDashboard(): JSX.Element {const { response, responseLoading, responseError } = useValues(overviewLogic)const { loadData } = useActions(overviewLogic)const overview = response as WebOverviewQueryResponse | undefined+ const customerOverviewLogic = dataNodeLogic({+ query: { ...query, conversionGoal: activeSection === 'acquisition' ? customerConversionGoal : null },+ key: 'marketing-acquisition-customers',+ autoLoad: !!customerConversionGoal && activeSection === 'acquisition',+ })+ const {+ response: customerResponse,+ responseLoading: customersLoading,+ responseError: customersError,+ } = useValues(customerOverviewLogic)+ const { loadData: loadCustomers } = useActions(customerOverviewLogic)+ const customerOverview = customerResponse as WebOverviewQueryResponse | undefined+ const reviewCustomerGoals = (): void => {+ setSetupSection(SetupSection.CONVERSION_GOALS)+ setActiveTab(MarketingAnalyticsTab.SETUP)+ }return (<div className="mt-4 flex flex-col gap-4">@@ -157,7 +167,19 @@ export function NewMarketingAnalyticsDashboard(): JSX.Element {{isTraffic && (<><CompareFilter compareFilter={compareFilter} updateCompareFilter={setCompareFilter} />- <LemonButton size="small" loading={responseLoading} onClick={() => loadData('force_async')}>+ <LemonButton+ size="small"+ loading={+ responseLoading ||+ (activeSection === 'acquisition' && !!customerConversionGoal && customersLoading)+ }+ onClick={() => {+ loadData('force_async')+ if (activeSection === 'acquisition' && customerConversionGoal) {+ loadCustomers('force_async')+ }+ }}+ >Reload summary</LemonButton></>@@ -268,21 +290,57 @@ export function NewMarketingAnalyticsDashboard(): JSX.Element {.map(({ title, keys }) => (<section key={title} className="flex flex-col gap-2" aria-label={title}><h2 className="mb-0">{title}</h2>- <OverviewMetricCardGrid- items={keys.flatMap((key) =>- (overview?.results?.filter((item) => item.key === key) ?? []).map(- (item) => ({- ...item,- value: item.value,- })- )+ <div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,12rem),1fr))] auto-rows-fr gap-2">+ <div className="contents">+ <OverviewMetricCardGrid+ layout="contents"+ items={keys.flatMap((key) =>+ (overview?.results?.filter((item) => item.key === key) ?? []).map(+ (item) => ({+ ...item,+ value: item.value,+ })+ )+ )}+ loading={responseLoading}+ numSkeletons={keys.length}+ samplingRate={overview?.samplingRate}+ preComputeStrategy={overview?.preComputeStrategy}+ labelFromKey={labelFromKey}+ />+ </div>+ {activeSection === 'acquisition' && (+ <CustomerAcquisitionCards+ configurationLoading={currentTeamLoading}+ configured={!!customerConversionGoal}+ loading={customersLoading || responseLoading}+ error={!!customersError}+ customerResults={customerOverview?.results}+ trafficResults={overview?.results}+ samplingRate={customerOverview?.samplingRate}+ onConfigure={reviewCustomerGoals}+ onRetry={() => loadCustomers('force_async')}+ />)}- loading={responseLoading}- numSkeletons={keys.length}- samplingRate={overview?.samplingRate}- preComputeStrategy={overview?.preComputeStrategy}- labelFromKey={labelFromKey}- />+ </div>+ {activeSection === 'acquisition' && customerConversionGoal && (+ <div className="flex flex-wrap items-center gap-2">+ <span>New customer goal</span>+ <LemonSelect+ aria-label="Customer goal"+ value={selectedCustomerGoal?.conversion_goal_id}+ onChange={setCustomerGoalId}+ options={customerGoals.map((goal) => ({+ value: goal.conversion_goal_id,+ label: goal.conversion_goal_name,+ }))}+ />+ <span className="text-secondary text-xs">+ Unique visitors completing this goal in the period. Use a+ once-per-customer goal to measure new customers.+ </span>+ </div>+ )}</section>))))}@@ -375,20 +433,34 @@ export function NewMarketingAnalyticsDashboard(): JSX.Element {source: {kind: NodeKind.WebStatsTableQuery,breakdownBy: trafficBreakdown,+ orderBy: trafficOrderBy[activeSection],dateRange,compareFilter,filterTestAccounts: shouldFilterTestAccounts,includeBounceRate: activeSection === 'engagement',+ includeTrafficMetrics: activeSection === 'acquisition',+ conversionGoal: activeSection === 'acquisition' ? customerConversionGoal : null,properties: [],limit: 25,tags: MARKETING_ANALYTICS_DEFAULT_QUERY_TAGS,},- hiddenColumns: activeSection === 'engagement' ? ['context.columns.views'] : [],+ hiddenColumns:+ activeSection === 'engagement'+ ? ['context.columns.views']+ : [+ 'context.columns.total_conversions',+ ...(customerConversionGoal ? ['context.columns.cross_sell'] : []),+ ],full: true,embedded: false,showOpenEditorButton: false,}}- context={{ ...QUERY_CONTEXT, compareFilter }}+ context={{+ ...marketingTrafficQueryContext(trafficOrderBy[activeSection], (field) =>+ toggleTrafficSort(activeSection, field)+ ),+ compareFilter,+ }}readOnly/></>diff --git a/products/marketing_analytics/frontend/dashboard/customerAcquisitionMetrics.test.ts b/products/marketing_analytics/frontend/dashboard/customerAcquisitionMetrics.test.tsnew file mode 100644index 000000000000..6c8e4f7560e3--- /dev/null+++ b/products/marketing_analytics/frontend/dashboard/customerAcquisitionMetrics.test.ts@@ -0,0 +1,64 @@+import { WebOverviewItem } from '~/queries/schema/schema-general'++import { customerAcquisitionMetrics } from './customerAcquisitionMetrics'++describe('customerAcquisitionMetrics', () => {+ it.each([+ ['normal', 2, 10, 1, 10, 20, 10, 100],+ ['over 100%', 3, 1, 1, 1, 300, 100, 200],+ ['zero visitors', 2, 0, 1, 10, undefined, 10, undefined],+ ['missing visitors', 2, undefined, 1, undefined, undefined, undefined, undefined],+ ['comparison off', 2, 10, undefined, undefined, 20, undefined, undefined],+ ['zero prior visitors', 2, 10, 1, 0, 20, undefined, undefined],+ ['zero baseline', 2, 10, 0, 10, 20, 0, undefined],+ ['zero customers', 0, 10, 1, 10, 0, 10, -100],+ ['missing customers value', undefined, 10, undefined, 10, undefined, undefined, undefined],+ ] as const)('%s', (_, count, visitors, priorCount, priorVisitors, value, previous, change) => {+ const customers: WebOverviewItem = {+ key: 'unique conversions',+ kind: 'unit',+ value: count,+ previous: priorCount,+ isIncreaseBad: false,+ }+ const rate: WebOverviewItem = {+ key: 'conversion rate',+ kind: 'percentage',+ value: 99,+ previous: 99,+ changeFromPreviousPct: 999,+ isIncreaseBad: false,+ }+ const traffic: WebOverviewItem = {+ key: 'visitors',+ kind: 'unit',+ value: visitors,+ previous: priorVisitors,+ }+ const result = customerAcquisitionMetrics([rate, customers], [traffic])+ expect(result[0]).toBe(customers)+ expect(result[1]).toEqual({ ...rate, value, previous, changeFromPreviousPct: change })+ expect(rate.value).toBe(99)+ })++ it('handles missing responses and missing visitors item', () => {+ expect(customerAcquisitionMetrics(undefined, undefined)).toEqual([])+ const customers: WebOverviewItem = {+ key: 'unique conversions',+ kind: 'unit',+ value: 3,+ }+ for (const traffic of [undefined, []]) {+ expect(customerAcquisitionMetrics([customers], traffic)).toEqual([+ customers,+ {+ key: 'conversion rate',+ kind: 'percentage',+ value: undefined,+ previous: undefined,+ changeFromPreviousPct: undefined,+ },+ ])+ }+ })+})diff --git a/products/marketing_analytics/frontend/dashboard/customerAcquisitionMetrics.ts b/products/marketing_analytics/frontend/dashboard/customerAcquisitionMetrics.tsnew file mode 100644index 000000000000..e17114c2ff50--- /dev/null+++ b/products/marketing_analytics/frontend/dashboard/customerAcquisitionMetrics.ts@@ -0,0 +1,30 @@+import { WebOverviewItem } from '~/queries/schema/schema-general'++export function customerAcquisitionMetrics(+ customerResults: WebOverviewItem[] | undefined,+ trafficResults: WebOverviewItem[] | undefined+): WebOverviewItem[] {+ const customers = customerResults?.find((item) => item.key === 'unique conversions')+ if (!customers) {+ return []+ }+ const visitors = trafficResults?.find((item) => item.key === 'visitors')+ const ratio = (numerator: number | undefined, denominator: number | undefined): number | undefined =>+ numerator != null && denominator != null && denominator > 0 ? (100 * numerator) / denominator : undefined+ const value = ratio(customers.value, visitors?.value)+ const previous = ratio(customers.previous, visitors?.previous)+ return [+ customers,+ {+ ...customerResults?.find((item) => item.key === 'conversion rate'),+ key: 'conversion rate',+ kind: 'percentage',+ value,+ previous,+ changeFromPreviousPct:+ value != null && previous != null && previous > 0+ ? Math.round((100 * (value - previous)) / previous)+ : undefined,+ },+ ]+}diff --git a/products/marketing_analytics/frontend/dashboard/marketingAcquisitionLogic.ts b/products/marketing_analytics/frontend/dashboard/marketingAcquisitionLogic.tsnew file mode 100644index 000000000000..8afd9d7076e8--- /dev/null+++ b/products/marketing_analytics/frontend/dashboard/marketingAcquisitionLogic.ts@@ -0,0 +1,108 @@+import { MakeLogicType, actions, connect, kea, path, reducers, selectors } from 'kea'++import { isWebAnalyticsPropertyFilter } from 'lib/components/PropertyFilters/utils'+import { marketingAnalyticsSettingsLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsSettingsLogic'+import { attributableConversionGoals } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown'++import {+ ConversionGoalFilter,+ NodeKind,+ WebAnalyticsConversionGoal,+ WebAnalyticsOrderByFields,+ WebAnalyticsOrderByDirection,+} from '~/queries/schema/schema-general'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface marketingAcquisitionLogicValues {+ conversion_goals: ConversionGoalFilter[] // marketingAnalyticsSettingsLogic+ customerConversionGoal: WebAnalyticsConversionGoal | null+ customerGoalId: string | null+ customerGoals: ConversionGoalFilter[]+ selectedCustomerGoal: ConversionGoalFilter | null+ trafficOrderBy: Record<string, [WebAnalyticsOrderByFields, WebAnalyticsOrderByDirection]>+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface marketingAcquisitionLogicActions {+ setCustomerGoalId: (customerGoalId: string) => {+ customerGoalId: string+ }+ toggleTrafficSort: (+ section: string,+ field: WebAnalyticsOrderByFields+ ) => {+ field: WebAnalyticsOrderByFields+ section: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface marketingAcquisitionLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ customerGoals: (conversion_goals: ConversionGoalFilter[]) => ConversionGoalFilter[]+ selectedCustomerGoal: (+ customerGoalId: string | null,+ customerGoals: ConversionGoalFilter[]+ ) => ConversionGoalFilter | null+ customerConversionGoal: (selectedCustomerGoal: ConversionGoalFilter | null) => WebAnalyticsConversionGoal | null+ }+}++export type marketingAcquisitionLogicType = MakeLogicType<+ marketingAcquisitionLogicValues,+ marketingAcquisitionLogicActions,+ Record<string, any>,+ marketingAcquisitionLogicMeta+>++export const marketingAcquisitionLogic = kea<marketingAcquisitionLogicType>([+ path(['products', 'marketing_analytics', 'dashboard', 'marketingAcquisitionLogic']),+ connect(() => ({ values: [marketingAnalyticsSettingsLogic, ['conversion_goals']] })),+ actions({+ setCustomerGoalId: (customerGoalId: string) => ({ customerGoalId }),+ toggleTrafficSort: (section: string, field: WebAnalyticsOrderByFields) => ({ section, field }),+ }),+ reducers({+ trafficOrderBy: [+ {} as Record<string, [WebAnalyticsOrderByFields, WebAnalyticsOrderByDirection]>,+ {+ toggleTrafficSort: (state, { section, field }) => ({+ ...state,+ [section]: [+ field,+ state[section]?.[0] === field && state[section]?.[1] === 'DESC' ? 'ASC' : 'DESC',+ ],+ }),+ },+ ],+ customerGoalId: [null as string | null, { setCustomerGoalId: (_, { customerGoalId }) => customerGoalId }],+ }),+ selectors({+ customerGoals: [+ (s) => [s.conversion_goals],+ (goals: ConversionGoalFilter[]): ConversionGoalFilter[] =>+ attributableConversionGoals(goals).filter((goal) => goal.counts_as_customer),+ ],+ selectedCustomerGoal: [+ (s) => [s.customerGoalId, s.customerGoals],+ (id: string | null, goals: ConversionGoalFilter[]): ConversionGoalFilter | null =>+ goals.find((goal) => goal.conversion_goal_id === id) ?? goals[0] ?? null,+ ],+ customerConversionGoal: [+ (s) => [s.selectedCustomerGoal],+ (goal: ConversionGoalFilter | null): WebAnalyticsConversionGoal | null => {+ const properties = goal?.properties+ if (properties && !properties.every(isWebAnalyticsPropertyFilter)) {+ return null+ }+ if (goal?.kind === NodeKind.ActionsNode) {+ return { actionId: goal.id, properties }+ }+ if (goal?.kind === NodeKind.EventsNode && goal.event) {+ return { customEventName: goal.event, properties }+ }+ return null+ },+ ],+ }),+])diff --git a/products/marketing_analytics/frontend/dashboard/marketingTrafficQueryContext.tsx b/products/marketing_analytics/frontend/dashboard/marketingTrafficQueryContext.tsxnew file mode 100644index 000000000000..fa83219aac3f--- /dev/null+++ b/products/marketing_analytics/frontend/dashboard/marketingTrafficQueryContext.tsx@@ -0,0 +1,63 @@+import { IconChevronDown } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { webAnalyticsDataTableQueryContext } from 'scenes/web-analytics/tiles/WebAnalyticsTile'++import { WebAnalyticsOrderByDirection, WebAnalyticsOrderByFields } from '~/queries/schema/schema-general'+import { QueryContext, QueryContextColumnTitleComponent } from '~/queries/types'++export function marketingTrafficQueryContext(+ orderBy: [WebAnalyticsOrderByFields, WebAnalyticsOrderByDirection] | undefined,+ onSort: (field: WebAnalyticsOrderByFields) => void+): QueryContext {+ const sortableTitle = (label: string, field: WebAnalyticsOrderByFields): QueryContextColumnTitleComponent =>+ function TrafficColumnTitle() {+ const selected = orderBy?.[0] === field+ return (+ <LemonButton+ size="xsmall"+ onClick={() => onSort(field)}+ sideIcon={+ <IconChevronDown+ className={selected ? (orderBy?.[1] === 'ASC' ? 'rotate-180' : '') : 'opacity-40'}+ />+ }+ aria-label={`Sort by ${label}${selected ? `, ${orderBy?.[1] === 'ASC' ? 'ascending' : 'descending'}` : ''}`}+ >+ {label}+ </LemonButton>+ )+ }++ return {+ ...webAnalyticsDataTableQueryContext,+ columns: {+ ...webAnalyticsDataTableQueryContext.columns,+ visitors: {+ ...webAnalyticsDataTableQueryContext.columns?.visitors,+ renderTitle: sortableTitle('Visitors', WebAnalyticsOrderByFields.Visitors),+ },+ sessions: {+ renderTitle: () => <>Sessions</>,+ render: webAnalyticsDataTableQueryContext.columns?.visitors?.render,+ align: 'right',+ },+ views: {+ ...webAnalyticsDataTableQueryContext.columns?.views,+ renderTitle: sortableTitle('Pageviews', WebAnalyticsOrderByFields.Views),+ },+ bounce_rate: {+ ...webAnalyticsDataTableQueryContext.columns?.bounce_rate,+ renderTitle: sortableTitle('Bounce rate', WebAnalyticsOrderByFields.BounceRate),+ },+ unique_conversions: {+ ...webAnalyticsDataTableQueryContext.columns?.unique_conversions,+ renderTitle: sortableTitle('New customers', WebAnalyticsOrderByFields.UniqueConversions),+ },+ conversion_rate: {+ ...webAnalyticsDataTableQueryContext.columns?.conversion_rate,+ renderTitle: sortableTitle('Customer-to-visitor ratio', WebAnalyticsOrderByFields.ConversionRate),+ },+ },+ }+}