: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): pick the metric shown in the visitors over time chart (#102256)
Javier Bahamondes5de0582c50cd
diff --git a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.test.tsx b/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.test.tsxindex 977b744d3f6e..4ebe0b91a2cf 100644--- a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.test.tsx+++ b/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.test.tsx@@ -15,12 +15,14 @@ jest.mock('@posthog/lemon-ui', () => ({value,onChange,options,+ 'aria-label': label,}: {value: stringonChange: (value: string) => voidoptions: { value: string; label: string }[]+ 'aria-label': string}) => (- <select aria-label="Traffic breakdown" value={value} onChange={(event) => onChange(event.target.value)}>+ <select aria-label={label} value={value} onChange={(event) => onChange(event.target.value)}>{options.map((option) => (<option key={option.value} value={option.value}>{option.label}@@ -94,6 +96,8 @@ describe('NewMarketingAnalyticsDashboard', () => {setupPlan: {},visibleSuggestions: [],trafficOrderBy: {},+ trafficChartMetric: 'visitors',+ trafficChartSeries: { kind: 'EventsNode', event: null, math: 'dau', custom_name: 'Visitors' },})render(<NewMarketingAnalyticsDashboard />)@@ -104,7 +108,12 @@ describe('NewMarketingAnalyticsDashboard', () => {expect(screen.getByText('Engagement')).not.toBeNull()expect(screen.queryByText('Attribution explorer')).toBeNull()expect(screen.queryByText('Retention explorer')).toBeNull()+ expect(screen.getByText('Visitors over time')).not.toBeNull()+ expect(screen.getByLabelText('Chart metric')).not.toBeNull()const trendBeforeBreakdown = screen.getByTestId('trend-query').textContent+ expect(JSON.parse(trendBeforeBreakdown || '{}').source.series).toEqual([+ { kind: 'EventsNode', event: null, math: 'dau', custom_name: 'Visitors' },+ ])fireEvent.change(screen.getByLabelText('Traffic breakdown'), { target: { value: 'InitialUTMCampaign' } })expect(JSON.parse(screen.getByTestId('traffic-query').textContent || '{}').source).toMatchObject({kind: 'WebStatsTableQuery',diff --git a/products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard.tsx b/products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard.tsxindex 108f9ee75b71..64c854054c7d 100644--- a/products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard.tsx+++ b/products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard.tsx@@ -34,11 +34,12 @@ import {WebOverviewQueryResponse,WebStatsBreakdown,} from '~/queries/schema/schema-general'-import { BaseMathType, ChartDisplayType, PropertyFilterType, PropertyOperator } from '~/types'+import { ChartDisplayType } from '~/types'import { CustomerAcquisitionCards } from './CustomerAcquisitionCards'import { marketingAcquisitionLogic } from './marketingAcquisitionLogic'import { marketingTrafficQueryContext } from './marketingTrafficQueryContext'+import { TRAFFIC_CHART_METRICS } from './trafficChartSeries'const TRAFFIC_BREAKDOWNS = [{ value: WebStatsBreakdown.InitialChannelType, label: 'Channel' },@@ -92,9 +93,15 @@ 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 {+ customerGoals,+ selectedCustomerGoal,+ customerConversionGoal,+ trafficOrderBy,+ trafficChartMetric,+ trafficChartSeries,+ } = useValues(marketingAcquisitionLogic)+ const { setCustomerGoalId, toggleTrafficSort, setTrafficChartMetric } = useActions(marketingAcquisitionLogic)const { dateFilter, compareFilter, shouldFilterTestAccounts } = useValues(marketingAnalyticsLogic)const { setDates, setCompareFilter, setActiveTab, setSetupSection } = useActions(marketingAnalyticsLogic)const { setupPlan, setupPlanLoading, visibleSuggestions } = useValues(setupPlanLogic)@@ -416,11 +423,30 @@ export function NewMarketingAnalyticsDashboard(): JSX.Element {<>{activeSection === 'acquisition' && (<LemonCard hoverEffect={false}>- <h3>Visitors over time</h3>+ <div className="flex flex-wrap justify-between items-center gap-2">+ <h3 className="mb-0">+ {`${TRAFFIC_CHART_METRICS.find(({ value }) => value === trafficChartMetric)?.label} over time`}+ </h3>+ <LemonSelect+ size="small"+ value={trafficChartMetric}+ onChange={(value) => value && setTrafficChartMetric(value)}+ options={TRAFFIC_CHART_METRICS.map(({ value, label }) => ({+ value,+ label,+ disabledReason:+ value === 'new_customers' && !customerConversionGoal+ ? 'Mark a conversion goal as a new customer goal in Setup first.'+ : undefined,+ }))}+ aria-label="Chart metric"+ data-attr="marketing-traffic-chart-metric"+ />+ </div><p className="text-secondary text-sm">All traffic in the selected period.</p><div className="flex flex-col h-80"><Query- key={activeSection}+ key={`${activeSection}-${trafficChartMetric}`}query={{kind: NodeKind.InsightVizNode,source: {@@ -430,22 +456,7 @@ export function NewMarketingAnalyticsDashboard(): JSX.Element {filterTestAccounts: shouldFilterTestAccounts,interval: 'day',tags: MARKETING_ANALYTICS_DEFAULT_QUERY_TAGS,- series: [- {- kind: NodeKind.EventsNode,- event: null,- properties: [- {- key: 'event',- type: PropertyFilterType.EventMetadata,- operator: PropertyOperator.Exact,- value: ['$pageview', '$screen'],- },- ],- math: BaseMathType.UniqueUsers,- custom_name: 'Visitors',- },- ],+ series: [trafficChartSeries],trendsFilter: { display: ChartDisplayType.ActionsLineGraph },},embedded: true,diff --git a/products/marketing_analytics/frontend/dashboard/marketingAcquisitionLogic.ts b/products/marketing_analytics/frontend/dashboard/marketingAcquisitionLogic.tsindex 8afd9d7076e8..813b2c8a0f79 100644--- a/products/marketing_analytics/frontend/dashboard/marketingAcquisitionLogic.ts+++ b/products/marketing_analytics/frontend/dashboard/marketingAcquisitionLogic.ts@@ -5,13 +5,17 @@ import { marketingAnalyticsSettingsLogic } from 'scenes/web-analytics/tabs/markeimport { attributableConversionGoals } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown'import {+ ActionsNode,ConversionGoalFilter,+ EventsNode,NodeKind,WebAnalyticsConversionGoal,WebAnalyticsOrderByFields,WebAnalyticsOrderByDirection,} from '~/queries/schema/schema-general'+import { TrafficChartMetric, trafficChartSeries } from './trafficChartSeries'+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface marketingAcquisitionLogicValues {conversion_goals: ConversionGoalFilter[] // marketingAnalyticsSettingsLogic@@ -19,6 +23,8 @@ export interface marketingAcquisitionLogicValues {customerGoalId: string | nullcustomerGoals: ConversionGoalFilter[]selectedCustomerGoal: ConversionGoalFilter | null+ trafficChartMetric: TrafficChartMetric+ trafficChartSeries: ActionsNode | EventsNodetrafficOrderBy: Record<string, [WebAnalyticsOrderByFields, WebAnalyticsOrderByDirection]>}@@ -27,6 +33,9 @@ export interface marketingAcquisitionLogicActions {setCustomerGoalId: (customerGoalId: string) => {customerGoalId: string}+ setTrafficChartMetric: (trafficChartMetric: TrafficChartMetric) => {+ trafficChartMetric: 'new_customers' | 'pageviews' | 'sessions' | 'visitors'+ }toggleTrafficSort: (section: string,field: WebAnalyticsOrderByFields@@ -45,6 +54,10 @@ export interface marketingAcquisitionLogicMeta {customerGoals: ConversionGoalFilter[]) => ConversionGoalFilter | nullcustomerConversionGoal: (selectedCustomerGoal: ConversionGoalFilter | null) => WebAnalyticsConversionGoal | null+ trafficChartSeries: (+ trafficChartMetric: 'new_customers' | 'pageviews' | 'sessions' | 'visitors',+ customerConversionGoal: WebAnalyticsConversionGoal | null+ ) => ActionsNode | EventsNode}}@@ -60,6 +73,7 @@ export const marketingAcquisitionLogic = kea<marketingAcquisitionLogicType>([connect(() => ({ values: [marketingAnalyticsSettingsLogic, ['conversion_goals']] })),actions({setCustomerGoalId: (customerGoalId: string) => ({ customerGoalId }),+ setTrafficChartMetric: (trafficChartMetric: TrafficChartMetric) => ({ trafficChartMetric }),toggleTrafficSort: (section: string, field: WebAnalyticsOrderByFields) => ({ section, field }),}),reducers({@@ -76,6 +90,10 @@ export const marketingAcquisitionLogic = kea<marketingAcquisitionLogicType>([},],customerGoalId: [null as string | null, { setCustomerGoalId: (_, { customerGoalId }) => customerGoalId }],+ trafficChartMetric: [+ 'visitors' as TrafficChartMetric,+ { setTrafficChartMetric: (_, { trafficChartMetric }) => trafficChartMetric },+ ],}),selectors({customerGoals: [@@ -104,5 +122,10 @@ export const marketingAcquisitionLogic = kea<marketingAcquisitionLogicType>([return null},],+ trafficChartSeries: [+ (s) => [s.trafficChartMetric, s.customerConversionGoal],+ (metric: TrafficChartMetric, goal: WebAnalyticsConversionGoal | null): EventsNode | ActionsNode =>+ trafficChartSeries(metric, goal),+ ],}),])diff --git a/products/marketing_analytics/frontend/dashboard/trafficChartSeries.test.ts b/products/marketing_analytics/frontend/dashboard/trafficChartSeries.test.tsnew file mode 100644index 000000000000..913549c58974--- /dev/null+++ b/products/marketing_analytics/frontend/dashboard/trafficChartSeries.test.ts@@ -0,0 +1,20 @@+import { NodeKind } from '~/queries/schema/schema-general'+import { BaseMathType } from '~/types'++import { trafficChartSeries } from './trafficChartSeries'++describe('trafficChartSeries', () => {+ const eventGoal = { customEventName: 'purchase' }+ const actionGoal = { actionId: 7 }++ it.each([+ ['visitors', null, { kind: NodeKind.EventsNode, event: null, math: BaseMathType.UniqueUsers }],+ ['sessions', eventGoal, { kind: NodeKind.EventsNode, event: null, math: BaseMathType.UniqueSessions }],+ ['pageviews', eventGoal, { kind: NodeKind.EventsNode, event: null, math: BaseMathType.TotalCount }],+ ['new_customers', eventGoal, { kind: NodeKind.EventsNode, event: 'purchase', math: BaseMathType.UniqueUsers }],+ ['new_customers', actionGoal, { kind: NodeKind.ActionsNode, id: 7, math: BaseMathType.UniqueUsers }],+ ['new_customers', null, { kind: NodeKind.EventsNode, event: null, math: BaseMathType.UniqueUsers }],+ ] as const)('%s with goal %j', (metric, goal, expected) => {+ expect(trafficChartSeries(metric, goal)).toMatchObject(expected)+ })+})diff --git a/products/marketing_analytics/frontend/dashboard/trafficChartSeries.ts b/products/marketing_analytics/frontend/dashboard/trafficChartSeries.tsnew file mode 100644index 000000000000..d7c01315bde3--- /dev/null+++ b/products/marketing_analytics/frontend/dashboard/trafficChartSeries.ts@@ -0,0 +1,47 @@+import { ActionsNode, EventsNode, NodeKind, WebAnalyticsConversionGoal } from '~/queries/schema/schema-general'+import { BaseMathType, PropertyFilterType, PropertyOperator } from '~/types'++export const TRAFFIC_CHART_METRICS = [+ { value: 'visitors', label: 'Visitors' },+ { value: 'sessions', label: 'Sessions' },+ { value: 'pageviews', label: 'Page views' },+ { value: 'new_customers', label: 'New customers' },+] as const++export type TrafficChartMetric = (typeof TRAFFIC_CHART_METRICS)[number]['value']++const pageviewOrScreen: EventsNode = {+ kind: NodeKind.EventsNode,+ event: null,+ properties: [+ {+ key: 'event',+ type: PropertyFilterType.EventMetadata,+ operator: PropertyOperator.Exact,+ value: ['$pageview', '$screen'],+ },+ ],+}++export function trafficChartSeries(+ metric: TrafficChartMetric,+ customerGoal: WebAnalyticsConversionGoal | null+): EventsNode | ActionsNode {+ if (metric === 'sessions') {+ return { ...pageviewOrScreen, math: BaseMathType.UniqueSessions, custom_name: 'Sessions' }+ }+ if (metric === 'pageviews') {+ return { ...pageviewOrScreen, math: BaseMathType.TotalCount, custom_name: 'Page views' }+ }+ if (metric === 'new_customers' && customerGoal) {+ const shared = {+ properties: customerGoal.properties,+ math: BaseMathType.UniqueUsers,+ custom_name: 'New customers',+ }+ return 'actionId' in customerGoal+ ? { kind: NodeKind.ActionsNode, id: customerGoal.actionId, ...shared }+ : { kind: NodeKind.EventsNode, event: customerGoal.customEventName, ...shared }+ }+ return { ...pageviewOrScreen, math: BaseMathType.UniqueUsers, custom_name: 'Visitors' }+}