: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(web-analytics): add weekly recap page (#65800)
Jordan Mryyan6c4926544eaf
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 3b6e764e4baf..211ad82cbd81 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -497,6 +497,7 @@ export const FEATURE_FLAGS = {WEB_ANALYTICS_METRIC_CARDS: 'web-analytics-metric-cards', // owner: #team-web-analyticsWEB_ANALYTICS_OPEN_URL: 'web-analytics-open-url', // owner: @lricoy #team-web-analyticsWEB_ANALYTICS_PRECOMPUTE_TOGGLE: 'web-analytics-precompute-toggle', // owner: @lricoy #team-web-analytics+ WEB_ANALYTICS_RECAP: 'web-analytics-recap', // owner: @jordanm-posthog #team-web-analyticsWEB_ANALYTICS_REGIONS_MAP: 'web-analytics-regions-map', // owner: @jordanm-posthog #team-web-analyticsWEB_ANALYTICS_SESSION_PROPERTY_CHARTS: 'web-analytics-session-property-charts', // owner: @lricoy #team-web-analyticsWEB_ANALYTICS_SHARE_NUDGE_V2: 'web-analytics-share-nudge-v2', // owner: @jordanm-posthog #team-web-analytics multivariate=control,control_b,banner,exportdiff --git a/frontend/src/scenes/appScenes.ts b/frontend/src/scenes/appScenes.tsindex ee5c11dce94c..1d5d2ab7ac46 100644--- a/frontend/src/scenes/appScenes.ts+++ b/frontend/src/scenes/appScenes.ts@@ -138,6 +138,7 @@ export const appScenes: Record<Scene | string, () => any> = {[Scene.WebAnalyticsWebVitals]: () => import('./web-analytics/WebAnalyticsScene'),[Scene.WebAnalyticsHealth]: () => import('./web-analytics/WebAnalyticsScene'),[Scene.WebAnalyticsLive]: () => import('./web-analytics/WebAnalyticsScene'),+ [Scene.WebAnalyticsRecap]: () => import('./web-analytics/recap/WebAnalyticsRecapScene'),[Scene.WebAnalytics]: () => import('./web-analytics/WebAnalyticsScene'),[Scene.Wizard]: () => import('./wizard/Wizard'),[Scene.OrganizationDeactivated]: () => import('./organization/Deactivated'),diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex 248d28eafbbf..5325d7f605d9 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -180,6 +180,7 @@ export enum Scene {WebAnalyticsWebVitals = 'WebAnalyticsWebVitals',WebAnalyticsHealth = 'WebAnalyticsHealth',WebAnalyticsLive = 'WebAnalyticsLive',+ WebAnalyticsRecap = 'WebAnalyticsRecap',WebScripts = 'WebScripts',Endpoints = 'Endpoints',Endpoint = 'Endpoint',@@ -339,6 +340,7 @@ export const sceneToAccessControlResourceType: Partial<Record<Scene, AccessContr[Scene.WebAnalyticsPageReports]: AccessControlResourceType.WebAnalytics,[Scene.WebAnalyticsWebVitals]: AccessControlResourceType.WebAnalytics,[Scene.WebAnalyticsHealth]: AccessControlResourceType.WebAnalytics,+ [Scene.WebAnalyticsRecap]: AccessControlResourceType.WebAnalytics,// Marketing Analytics[Scene.MarketingAnalytics]: AccessControlResourceType.WebAnalytics,diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.tsindex d79913288741..a8e5568e6cb3 100644--- a/frontend/src/scenes/scenes.ts+++ b/frontend/src/scenes/scenes.ts@@ -610,6 +610,13 @@ export const sceneConfigurations: Record<Scene | string, SceneConfig> = {description: 'Analyze your web analytics data to understand website performance and user behavior.',iconType: 'web_analytics',},+ [Scene.WebAnalyticsRecap]: {+ projectBased: true,+ name: 'Weekly recap',+ layout: 'app-raw',+ description: "A delightful weekly recap of this project's web analytics.",+ iconType: 'web_analytics',+ },[Scene.Wizard]: { projectBased: true, name: 'Wizard', layout: 'plain' },[Scene.OrganizationDeactivated]: {projectBased: false,@@ -785,6 +792,7 @@ export const routes: Record<string, [Scene | string, string]> = {[urls.webAnalyticsBotAnalytics()]: [Scene.WebAnalytics, 'webAnalyticsBotAnalytics'],[urls.webAnalyticsHealth()]: [Scene.WebAnalyticsHealth, 'webAnalyticsHealth'],[urls.webAnalyticsLive()]: [Scene.WebAnalyticsLive, 'webAnalyticsLive'],+ [urls.webAnalyticsRecap()]: [Scene.WebAnalyticsRecap, 'webAnalyticsRecap'],[urls.webAnalyticsPageReports()]: [Scene.WebAnalytics, 'webAnalyticsPageReports'],[urls.revenueAnalytics()]: [Scene.RevenueAnalytics, 'revenueAnalytics'],[urls.marketingAnalyticsApp()]: [Scene.MarketingAnalytics, 'marketingAnalytics'],diff --git a/frontend/src/scenes/urls.test.ts b/frontend/src/scenes/urls.test.tsindex 5fb6bbef9a70..62e1d5a4441e 100644--- a/frontend/src/scenes/urls.test.ts+++ b/frontend/src/scenes/urls.test.ts@@ -1,6 +1,10 @@import { urls } from './urls'describe('urls', () => {+ it('links to the web analytics recap scene', () => {+ expect(urls.webAnalyticsRecap()).toEqual('/web/recap')+ })+it.each(['Postgres', 'MySQL'] as const)('includes direct access method when opening the new %s source wizard in direct mode',(sourceType) => {diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.tsindex c6f2732cd88d..388c4eceb5ae 100644--- a/frontend/src/scenes/urls.ts+++ b/frontend/src/scenes/urls.ts@@ -313,6 +313,7 @@ export const urls = {inboxFindings: (): string => '/inbox/scouts/findings',webAnalyticsBotAnalytics: (): string => '/web/bots',webAnalyticsHealth: (): string => '/web/health',+ webAnalyticsRecap: (): string => '/web/recap',pipelineStatus: (): string => '/health/pipeline-status',sdkHealth: (): string => '/health/sdk-health',exports: (): string => '/exports',diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsSceneMenuBar.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsSceneMenuBar.tsxindex 438b6cfae6bb..35b2088ddca8 100644--- a/frontend/src/scenes/web-analytics/WebAnalyticsSceneMenuBar.tsx+++ b/frontend/src/scenes/web-analytics/WebAnalyticsSceneMenuBar.tsx@@ -1,6 +1,7 @@import { useActions, useValues } from 'kea'+import { router } from 'kea-router'-import { IconBolt, IconGear, IconSearch, IconStar, IconTarget, IconX } from '@posthog/icons'+import { IconBolt, IconGear, IconSearch, IconSparkles, IconStar, IconTarget, IconX } from '@posthog/icons'import { Badge, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'import { SceneMenuBarFileItems } from 'lib/components/Scenes/SceneMenuBarFileItems'@@ -97,6 +98,7 @@ function WebAnalyticsSceneMenuBarInner(): JSX.Element {const { openModal: openAchievementsModal } = useActions(webAnalyticsAchievementsLogic)const showAchievements = isWebAnalyticsAchievementsEnabled(featureFlags)+ const showRecap = !!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_RECAP]const showTileToggles = !!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_TILE_TOGGLES]const showQueryEngineToggle = !!featureFlags[FEATURE_FLAGS.SETTINGS_WEB_ANALYTICS_PRE_AGGREGATED_TABLES]const isUsingNewEngine = !!currentTeam?.modifiers?.useWebAnalyticsPreAggregatedTables@@ -142,6 +144,15 @@ function WebAnalyticsSceneMenuBarInner(): JSX.Element {</SceneMenuBarMenu>)}<SceneMenuBarMenu label="View" dataAttr="web-analytics-menubar-view">+ {showRecap && (+ <SceneMenuBarItem+ onClick={() => router.actions.push(urls.webAnalyticsRecap())}+ data-attr="web-analytics-menubar-weekly-recap"+ >+ <IconSparkles />+ Weekly recap+ </SceneMenuBarItem>+ )}<SceneMenuBarItemonClick={() => window.location.assign(urls.sessionAttributionExplorer())}data-attr="web-analytics-menubar-session-attribution"diff --git a/frontend/src/scenes/web-analytics/recap/WebAnalyticsRecapScene.stories.tsx b/frontend/src/scenes/web-analytics/recap/WebAnalyticsRecapScene.stories.tsxnew file mode 100644index 000000000000..6ebe9105ea1e--- /dev/null+++ b/frontend/src/scenes/web-analytics/recap/WebAnalyticsRecapScene.stories.tsx@@ -0,0 +1,97 @@+import { Meta } from '@storybook/react'++import { FEATURE_FLAGS } from 'lib/constants'+import { App } from 'scenes/App'+import { urls } from 'scenes/urls'++import { mswDecorator } from '~/mocks/browser'++import type { WebAnalyticsRecapResponseApi, WoWChangeApi } from 'products/web_analytics/frontend/generated/api.schemas'++const up = (percent: number): WoWChangeApi => ({+ percent,+ direction: 'Up',+ color: '#2f7d4f',+ text: `Up ${percent}%`,+ long_text: `Up ${percent}% from previous week`,+})++const recapMock: WebAnalyticsRecapResponseApi = {+ visitors: { current: 12402, previous: 10510, change: up(18) },+ pageviews: { current: 38211, previous: 33100, change: up(15) },+ sessions: { current: 15890, previous: 14002, change: up(13) },+ bounce_rate: { current: 41, previous: 47, change: { ...up(13), direction: 'Down', text: 'Down 13%' } },+ avg_session_duration: { current: '2m 34s', previous: '2m 10s', change: up(11) },+ top_pages: [+ { host: '', path: '/pricing', visitors: 3201, change: up(42) },+ { host: '', path: '/', visitors: 2890, change: up(8) },+ { host: '', path: '/blog/launch-week', visitors: 1502, change: up(120) },+ ],+ top_sources: [+ { name: 'google.com', visitors: 5400, change: up(20) },+ { name: 'twitter.com', visitors: 1820, change: up(60) },+ ],+ goals: [{ name: 'Signed up', conversions: 312, change: up(25) }],+ dashboard_url: '/project/1/web',+ persona: {+ id: 'traffic_magnet',+ name: 'Traffic Magnet',+ emoji: '🧲',+ blurb: 'Visitors surged +18% this week. Whatever you’re doing, keep doing it.',+ color: '#e0a23b',+ },+ highlights: [+ {+ id: 'milestone',+ emoji: '🎉',+ title: 'Milestone unlocked',+ value: '10,000 visitors',+ detail: 'You crossed a new visitor milestone this week.',+ },+ {+ id: 'rising_page',+ emoji: '📈',+ title: 'Rising star page',+ value: '/blog/launch-week',+ detail: 'Up 120% in visitors week over week.',+ },+ {+ id: 'top_source',+ emoji: '🌐',+ title: 'Top source',+ value: 'google.com',+ detail: '5,400 visitors came from here.',+ },+ ],+ period_label: 'Last 7 days',+ period_start: '2023-01-25',+ period_end: '2023-02-01',+ project_name: 'PostHog App + Website',+ recap_url: '/project/1/web/recap?utm_source=web_analytics_recap',+}++const meta: Meta = {+ component: App,+ title: 'Scenes-App/Web Analytics/Weekly Recap',+ // Animated scene (count-up + Hogfetti) — viewable in Storybook but excluded from visual snapshots.+ tags: ['test-skip'],+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ mockDate: '2023-02-01',+ pageUrl: urls.webAnalyticsRecap(),+ featureFlags: [FEATURE_FLAGS.WEB_ANALYTICS_RECAP],+ },+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/web_analytics/recap/': () => [200, recapMock],+ },+ }),+ ],+}+export default meta++export function WeeklyRecap(): JSX.Element {+ return <App />+}diff --git a/frontend/src/scenes/web-analytics/recap/WebAnalyticsRecapScene.tsx b/frontend/src/scenes/web-analytics/recap/WebAnalyticsRecapScene.tsxnew file mode 100644index 000000000000..429e846d678c--- /dev/null+++ b/frontend/src/scenes/web-analytics/recap/WebAnalyticsRecapScene.tsx@@ -0,0 +1,490 @@+import clsx from 'clsx'+import { useActions, useValues } from 'kea'+import { useEffect, useRef, useState } from 'react'++import { IconArrowRight, IconAtSign, IconSparkles } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { useHogfetti } from 'lib/components/Hogfetti/Hogfetti'+import { NotFound } from 'lib/components/NotFound'+import { FEATURE_FLAGS } from 'lib/constants'+import { IconLink, IconSlack } from 'lib/lemon-ui/icons'+import { Spinner } from 'lib/lemon-ui/Spinner'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { SceneExport } from 'scenes/sceneTypes'++import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'+import { SidePanelTab } from '~/types'++import type {+ GoalApi,+ RecapHighlightApi,+ TopPageApi,+ TopSourceApi,+ WebAnalyticsRecapResponseApi,+ WoWChangeApi,+} from 'products/web_analytics/frontend/generated/api.schemas'++import { formatRecapDateRange } from './recapDates'+import { CountUp, Reveal, ScrollHint, TrendPill } from './recapPrimitives'+import { webAnalyticsRecapLogic } from './webAnalyticsRecapLogic'++export const scene: SceneExport = {+ component: WebAnalyticsRecapScene,+ logic: webAnalyticsRecapLogic,+}++function buildRecapMaxPrompt(recap: WebAnalyticsRecapResponseApi): string {+ const change = (c: WoWChangeApi | null): string =>+ c ? ` (${c.direction === 'Up' ? 'up' : 'down'} ${c.percent}%)` : ''+ return (+ `!Here's my website analytics recap for the past week on ${recap.project_name}: ` ++ `${recap.visitors.current.toLocaleString()} visitors${change(recap.visitors.change)}, ` ++ `${recap.pageviews.current.toLocaleString()} pageviews${change(recap.pageviews.change)}, ` ++ `bounce rate ${Math.round(recap.bounce_rate.current)}%${change(recap.bounce_rate.change)}. ` ++ `What are the most important changes, and what should I dig into next?`+ )+}++function Section({+ children,+ className,+ overlay,+}: {+ children: React.ReactNode+ className?: string+ overlay?: React.ReactNode+}): JSX.Element {+ return (+ <section+ className={clsx(+ 'snap-start shrink-0 min-h-[72%] w-full flex flex-col items-center justify-center px-4 py-[8vh]',+ className+ )}+ >+ <div className="w-full max-w-3xl my-auto">{children}</div>+ {overlay}+ </section>+ )+}++function WhitePanel({ children, className }: { children: React.ReactNode; className?: string }): JSX.Element {+ return (+ <div+ className={clsx(+ 'rounded-3xl bg-surface-primary shadow-xl p-8 md:p-10 min-h-[56vh] flex flex-col justify-center',+ className+ )}+ >+ {children}+ </div>+ )+}++function MetricTile({+ label,+ value,+ change,+}: {+ label: string+ value: React.ReactNode+ change: WoWChangeApi | null+}): JSX.Element {+ return (+ <div className="flex flex-col gap-1 rounded-xl bg-surface-secondary p-4">+ <span className="text-sm text-secondary">{label}</span>+ <div className="flex items-baseline gap-2">+ <span className="text-3xl font-bold font-title tracking-tight tabular-nums">{value}</span>+ <TrendPill change={change} />+ </div>+ </div>+ )+}++function LeaderboardRow({+ rank,+ label,+ value,+ pct,+ change,+}: {+ rank: number+ label: string+ value: string+ pct: number+ change: WoWChangeApi | null+}): JSX.Element {+ return (+ <div className="relative flex items-center justify-between gap-3 overflow-hidden rounded-lg px-3 py-2.5">+ <div+ aria-hidden+ className="absolute inset-y-0 left-0 rounded-lg"+ // eslint-disable-next-line react/forbid-dom-props+ style={{+ width: `${Math.max(pct, 3)}%`,+ background: 'color-mix(in oklab, var(--recap-accent) 14%, transparent)',+ }}+ />+ <span className="relative flex min-w-0 items-center gap-3">+ <span+ className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-xs font-bold tabular-nums"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ background: 'color-mix(in oklab, var(--recap-accent) 24%, transparent)' }}+ >+ {rank}+ </span>+ <span className="truncate font-medium">{label}</span>+ </span>+ <span className="relative flex shrink-0 items-center gap-3">+ <span className="font-title font-semibold tabular-nums">{value}</span>+ <TrendPill change={change} />+ </span>+ </div>+ )+}++export function WebAnalyticsRecapScene(): JSX.Element {+ const { featureFlags } = useValues(featureFlagLogic)+ const { recap: loadedRecap, recapLoading } = useValues(webAnalyticsRecapLogic)+ const recap = loadedRecap as WebAnalyticsRecapResponseApi | null+ const {+ recordReachedEnd,+ recordCtaClicked,+ copyRecapLink,+ copyRecapForSlack,+ copyRecapForEmail,+ goToWebAnalytics,+ } = useActions(webAnalyticsRecapLogic)+ const { openSidePanel } = useActions(sidePanelStateLogic)+ const { trigger: triggerHogfetti, HogfettiComponent } = useHogfetti({ count: 60, power: 6, duration: 2500 })++ const endRef = useRef<HTMLDivElement>(null)+ const celebratedRef = useRef(false)+ const reachedEndRef = useRef(false)+ const [scrolledPastIntro, setScrolledPastIntro] = useState(false)++ // One celebratory burst once the recap has loaded.+ useEffect(() => {+ if (recap && !celebratedRef.current) {+ celebratedRef.current = true+ triggerHogfetti()+ }+ }, [recap, triggerHogfetti])++ useEffect(() => {+ const node = endRef.current+ if (!node || typeof IntersectionObserver === 'undefined') {+ return+ }+ const observer = new IntersectionObserver(([entry]) => {+ if (entry.isIntersecting && !reachedEndRef.current) {+ reachedEndRef.current = true+ recordReachedEnd()+ observer.disconnect()+ }+ })+ observer.observe(node)+ return () => observer.disconnect()+ }, [recap, recordReachedEnd])++ if (!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_RECAP]) {+ return <NotFound object="page" />+ }++ if (recapLoading && !recap) {+ return (+ <div className="flex flex-col items-center justify-center h-full gap-3">+ <Spinner className="text-3xl" />+ <span className="text-secondary">Wrapping up your week…</span>+ </div>+ )+ }++ if (!recap) {+ return (+ <div className="flex flex-col items-center justify-center h-full gap-2 text-center px-4">+ <span className="text-2xl">🦔</span>+ <h2>Your recap isn't ready yet</h2>+ <p className="text-secondary max-w-md">+ We couldn't build a recap for this project right now. Once there's some traffic, check back here.+ </p>+ <LemonButton type="primary" onClick={() => goToWebAnalytics('go_to_web_analytics')}>+ Go to web analytics+ </LemonButton>+ </div>+ )+ }++ const persona = recap.persona+ const maxPageVisitors = Math.max(...recap.top_pages.map((page) => page.visitors), 1)+ const maxSourceVisitors = Math.max(...recap.top_sources.map((source) => source.visitors), 1)+ const maxGoalConversions = Math.max(...recap.goals.map((goal) => goal.conversions), 1)++ return (+ <div+ className="WebAnalyticsRecap relative isolate h-full overflow-y-auto overflow-x-hidden overscroll-contain snap-y snap-mandatory"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ '--recap-accent': persona.color } as React.CSSProperties}+ >+ <HogfettiComponent />++ {/* Cohesive full-bleed backdrop pinned behind the snapping sections */}+ <div aria-hidden className="sticky top-0 z-0 h-0">+ <div+ className="absolute top-0 left-0 right-0 h-screen -z-10"+ // eslint-disable-next-line react/forbid-dom-props+ style={{+ background:+ 'radial-gradient(1200px 600px at 50% -10%, color-mix(in oklab, var(--recap-accent) 18%, transparent), transparent 60%), linear-gradient(180deg, var(--color-bg-surface-secondary), var(--color-bg-primary))',+ }}+ />+ </div>++ <div className="contents">+ <Section+ className="text-center text-white relative"+ overlay={+ <ScrollHint+ className={clsx(+ 'absolute bottom-[6vh] left-1/2 -translate-x-1/2 transition-opacity duration-500',+ scrolledPastIntro && 'opacity-0'+ )}+ />+ }+ >+ <Reveal>+ <div+ className="rounded-2xl px-6 py-16 md:py-20 shadow-xl min-h-[56vh] flex flex-col justify-center"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ background: 'linear-gradient(135deg, #1d1f27 0%, #2b2333 100%)' }}+ >+ <p className="text-sm uppercase tracking-widest opacity-70">+ {formatRecapDateRange(recap)}+ </p>+ <h1 className="font-title text-5xl md:text-6xl font-extrabold tracking-tight mt-3 text-white">+ {recap.project_name}'s week on the web+ </h1>+ </div>+ </Reveal>+ </Section>++ {/* 2. Headline number */}+ <Section className="text-center">+ <Reveal onInView={() => setScrolledPastIntro(true)}>+ <WhitePanel className="text-center">+ <p className="text-sm uppercase tracking-widest text-secondary">+ This week your website welcomed+ </p>+ <div className="flex flex-1 flex-col items-center justify-center">+ <div className="flex items-end justify-center gap-3">+ <CountUp+ value={recap.visitors.current}+ className="font-title text-7xl md:text-8xl font-bold leading-none tracking-tight text-[color:var(--recap-accent)]"+ />+ <TrendPill change={recap.visitors.change} className="text-xl mb-2" />+ </div>+ <p className="text-2xl text-secondary mt-3">visitors</p>+ </div>+ </WhitePanel>+ </Reveal>+ </Section>++ {/* 3. Persona */}+ <Section className="text-center">+ <Reveal>+ <div+ className="rounded-2xl p-10 text-white shadow-xl min-h-[56vh] flex flex-col justify-center"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ background: persona.color }}+ >+ <div className="text-6xl">{persona.emoji}</div>+ <p className="uppercase tracking-widest opacity-80 mt-4 text-sm">Your persona</p>+ <h2 className="font-title text-4xl font-extrabold mt-1 text-white">{persona.name}</h2>+ <p className="text-lg opacity-90 mt-3 max-w-xl mx-auto">{persona.blurb}</p>+ </div>+ </Reveal>+ </Section>++ {/* 4. Vital signs */}+ <Section>+ <Reveal>+ <WhitePanel>+ <h3 className="font-title text-2xl font-bold mb-4 text-center">Your week in numbers</h3>+ <div className="grid grid-cols-2 gap-3 flex-1 content-center">+ <MetricTile+ label="Pageviews"+ value={<CountUp value={recap.pageviews.current} />}+ change={recap.pageviews.change}+ />+ <MetricTile+ label="Sessions"+ value={<CountUp value={recap.sessions.current} />}+ change={recap.sessions.change}+ />+ <MetricTile+ label="Bounce rate"+ value={`${Math.round(recap.bounce_rate.current)}%`}+ change={recap.bounce_rate.change}+ />+ <MetricTile+ label="Avg. session"+ value={recap.avg_session_duration.current}+ change={recap.avg_session_duration.change}+ />+ </div>+ </WhitePanel>+ </Reveal>+ </Section>++ {/* 5. Top pages */}+ {recap.top_pages.length > 0 && (+ <Section>+ <Reveal>+ <WhitePanel>+ <h3 className="font-title text-2xl font-bold mb-4 text-center">Your top pages</h3>+ <div className="flex flex-1 flex-col justify-center gap-1.5">+ {recap.top_pages.map((page: TopPageApi, index: number) => (+ <LeaderboardRow+ key={`${page.host}::${page.path}`}+ rank={index + 1}+ label={page.path || '/'}+ value={page.visitors.toLocaleString()}+ pct={(page.visitors / maxPageVisitors) * 100}+ change={page.change}+ />+ ))}+ </div>+ </WhitePanel>+ </Reveal>+ </Section>+ )}++ {/* 6. Top sources */}+ {recap.top_sources.length > 0 && (+ <Section>+ <Reveal>+ <WhitePanel>+ <h3 className="font-title text-2xl font-bold mb-4 text-center">Where they came from</h3>+ <div className="flex flex-1 flex-col justify-center gap-1.5">+ {recap.top_sources.map((source: TopSourceApi, index: number) => (+ <LeaderboardRow+ key={`${source.name}-${index}`}+ rank={index + 1}+ label={source.name}+ value={source.visitors.toLocaleString()}+ pct={(source.visitors / maxSourceVisitors) * 100}+ change={source.change}+ />+ ))}+ </div>+ </WhitePanel>+ </Reveal>+ </Section>+ )}++ {/* 7. Goals */}+ {recap.goals.length > 0 && (+ <Section>+ <Reveal>+ <WhitePanel>+ <h3 className="font-title text-2xl font-bold mb-4 text-center">Goals you hit</h3>+ <div className="flex flex-1 flex-col justify-center gap-1.5">+ {recap.goals.map((goal: GoalApi, index: number) => (+ <LeaderboardRow+ key={`${goal.name}-${index}`}+ rank={index + 1}+ label={goal.name}+ value={goal.conversions.toLocaleString()}+ pct={(goal.conversions / maxGoalConversions) * 100}+ change={goal.change}+ />+ ))}+ </div>+ </WhitePanel>+ </Reveal>+ </Section>+ )}++ {/* 8. Highlights / badges */}+ {recap.highlights.length > 0 && (+ <Section>+ <Reveal>+ <WhitePanel>+ <h3 className="font-title text-2xl font-bold mb-4 text-center">This week's wins</h3>+ <div className="grid grid-cols-1 md:grid-cols-3 gap-3 flex-1 content-center">+ {recap.highlights.map((highlight: RecapHighlightApi) => (+ <div+ key={highlight.id}+ className="flex flex-col gap-1 rounded-xl bg-surface-secondary p-4 text-center"+ >+ <span className="text-3xl">{highlight.emoji}</span>+ <span className="text-sm text-secondary">{highlight.title}</span>+ <span className="text-lg font-bold truncate">{highlight.value}</span>+ <span className="text-xs text-muted">{highlight.detail}</span>+ </div>+ ))}+ </div>+ </WhitePanel>+ </Reveal>+ </Section>+ )}++ {/* 9. Max's take */}+ <Section className="text-center">+ <Reveal>+ <div className="rounded-3xl bg-surface-primary shadow-xl p-10 min-h-[56vh] flex flex-col items-center justify-center">+ <IconSparkles className="text-4xl text-accent mx-auto" />+ <h3 className="font-title text-2xl font-bold mt-3">Curious what's behind the numbers?</h3>+ <p className="text-secondary mt-2">+ PostHog AI can explain what changed this week and what to look at next.+ </p>+ <LemonButton+ type="primary"+ className="mt-5 mx-auto"+ icon={<IconSparkles />}+ onClick={() => {+ recordCtaClicked('ask_posthog_ai')+ openSidePanel(SidePanelTab.Max, buildRecapMaxPrompt(recap))+ }}+ >+ Ask PostHog AI about your week+ </LemonButton>+ </div>+ </Reveal>+ </Section>++ {/* 10. Outro & share */}+ <Section className="text-center">+ <Reveal>+ <WhitePanel>+ <h2 className="font-title text-3xl font-extrabold">See you next week 👋</h2>+ <p className="text-secondary mt-2">Share your week or dive into the details.</p>+ <div className="flex flex-wrap items-center justify-center gap-2 mt-6">+ <LemonButton type="secondary" icon={<IconLink />} onClick={copyRecapLink}>+ Copy link+ </LemonButton>+ <LemonButton type="secondary" icon={<IconSlack />} onClick={copyRecapForSlack}>+ Copy for Slack+ </LemonButton>+ <LemonButton type="secondary" icon={<IconAtSign />} onClick={copyRecapForEmail}>+ Copy for email+ </LemonButton>+ <LemonButton+ type="primary"+ sideIcon={<IconArrowRight />}+ onClick={() => {+ goToWebAnalytics('view_dashboard')+ }}+ >+ Explore full dashboard+ </LemonButton>+ </div>+ </WhitePanel>+ </Reveal>+ </Section>++ <div ref={endRef} aria-hidden className="h-[30vh]" />+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/web-analytics/recap/recapDates.ts b/frontend/src/scenes/web-analytics/recap/recapDates.tsnew file mode 100644index 000000000000..fe6fcecb1e2e--- /dev/null+++ b/frontend/src/scenes/web-analytics/recap/recapDates.ts@@ -0,0 +1,18 @@+import type { WebAnalyticsRecapResponseApi } from 'products/web_analytics/frontend/generated/api.schemas'++function parseApiDate(date: string): Date {+ const [year, month, day] = date.split('-').map(Number)+ return new Date(year, month - 1, day)+}++function formatApiDate(date: string): string {+ return new Intl.DateTimeFormat(undefined, {+ month: 'short',+ day: 'numeric',+ year: 'numeric',+ }).format(parseApiDate(date))+}++export function formatRecapDateRange(recap: Pick<WebAnalyticsRecapResponseApi, 'period_start' | 'period_end'>): string {+ return `${formatApiDate(recap.period_start)} - ${formatApiDate(recap.period_end)}`+}diff --git a/frontend/src/scenes/web-analytics/recap/recapPrimitives.tsx b/frontend/src/scenes/web-analytics/recap/recapPrimitives.tsxnew file mode 100644index 000000000000..c40519c0c4e2--- /dev/null+++ b/frontend/src/scenes/web-analytics/recap/recapPrimitives.tsx@@ -0,0 +1,169 @@+import clsx from 'clsx'+import { useEffect, useRef, useState } from 'react'++import { IconChevronDown } from '@posthog/icons'++import type { WoWChangeApi } from 'products/web_analytics/frontend/generated/api.schemas'++function prefersReducedMotion(): boolean {+ return typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches+}++function useInView<T extends HTMLElement>(threshold = 0.25): [React.RefObject<T>, boolean] {+ const ref = useRef<T>(null)+ const [inView, setInView] = useState(false)++ useEffect(() => {+ const node = ref.current+ if (!node) {+ return+ }+ if (prefersReducedMotion() || typeof IntersectionObserver === 'undefined') {+ setInView(true)+ return+ }+ const observer = new IntersectionObserver(+ ([entry]) => {+ if (entry.isIntersecting) {+ setInView(true)+ observer.disconnect()+ }+ },+ { threshold }+ )+ observer.observe(node)+ return () => observer.disconnect()+ }, [threshold])++ return [ref, inView]+}++/** Fades and slides children up the first time they scroll into view. Honors prefers-reduced-motion. */+export function Reveal({+ children,+ className,+ delayMs = 0,+ onInView,+}: {+ children: React.ReactNode+ className?: string+ delayMs?: number+ onInView?: () => void+}): JSX.Element {+ const [ref, inView] = useInView<HTMLDivElement>()+ useEffect(() => {+ if (inView) {+ onInView?.()+ }+ // onInView is intentionally not a dep — fire once when the section first enters view+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [inView])+ return (+ <div+ ref={ref}+ className={clsx(+ 'transition-all duration-700 ease-out motion-reduce:transition-none',+ inView ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8',+ className+ )}+ style={{ transitionDelay: `${delayMs}ms` }}+ >+ {children}+ </div>+ )+}++/** Counts a number up from zero the first time it scrolls into view. */+export function CountUp({+ value,+ durationMs = 1400,+ className,+ suffix = '',+}: {+ value: number+ durationMs?: number+ className?: string+ suffix?: string+}): JSX.Element {+ const [ref, inView] = useInView<HTMLSpanElement>()+ const [display, setDisplay] = useState(0)++ useEffect(() => {+ if (!inView) {+ return+ }+ if (prefersReducedMotion()) {+ setDisplay(value)+ return+ }+ let raf = 0+ let start: number | null = null+ const tick = (now: number): void => {+ start ??= now+ const progress = Math.min((now - start) / durationMs, 1)+ // easeOutCubic for a satisfying deceleration+ const eased = 1 - Math.pow(1 - progress, 3)+ setDisplay(value * eased)+ if (progress < 1) {+ raf = requestAnimationFrame(tick)+ }+ }+ raf = requestAnimationFrame(tick)+ return () => cancelAnimationFrame(raf)+ }, [inView, value, durationMs])++ return (+ <span ref={ref} className={clsx('tabular-nums', className)}>+ {Math.round(display).toLocaleString()}+ {suffix}+ </span>+ )+}++/** Small up/down pill colored by the backend's good/bad signal. */+export function TrendPill({+ change,+ className,+}: {+ change: WoWChangeApi | null+ className?: string+}): JSX.Element | null {+ if (!change) {+ return null+ }+ return (+ <span+ className={clsx('inline-flex items-center gap-0.5 text-sm font-semibold', className)}+ style={{ color: change.color }}+ title={change.long_text}+ >+ <span className="leading-none">{change.direction === 'Up' ? '↑' : '↓'}</span>+ {change.percent}%+ </span>+ )+}++/** A decorative "scroll down to continue" affordance. Hidden entirely for reduced-motion users. */+export function ScrollHint({+ label = 'Scroll to continue',+ className,+}: {+ label?: string+ className?: string+}): JSX.Element | null {+ if (prefersReducedMotion()) {+ return null+ }+ return (+ <div+ aria-hidden+ className={clsx(+ 'pointer-events-none flex flex-col items-center gap-1 text-secondary select-none',+ className+ )}+ >+ <span className="text-xs uppercase tracking-widest opacity-70">{label}</span>+ <IconChevronDown className="text-2xl animate-bounce" />+ </div>+ )+}diff --git a/frontend/src/scenes/web-analytics/recap/webAnalyticsRecapLogic.test.ts b/frontend/src/scenes/web-analytics/recap/webAnalyticsRecapLogic.test.tsnew file mode 100644index 000000000000..b2d95ffb0d72--- /dev/null+++ b/frontend/src/scenes/web-analytics/recap/webAnalyticsRecapLogic.test.ts@@ -0,0 +1,245 @@+import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { copyToClipboard } from 'lib/utils/copyToClipboard'+import { urls } from 'scenes/urls'++import { initKeaTests } from '~/test/init'++import { webAnalyticsRecap } from 'products/web_analytics/frontend/generated/api'+import type { WebAnalyticsRecapResponseApi } from 'products/web_analytics/frontend/generated/api.schemas'++import { webAnalyticsRecapLogic } from './webAnalyticsRecapLogic'++jest.mock('products/web_analytics/frontend/generated/api', () => ({+ webAnalyticsRecap: jest.fn(),+}))+jest.mock('lib/utils/copyToClipboard', () => ({+ copyToClipboard: jest.fn().mockResolvedValue(true),+}))++const mockRecap = webAnalyticsRecap as jest.Mock++function makeRecap(overrides: Partial<WebAnalyticsRecapResponseApi> = {}): WebAnalyticsRecapResponseApi {+ return {+ visitors: { current: 100, previous: 80, change: null },+ pageviews: { current: 200, previous: 150, change: null },+ sessions: { current: 90, previous: 70, change: null },+ bounce_rate: { current: 40, previous: 45, change: null },+ avg_session_duration: { current: '1m 20s', previous: '1m', change: null },+ top_pages: [],+ top_sources: [],+ goals: [],+ dashboard_url: 'http://localhost/project/1/web',+ persona: { id: 'rising_star', name: 'Rising Star', emoji: '🚀', blurb: 'Up!', color: '#6a5af0' },+ highlights: [],+ period_label: 'Last 7 days',+ period_start: '2025-01-22',+ period_end: '2025-01-29',+ project_name: 'Test',+ recap_url: 'http://localhost/project/1/web/recap?utm_source=web_analytics_recap',+ ...overrides,+ }+}++describe('webAnalyticsRecapLogic', () => {+ let logic: ReturnType<typeof webAnalyticsRecapLogic.build>++ beforeEach(() => {+ initKeaTests()+ mockRecap.mockReset()+ jest.spyOn(posthog, 'capture').mockReturnValue(null as any)+ ;(copyToClipboard as jest.Mock).mockClear()+ })++ afterEach(() => {+ logic?.unmount()+ jest.restoreAllMocks()+ })++ it('loads the recap on mount and records opened + persona events', async () => {+ mockRecap.mockResolvedValue(makeRecap())+ logic = webAnalyticsRecapLogic()+ logic.mount()++ await expectLogic(logic)+ .toDispatchActions(['recordOpened', 'loadRecapSuccess'])+ .toMatchValues({+ recap: expect.objectContaining({ persona: expect.objectContaining({ id: 'rising_star' }) }),+ recapLoading: false,+ })++ expect(mockRecap).toHaveBeenCalledWith(expect.any(String), { days: 7 })+ expect(posthog.capture).toHaveBeenCalledWith(+ 'web_analytics_recap_opened',+ expect.objectContaining({+ period_start: null,+ period_end: null,+ persona: null,+ visitors: null,+ })+ )+ expect(posthog.capture).toHaveBeenCalledWith(+ 'web_analytics_recap_persona_assigned',+ expect.objectContaining({+ period_start: '2025-01-22',+ period_end: '2025-01-29',+ persona: 'rising_star',+ visitors: 100,+ })+ )+ })++ it('copies the recap link and records the share', async () => {+ mockRecap.mockResolvedValue(makeRecap())+ logic = webAnalyticsRecapLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadRecapSuccess'])++ await expectLogic(logic, () => {+ logic.actions.copyRecapLink()+ }).toDispatchActions(['copyRecapLink', 'recordShared'])++ expect(copyToClipboard).toHaveBeenCalledWith(+ 'http://localhost/project/1/web/recap?utm_source=web_analytics_recap',+ 'recap link'+ )+ expect(posthog.capture).toHaveBeenCalledWith(+ 'web_analytics_recap_button_clicked',+ expect.objectContaining({+ button: 'copy_link',+ intent: 'share',+ destination: 'clipboard',+ persona: 'rising_star',+ })+ )+ expect(posthog.capture).toHaveBeenCalledWith(+ 'web_analytics_recap_shared',+ expect.objectContaining({ method: 'copy_link', period_start: '2025-01-22' })+ )+ })++ it('does not record a share when the clipboard write fails', async () => {+ mockRecap.mockResolvedValue(makeRecap())+ ;(copyToClipboard as jest.Mock).mockResolvedValueOnce(false)+ logic = webAnalyticsRecapLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadRecapSuccess'])++ await expectLogic(logic, () => {+ logic.actions.copyRecapLink()+ }).toDispatchActions(['copyRecapLink', 'recordButtonClicked'])+ await new Promise((resolve) => setTimeout(resolve, 0))++ expect(copyToClipboard).toHaveBeenCalled()+ expect(posthog.capture).not.toHaveBeenCalledWith('web_analytics_recap_shared', expect.anything())+ })++ it('copies Slack-ready recap text and records the share', async () => {+ mockRecap.mockResolvedValue(makeRecap())+ logic = webAnalyticsRecapLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadRecapSuccess'])++ await expectLogic(logic, () => {+ logic.actions.copyRecapForSlack()+ }).toDispatchActions(['copyRecapForSlack', 'recordShared'])++ expect(copyToClipboard).toHaveBeenCalledWith(expect.stringContaining('*Test website recap*'), 'Slack recap')+ expect(copyToClipboard).toHaveBeenCalledWith(expect.stringContaining('100 visitors'), 'Slack recap')+ expect(posthog.capture).toHaveBeenCalledWith(+ 'web_analytics_recap_button_clicked',+ expect.objectContaining({+ button: 'copy_slack',+ intent: 'share',+ destination: 'clipboard',+ })+ )+ expect(posthog.capture).toHaveBeenCalledWith(+ 'web_analytics_recap_shared',+ expect.objectContaining({ method: 'copy_slack', persona: 'rising_star' })+ )+ })++ it('copies email-ready recap text and records the share', async () => {+ mockRecap.mockResolvedValue(makeRecap())+ logic = webAnalyticsRecapLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadRecapSuccess'])++ await expectLogic(logic, () => {+ logic.actions.copyRecapForEmail()+ }).toDispatchActions(['copyRecapForEmail', 'recordShared'])++ expect(copyToClipboard).toHaveBeenCalledWith(+ expect.stringContaining('Subject: Test website recap:'),+ 'email recap'+ )+ expect(copyToClipboard).toHaveBeenCalledWith(expect.stringContaining('View the full recap:'), 'email recap')+ expect(posthog.capture).toHaveBeenCalledWith(+ 'web_analytics_recap_button_clicked',+ expect.objectContaining({+ button: 'copy_email',+ intent: 'share',+ destination: 'clipboard',+ })+ )+ expect(posthog.capture).toHaveBeenCalledWith(+ 'web_analytics_recap_shared',+ expect.objectContaining({ method: 'copy_email', persona: 'rising_star' })+ )+ })++ it('records PostHog AI CTA usage with recap context', async () => {+ mockRecap.mockResolvedValue(makeRecap())+ logic = webAnalyticsRecapLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadRecapSuccess'])++ await expectLogic(logic, () => {+ logic.actions.recordCtaClicked('ask_posthog_ai')+ }).toDispatchActions(['recordCtaClicked', 'recordButtonClicked'])++ expect(posthog.capture).toHaveBeenCalledWith(+ 'web_analytics_recap_button_clicked',+ expect.objectContaining({+ button: 'ask_posthog_ai',+ intent: 'posthog_ai_usage',+ destination: 'posthog_ai_side_panel',+ period_end: '2025-01-29',+ })+ )+ expect(posthog.capture).toHaveBeenCalledWith(+ 'web_analytics_recap_cta_clicked',+ expect.objectContaining({ cta: 'ask_posthog_ai', persona: 'rising_star' })+ )+ })++ it('routes Web analytics CTA clicks with recap attribution params', async () => {+ const pushSpy = jest.spyOn(router.actions, 'push').mockImplementation(() => {})+ mockRecap.mockResolvedValue(makeRecap())+ logic = webAnalyticsRecapLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadRecapSuccess'])++ await expectLogic(logic, () => {+ logic.actions.goToWebAnalytics('view_dashboard')+ }).toDispatchActions(['goToWebAnalytics', 'recordCtaClicked', 'recordButtonClicked'])++ expect(posthog.capture).toHaveBeenCalledWith(+ 'web_analytics_recap_button_clicked',+ expect.objectContaining({+ button: 'view_dashboard',+ intent: 'web_analytics_view',+ destination: 'web_analytics_dashboard',+ })+ )+ expect(pushSpy).toHaveBeenCalledWith(urls.webAnalytics(), {+ utm_source: 'web_analytics_recap',+ utm_medium: 'recap_button',+ utm_campaign: 'weekly_recap',+ utm_content: 'view_dashboard',+ })+ })+})diff --git a/frontend/src/scenes/web-analytics/recap/webAnalyticsRecapLogic.ts b/frontend/src/scenes/web-analytics/recap/webAnalyticsRecapLogic.tsnew file mode 100644index 000000000000..06ee85ae6d04--- /dev/null+++ b/frontend/src/scenes/web-analytics/recap/webAnalyticsRecapLogic.ts@@ -0,0 +1,204 @@+import { actions, afterMount, connect, kea, listeners, path } from 'kea'+import { loaders } from 'kea-loaders'+import { router } from 'kea-router'+import posthog from 'posthog-js'++import { copyToClipboard } from 'lib/utils/copyToClipboard'+import { projectLogic } from 'scenes/projectLogic'+import { urls } from 'scenes/urls'++import { webAnalyticsRecap } from 'products/web_analytics/frontend/generated/api'+import type { WebAnalyticsRecapResponseApi } from 'products/web_analytics/frontend/generated/api.schemas'++import { formatRecapDateRange } from './recapDates'+import type { webAnalyticsRecapLogicType } from './webAnalyticsRecapLogicType'++export type RecapShareMethod = 'copy_link' | 'copy_slack' | 'copy_email'+export type RecapCta = 'view_dashboard' | 'ask_posthog_ai' | 'go_to_web_analytics'+export type RecapButton = RecapShareMethod | RecapCta+type RecapButtonIntent = 'share' | 'web_analytics_view' | 'posthog_ai_usage'+type RecapButtonDestination = 'clipboard' | 'web_analytics_dashboard' | 'posthog_ai_side_panel'+type RecapEventProperties = Record<string, string | number | boolean | null>++// Matches the existing weekly digest cadence — the recap is the weekly moment, not a custom range.+const RECAP_DAYS = 7++const WEB_ANALYTICS_RECAP_DASHBOARD_PARAMS = {+ utm_source: 'web_analytics_recap',+ utm_medium: 'recap_button',+ utm_campaign: 'weekly_recap',+}++function buildSlackCopy(recap: WebAnalyticsRecapResponseApi): string {+ return [+ `*${recap.project_name} website recap*`,+ formatRecapDateRange(recap),+ '',+ `• ${recap.visitors.current.toLocaleString()} visitors`,+ `• ${recap.pageviews.current.toLocaleString()} pageviews`,+ `• ${recap.sessions.current.toLocaleString()} sessions`,+ `• ${Math.round(recap.bounce_rate.current)}% bounce rate`,+ '',+ `Persona: ${recap.persona.emoji} ${recap.persona.name}`,+ recap.recap_url,+ ].join('\n')+}++function buildEmailCopy(recap: WebAnalyticsRecapResponseApi): string {+ return [+ `Subject: ${recap.project_name} website recap: ${formatRecapDateRange(recap)}`,+ '',+ `Here's the website recap for ${recap.project_name} (${formatRecapDateRange(recap)}):`,+ '',+ `${recap.visitors.current.toLocaleString()} visitors`,+ `${recap.pageviews.current.toLocaleString()} pageviews`,+ `${recap.sessions.current.toLocaleString()} sessions`,+ `${Math.round(recap.bounce_rate.current)}% bounce rate`,+ '',+ `This week's persona: ${recap.persona.emoji} ${recap.persona.name}`,+ recap.persona.blurb,+ '',+ `View the full recap: ${recap.recap_url}`,+ ].join('\n')+}++export const webAnalyticsRecapLogic = kea<webAnalyticsRecapLogicType>([+ path(['scenes', 'web-analytics', 'recap', 'webAnalyticsRecapLogic']),+ connect(() => ({+ values: [projectLogic, ['currentProjectId']],+ })),+ actions({+ recordOpened: true,+ recordReachedEnd: true,+ recordButtonClicked: (button: RecapButton) => ({ button }),+ recordShared: (method: RecapShareMethod) => ({ method }),+ recordCtaClicked: (cta: RecapCta) => ({ cta }),+ copyRecapLink: true,+ copyRecapForSlack: true,+ copyRecapForEmail: true,+ goToWebAnalytics: (cta: Extract<RecapCta, 'view_dashboard' | 'go_to_web_analytics'>) => ({ cta }),+ }),+ loaders(({ values }) => ({+ recap: [+ null as WebAnalyticsRecapResponseApi | null,+ {+ loadRecap: async () => {+ const projectId = values.currentProjectId+ if (projectId == null) {+ return null+ }+ return await webAnalyticsRecap(String(projectId), { days: RECAP_DAYS })+ },+ },+ ],+ })),+ listeners(({ values, actions }) => {+ const recapProperties = (): RecapEventProperties => {+ const recap = values.recap+ return {+ project_id: values.currentProjectId ?? null,+ period_label: recap?.period_label ?? null,+ period_start: recap?.period_start ?? null,+ period_end: recap?.period_end ?? null,+ persona: recap?.persona.id ?? null,+ visitors: recap?.visitors.current ?? null,+ pageviews: recap?.pageviews.current ?? null,+ sessions: recap?.sessions.current ?? null,+ top_pages_count: recap?.top_pages.length ?? null,+ top_sources_count: recap?.top_sources.length ?? null,+ goals_count: recap?.goals.length ?? null,+ highlights_count: recap?.highlights.length ?? null,+ }+ }++ const buttonContext = (+ button: RecapButton+ ): { intent: RecapButtonIntent; destination: RecapButtonDestination } => {+ if (button === 'copy_link' || button === 'copy_slack' || button === 'copy_email') {+ return { intent: 'share', destination: 'clipboard' }+ }+ if (button === 'ask_posthog_ai') {+ return { intent: 'posthog_ai_usage', destination: 'posthog_ai_side_panel' }+ }+ return { intent: 'web_analytics_view', destination: 'web_analytics_dashboard' }+ }++ return {+ recordOpened: () => {+ const { utm_source, utm_medium } = router.values.searchParams+ posthog.capture('web_analytics_recap_opened', {+ utm_source: utm_source ?? null,+ utm_medium: utm_medium ?? null,+ ...recapProperties(),+ })+ },+ loadRecapSuccess: () => {+ if (values.recap?.persona) {+ posthog.capture('web_analytics_recap_persona_assigned', {+ ...recapProperties(),+ persona: values.recap.persona.id,+ })+ }+ },+ recordReachedEnd: () => {+ posthog.capture('web_analytics_recap_completed', recapProperties())+ },+ recordButtonClicked: ({ button }) => {+ posthog.capture('web_analytics_recap_button_clicked', {+ ...recapProperties(),+ button,+ ...buttonContext(button),+ })+ },+ recordShared: ({ method }) => {+ posthog.capture('web_analytics_recap_shared', {+ ...recapProperties(),+ method,+ })+ },+ recordCtaClicked: ({ cta }) => {+ actions.recordButtonClicked(cta)+ posthog.capture('web_analytics_recap_cta_clicked', {+ ...recapProperties(),+ cta,+ })+ },+ copyRecapLink: async () => {+ actions.recordButtonClicked('copy_link')+ const url = values.recap?.recap_url ?? window.location.href+ if (await copyToClipboard(url, 'recap link')) {+ actions.recordShared('copy_link')+ }+ },+ copyRecapForSlack: async () => {+ if (!values.recap) {+ return+ }+ actions.recordButtonClicked('copy_slack')+ if (await copyToClipboard(buildSlackCopy(values.recap), 'Slack recap')) {+ actions.recordShared('copy_slack')+ }+ },+ copyRecapForEmail: async () => {+ if (!values.recap) {+ return+ }+ actions.recordButtonClicked('copy_email')+ if (await copyToClipboard(buildEmailCopy(values.recap), 'email recap')) {+ actions.recordShared('copy_email')+ }+ },+ goToWebAnalytics: ({ cta }) => {+ actions.recordCtaClicked(cta)+ router.actions.push(urls.webAnalytics(), {+ ...WEB_ANALYTICS_RECAP_DASHBOARD_PARAMS,+ utm_content: cta,+ })+ },+ }+ }),+ afterMount(({ actions }) => {+ actions.loadRecap()+ actions.recordOpened()+ }),+])diff --git a/products/web_analytics/backend/api/api.py b/products/web_analytics/backend/api/api.pyindex 4cb8d023fea2..e4d0bfe8cb85 100644--- a/products/web_analytics/backend/api/api.py+++ b/products/web_analytics/backend/api/api.py@@ -7,7 +7,11 @@ from rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixin-from products.web_analytics.backend.serializers import WeeklyDigestResponseSerializer+from products.web_analytics.backend.recap import build_team_recap+from products.web_analytics.backend.serializers import (+ WebAnalyticsRecapResponseSerializer,+ WeeklyDigestResponseSerializer,+)from products.web_analytics.backend.weekly_digest import build_team_digestMIN_DAYS = 1@@ -22,7 +26,7 @@ class _DigestQuerySerializer(serializers.Serializer):class WebAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):scope_object = "web_analytics"- scope_object_read_actions = ["weekly_digest"]+ scope_object_read_actions = ["weekly_digest", "recap"]serializer_class = WeeklyDigestResponseSerializer@extend_schema(@@ -67,3 +71,45 @@ class WebAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):digest = build_team_digest(self.team, days=params["days"], compare=params["compare"])serializer = self.get_serializer(instance=digest)return Response(serializer.data)++ @extend_schema(+ operation_id="web_analytics_recap",+ summary="Weekly web analytics recap",+ description=(+ "The 'Wrapped'-style weekly recap: everything in the weekly digest (visitors, pageviews, "+ "sessions, bounce rate, average session duration with period-over-period comparisons, top "+ "pages, top sources, and goals) plus a single derived weekly persona and a short list of "+ "screenshot-worthy highlights for the period."+ ),+ parameters=[+ OpenApiParameter(+ name="days",+ type=OpenApiTypes.INT,+ location=OpenApiParameter.QUERY,+ required=False,+ default=DEFAULT_DAYS,+ description=f"Lookback window in days ({MIN_DAYS}–{MAX_DAYS}). Defaults to {DEFAULT_DAYS}.",+ ),+ OpenApiParameter(+ name="compare",+ type=OpenApiTypes.BOOL,+ location=OpenApiParameter.QUERY,+ required=False,+ default=True,+ description=(+ "When true (default), include period-over-period change for each metric comparing "+ "against the prior equal-length period. Set to false to skip the comparison query."+ ),+ ),+ ],+ responses={200: OpenApiResponse(response=WebAnalyticsRecapResponseSerializer)},+ tags=["web_analytics"],+ )+ @action(detail=False, methods=["get"], url_path="recap")+ def recap(self, request: "Request", **kwargs: object) -> Response:+ query_serializer = _DigestQuerySerializer(data=request.query_params)+ query_serializer.is_valid(raise_exception=True)+ params = query_serializer.validated_data+ recap = build_team_recap(self.team, days=params["days"], compare=params["compare"])+ serializer = WebAnalyticsRecapResponseSerializer(instance=recap, context=self.get_serializer_context())+ return Response(serializer.data)diff --git a/products/web_analytics/backend/recap.py b/products/web_analytics/backend/recap.pynew file mode 100644index 000000000000..f0c8cf5ac3f4--- /dev/null+++ b/products/web_analytics/backend/recap.py@@ -0,0 +1,245 @@+from datetime import date, timedelta+from urllib.parse import urlencode+from zoneinfo import ZoneInfo++from django.conf import settings+from django.utils import timezone++from posthog.models import Team++from products.web_analytics.backend.weekly_digest import build_team_digest++# Below this many weekly visitors we don't try to assign a "real" persona — we+# celebrate the start of the journey instead of surfacing a thin, discouraging stat.+LOW_TRAFFIC_THRESHOLD = 25++# Round numbers we treat as celebratable visitor milestones when crossed week over week.+VISITOR_MILESTONES = [100, 250, 500, 1000, 2500, 5000, 10000, 25000, 50000, 100000, 250000, 500000, 1000000]++_SEARCH_DOMAINS = ("google", "bing", "duckduckgo", "yahoo", "baidu", "yandex", "ecosia", "brave")+_SOCIAL_DOMAINS = (+ "twitter",+ "x.com",+ "t.co",+ "facebook",+ "linkedin",+ "reddit",+ "youtube",+ "instagram",+ "news.ycombinator",+ "producthunt",+ "tiktok",+ "mastodon",+ "bsky",+)++PERSONAS: dict[str, dict[str, str]] = {+ "just_getting_started": {+ "name": "The Newcomer",+ "emoji": "🐣",+ "blurb": "Every big site starts with a first visitor. The journey is underway.",+ "color": "#8f55e0",+ },+ "conversion_machine": {+ "name": "Conversion Machine",+ "emoji": "🎯",+ "blurb": "Conversions jumped {value} this week. Your funnel is firing.",+ "color": "#2f7d4f",+ },+ "traffic_magnet": {+ "name": "Traffic Magnet",+ "emoji": "🧲",+ "blurb": "Visitors surged {value} this week. Whatever you're doing, keep doing it.",+ "color": "#e0a23b",+ },+ "crowd_favorite": {+ "name": "Crowd Favorite",+ "emoji": "⭐",+ "blurb": "One page stole the show, pulling {value} of all your visitors.",+ "color": "#db5a9a",+ },+ "search_hog": {+ "name": "Search Sensation",+ "emoji": "🔍",+ "blurb": "Search engines sent the crowd this week, and {value} led the way.",+ "color": "#3b8fe0",+ },+ "word_of_mouth": {+ "name": "The Influencer",+ "emoji": "📣",+ "blurb": "People are spreading the word, and {value} drove your biggest referral.",+ "color": "#e0653b",+ },+ "loyal_following": {+ "name": "Cult Classic",+ "emoji": "💚",+ "blurb": "Your visitors stuck around. Engagement is up and bounce is down.",+ "color": "#2f9d7d",+ },+ "rising_star": {+ "name": "Rising Star",+ "emoji": "🚀",+ "blurb": "Across the board, this week beat last week. You're on the way up.",+ "color": "#6a5af0",+ },+ "steady_hog": {+ "name": "Old Faithful",+ "emoji": "🦔",+ "blurb": "A calm, consistent week. Steady traffic is its own kind of win.",+ "color": "#7a8089",+ },+}+++def _signed_percent(metric: dict | None) -> int:+ """Return the week-over-week change as a signed integer percent (Up positive, Down negative)."""+ change = metric.get("change") if metric else None+ if not change:+ return 0+ percent = change.get("percent", 0)+ return percent if change.get("direction") == "Up" else -percent+++def _domain_matches(name: str, needles: tuple[str, ...]) -> bool:+ lowered = name.lower()+ return any(needle in lowered for needle in needles)+++def compute_persona(digest: dict) -> dict:+ """Assign a single weekly persona from the digest data.++ Deterministic, priority-ordered, and pure so it can be unit-tested without ClickHouse.+ The first matching rule wins; the fallback is always a valid, warm identity.+ """+ visitors = digest.get("visitors") or {}+ visitors_current = visitors.get("current") or 0+ visitors_change = _signed_percent(visitors)+ pageviews_change = _signed_percent(digest.get("pageviews"))+ sessions_change = _signed_percent(digest.get("sessions"))+ bounce_change = _signed_percent(digest.get("bounce_rate"))+ duration_change = _signed_percent(digest.get("avg_session_duration"))++ top_pages = digest.get("top_pages") or []+ top_sources = digest.get("top_sources") or []+ goals = digest.get("goals") or []++ def persona(persona_id: str, value: str = "") -> dict:+ base = PERSONAS[persona_id]+ return {**base, "id": persona_id, "blurb": base["blurb"].replace("{value}", value)}++ if visitors_current < LOW_TRAFFIC_THRESHOLD:+ return persona("just_getting_started")++ top_goal_change = _signed_percent(goals[0]) if goals else 0+ if goals and top_goal_change >= 20:+ return persona("conversion_machine", f"+{top_goal_change}%")++ if visitors_change >= 30:+ return persona("traffic_magnet", f"+{visitors_change}%")++ if top_pages and visitors_current:+ top_page_share = min(round((top_pages[0].get("visitors") or 0) / visitors_current * 100), 100)+ if top_page_share >= 50:+ return persona("crowd_favorite", f"{top_page_share}%")++ if top_sources:+ top_source_name = top_sources[0].get("name") or ""+ top_source_display = top_source_name or "Direct"+ top_source_share = (+ min(round((top_sources[0].get("visitors") or 0) / visitors_current * 100), 100) if visitors_current else 0+ )+ if _domain_matches(top_source_name, _SEARCH_DOMAINS):+ return persona("search_hog", top_source_display)+ if _domain_matches(top_source_name, _SOCIAL_DOMAINS) or top_source_share >= 30:+ return persona("word_of_mouth", top_source_display)++ if bounce_change < 0 or duration_change > 0:+ return persona("loyal_following")++ if visitors_change > 0 and (pageviews_change > 0 or sessions_change > 0):+ return persona("rising_star")++ return persona("steady_hog")+++def _build_highlights(digest: dict, compare: bool = True) -> list[dict]:+ """Pull a few screenshot-worthy superlatives from the digest data."""+ highlights: list[dict] = []++ visitors = digest.get("visitors") or {}+ current = visitors.get("current") or 0+ previous = visitors.get("previous")+ if previous is None and compare:+ previous = 0+ if previous is not None:+ crossed = [threshold for threshold in VISITOR_MILESTONES if previous < threshold <= current]+ if crossed:+ highlights.append(+ {+ "id": "milestone",+ "emoji": "🎉",+ "title": "Milestone unlocked",+ "value": f"{max(crossed):,} visitors",+ "detail": "You crossed a new visitor milestone this week.",+ }+ )++ top_pages = digest.get("top_pages") or []+ risers = [page for page in top_pages if _signed_percent(page) > 0]+ if risers:+ rising = max(risers, key=_signed_percent)+ highlights.append(+ {+ "id": "rising_page",+ "emoji": "📈",+ "title": "Rising star page",+ "value": rising.get("path") or "/",+ "detail": f"Up {_signed_percent(rising)}% in visitors week over week.",+ }+ )++ top_sources = digest.get("top_sources") or []+ if top_sources:+ top_source = top_sources[0]+ highlights.append(+ {+ "id": "top_source",+ "emoji": "🌐",+ "title": "Top source",+ "value": top_source.get("name") or "Direct",+ "detail": f"{top_source.get('visitors') or 0:,} visitors came from here.",+ }+ )++ return highlights[:3]+++def _build_period_dates(team: Team, days: int) -> dict[str, date]:+ period_end = timezone.now().astimezone(ZoneInfo(team.timezone)).date()+ period_start = period_end - timedelta(days=days)+ return {+ "period_start": period_start,+ "period_end": period_end,+ }+++def recap_url_for_team(team: Team, *, utm_source: str, utm_medium: str | None = None) -> str:+ """The single canonical link to a team's weekly recap, with attribution params."""+ params: dict[str, str] = {"utm_source": utm_source}+ if utm_medium:+ params["utm_medium"] = utm_medium+ return f"{settings.SITE_URL}/project/{team.pk}/web/recap?{urlencode(params)}"+++def build_team_recap(team: Team, days: int = 7, compare: bool = True) -> dict:+ """Build the full weekly recap payload: the digest data plus the derived persona and highlights."""+ digest = build_team_digest(team, days=days, compare=compare)+ return {+ **digest,+ "persona": compute_persona(digest),+ "highlights": _build_highlights(digest, compare=compare),+ "period_label": f"Last {days} days",+ **_build_period_dates(team, days),+ "project_name": team.name,+ "recap_url": recap_url_for_team(team, utm_source="web_analytics_recap"),+ }diff --git a/products/web_analytics/backend/serializers.py b/products/web_analytics/backend/serializers.pyindex d44604a47938..77cb30bf8798 100644--- a/products/web_analytics/backend/serializers.py+++ b/products/web_analytics/backend/serializers.py@@ -58,3 +58,36 @@ class WeeklyDigestResponseSerializer(serializers.Serializer):top_sources = TopSourceSerializer(many=True, help_text="Top 5 traffic sources by unique visitors.")goals = GoalSerializer(many=True, help_text="Goal conversions.")dashboard_url = serializers.URLField(help_text="Link to the Web analytics dashboard for this project.")+++class RecapPersonaSerializer(serializers.Serializer):+ id = serializers.CharField(+ help_text=(+ "Stable persona identifier. One of: just_getting_started, conversion_machine, traffic_magnet, "+ "crowd_favorite, search_hog, word_of_mouth, loyal_following, rising_star, steady_hog."+ )+ )+ name = serializers.CharField(help_text="Display name for the persona, e.g. 'Traffic Magnet'.")+ emoji = serializers.CharField(help_text="Emoji representing the persona.")+ blurb = serializers.CharField(help_text="One-line explanation of why this persona was assigned this week.")+ color = serializers.CharField(help_text="Hex accent color for rendering the persona card.")+++class RecapHighlightSerializer(serializers.Serializer):+ id = serializers.CharField(help_text="Stable highlight identifier, e.g. 'milestone', 'rising_page', 'top_source'.")+ emoji = serializers.CharField(help_text="Emoji for the highlight.")+ title = serializers.CharField(help_text="Short headline for the highlight, e.g. 'Rising star page'.")+ value = serializers.CharField(help_text="The standout value, e.g. a page path or visitor count.")+ detail = serializers.CharField(allow_blank=True, help_text="Supporting sentence for the highlight.")+++class WebAnalyticsRecapResponseSerializer(WeeklyDigestResponseSerializer):+ persona = RecapPersonaSerializer(help_text="The single weekly persona assigned from this week's data.")+ highlights = RecapHighlightSerializer(+ many=True, help_text="Up to three screenshot-worthy superlatives for the week."+ )+ period_label = serializers.CharField(help_text="Human-readable period label, e.g. 'Last 7 days'.")+ period_start = serializers.DateField(help_text="First date included in the recap period, in the project timezone.")+ period_end = serializers.DateField(help_text="Final date included in the recap period, in the project timezone.")+ project_name = serializers.CharField(help_text="Name of the project this recap is for.")+ recap_url = serializers.URLField(help_text="Canonical link to this project's weekly recap.")diff --git a/products/web_analytics/backend/test/test_api.py b/products/web_analytics/backend/test/test_api.pyindex f76316d0a8c4..a1409a675604 100644--- a/products/web_analytics/backend/test/test_api.py+++ b/products/web_analytics/backend/test/test_api.py@@ -275,3 +275,78 @@ class TestWebAnalyticsDigestAPI(ClickhouseTestMixin, APIBaseTest):dashboard_url = response.json()["dashboard_url"]assert f"/project/{self.team.id}/web" in dashboard_urlassert "utm_source=" in dashboard_url+++class TestWebAnalyticsRecapAPI(ClickhouseTestMixin, APIBaseTest):+ ENDPOINT = "/api/environments/{team_id}/web_analytics/recap/"++ def _url(self, team_id=None):+ return self.ENDPOINT.format(team_id=team_id or self.team.id)++ def test_recap_extends_digest_with_persona_and_highlights(self):+ with freeze_time(QUERY_TIMESTAMP):+ _create_person(team_id=self.team.pk, distinct_ids=["user_1"])+ _create_pageview(self.team, distinct_id="user_1", url="https://example.com/", timestamp="2025-01-25")+ flush_persons_and_events()++ response = self.client.get(self._url())++ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ # superset of the digest shape+ assert {"visitors", "pageviews", "sessions", "bounce_rate", "avg_session_duration", "goals"} <= set(data.keys())+ # plus the recap-only fields+ assert {+ "persona",+ "highlights",+ "period_label",+ "period_start",+ "period_end",+ "project_name",+ "recap_url",+ } <= set(data.keys())+ assert set(data["persona"].keys()) == {"id", "name", "emoji", "blurb", "color"}+ assert isinstance(data["highlights"], list)+ assert data["period_start"] == "2025-01-22"+ assert data["period_end"] == "2025-01-29"+ assert data["project_name"] == self.team.name++ def test_empty_team_gets_just_getting_started_persona(self):+ with freeze_time(QUERY_TIMESTAMP):+ response = self.client.get(self._url())++ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ assert data["persona"]["id"] == "just_getting_started"+ assert data["highlights"] == []++ def test_recap_url_points_at_recap_route(self):+ response = self.client.get(self._url())++ assert response.status_code == status.HTTP_200_OK+ recap_url = response.json()["recap_url"]+ assert f"/project/{self.team.id}/web/recap" in recap_url+ assert "utm_source=web_analytics_recap" in recap_url++ def test_cannot_read_other_teams_recap(self):+ other_org = Organization.objects.create(name="Other Org")+ other_team = Team.objects.create(organization=other_org, name="Other Team")++ response = self.client.get(self._url(team_id=other_team.id))++ assert response.status_code in (status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND)++ @parameterized.expand(+ [+ (["feature_flag:read"], status.HTTP_403_FORBIDDEN),+ (["web_analytics:read"], status.HTTP_200_OK),+ ]+ )+ def test_personal_api_key_requires_web_analytics_read_scope(self, scopes, expected_status):+ api_key = self.create_personal_api_key_with_scopes(scopes)+ self.client.logout()++ with freeze_time(QUERY_TIMESTAMP):+ response = self.client.get(self._url(), HTTP_AUTHORIZATION=f"Bearer {api_key}")++ assert response.status_code == expected_statusdiff --git a/products/web_analytics/backend/test/test_recap.py b/products/web_analytics/backend/test/test_recap.pynew file mode 100644index 000000000000..2a3ba9d7c669--- /dev/null+++ b/products/web_analytics/backend/test/test_recap.py@@ -0,0 +1,189 @@+from django.test import SimpleTestCase++from parameterized import parameterized++from products.web_analytics.backend.recap import _build_highlights, compute_persona+++def _metric(current, percent=0, direction="Up", previous=None):+ change = {"percent": percent, "direction": direction} if percent else None+ return {"current": current, "previous": previous, "change": change}+++def _digest(**overrides):+ base = {+ "visitors": _metric(100),+ "pageviews": _metric(100),+ "sessions": _metric(100),+ "bounce_rate": _metric(40.0),+ "avg_session_duration": {"current": "1m", "previous": None, "change": None},+ "top_pages": [],+ "top_sources": [],+ "goals": [],+ }+ base.update(overrides)+ return base+++class TestComputePersona(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "low_traffic_is_just_getting_started",+ _digest(visitors=_metric(10, percent=80, direction="Up")),+ "just_getting_started",+ ),+ (+ "boundary_25_is_not_low_traffic",+ _digest(visitors=_metric(25)),+ "steady_hog",+ ),+ (+ "goals_up_is_conversion_machine",+ _digest(+ visitors=_metric(100, percent=5, direction="Up"),+ goals=[{"name": "Signup", "conversions": 50, "change": {"percent": 40, "direction": "Up"}}],+ ),+ "conversion_machine",+ ),+ (+ "visitors_up_30_is_traffic_magnet",+ _digest(visitors=_metric(100, percent=40, direction="Up")),+ "traffic_magnet",+ ),+ (+ "dominant_page_is_crowd_favorite",+ _digest(+ visitors=_metric(100, percent=5, direction="Up"),+ top_pages=[{"path": "/", "visitors": 60, "change": None}],+ ),+ "crowd_favorite",+ ),+ (+ "search_engine_source_is_search_hog",+ _digest(+ visitors=_metric(100, percent=5, direction="Up"),+ top_pages=[{"path": "/", "visitors": 10, "change": None}],+ top_sources=[{"name": "google.com", "visitors": 40, "change": None}],+ ),+ "search_hog",+ ),+ (+ "social_source_is_word_of_mouth",+ _digest(+ visitors=_metric(100, percent=5, direction="Up"),+ top_pages=[{"path": "/", "visitors": 10, "change": None}],+ top_sources=[{"name": "twitter.com", "visitors": 10, "change": None}],+ ),+ "word_of_mouth",+ ),+ (+ "high_share_referral_is_word_of_mouth",+ _digest(+ visitors=_metric(100, percent=5, direction="Up"),+ top_pages=[{"path": "/", "visitors": 10, "change": None}],+ top_sources=[{"name": "someblog.com", "visitors": 40, "change": None}],+ ),+ "word_of_mouth",+ ),+ (+ "bounce_down_is_loyal_following",+ _digest(+ visitors=_metric(100, percent=5, direction="Up"),+ bounce_rate=_metric(30.0, percent=10, direction="Down"),+ ),+ "loyal_following",+ ),+ (+ "broad_growth_is_rising_star",+ _digest(+ visitors=_metric(100, percent=5, direction="Up"),+ pageviews=_metric(100, percent=10, direction="Up"),+ bounce_rate=_metric(45.0, percent=5, direction="Up"),+ avg_session_duration={+ "current": "1m",+ "previous": "1m",+ "change": {"percent": 5, "direction": "Down"},+ },+ ),+ "rising_star",+ ),+ (+ "flat_week_is_steady_hog",+ _digest(visitors=_metric(100)),+ "steady_hog",+ ),+ ]+ )+ def test_persona_assignment(self, _name, digest, expected_id):+ persona = compute_persona(digest)+ assert persona["id"] == expected_id+ assert persona["name"]+ assert persona["emoji"]+ assert persona["blurb"]+ assert "{value}" not in persona["blurb"]+ assert persona["color"].startswith("#")++ def test_dominant_page_share_is_clamped_to_100(self):+ digest = _digest(+ visitors=_metric(100, percent=5, direction="Up"),+ top_pages=[{"path": "/", "visitors": 150, "change": None}],+ )+ persona = compute_persona(digest)+ assert persona["id"] == "crowd_favorite"+ assert "100%" in persona["blurb"]+ assert "150%" not in persona["blurb"]++ def test_direct_traffic_top_source_falls_back_to_direct_label(self):+ digest = _digest(+ visitors=_metric(100, percent=5, direction="Up"),+ top_pages=[{"path": "/", "visitors": 10, "change": None}],+ top_sources=[{"name": "", "visitors": 40, "change": None}],+ )+ persona = compute_persona(digest)+ assert persona["id"] == "word_of_mouth"+ assert "Direct" in persona["blurb"]+ assert " " not in persona["blurb"]+++class TestBuildHighlights(SimpleTestCase):+ def test_empty_digest_has_no_highlights(self):+ assert _build_highlights(_digest(visitors=_metric(0))) == []++ def test_milestone_when_crossing_round_number(self):+ digest = _digest(visitors={"current": 120, "previous": 90, "change": {"percent": 33, "direction": "Up"}})+ highlights = _build_highlights(digest)+ milestone = next(h for h in highlights if h["id"] == "milestone")+ assert "100" in milestone["value"]++ def test_milestone_when_crossing_from_zero_baseline(self):+ digest = _digest(visitors=_metric(120))+ highlights = _build_highlights(digest, compare=True)+ milestone = next(h for h in highlights if h["id"] == "milestone")+ assert "100" in milestone["value"]++ def test_no_milestone_when_compare_disabled(self):+ digest = _digest(visitors=_metric(120))+ assert not any(h["id"] == "milestone" for h in _build_highlights(digest, compare=False))++ def test_rising_page_and_top_source(self):+ digest = _digest(+ top_pages=[+ {"path": "/pricing", "visitors": 50, "change": {"percent": 80, "direction": "Up"}},+ {"path": "/", "visitors": 40, "change": {"percent": 5, "direction": "Up"}},+ ],+ top_sources=[{"name": "google.com", "visitors": 30, "change": None}],+ )+ highlights = _build_highlights(digest)+ rising = next(h for h in highlights if h["id"] == "rising_page")+ assert rising["value"] == "/pricing"+ top_source = next(h for h in highlights if h["id"] == "top_source")+ assert top_source["value"] == "google.com"++ def test_capped_at_three(self):+ digest = _digest(+ visitors={"current": 120, "previous": 90, "change": {"percent": 33, "direction": "Up"}},+ top_pages=[{"path": "/a", "visitors": 50, "change": {"percent": 80, "direction": "Up"}}],+ top_sources=[{"name": "google.com", "visitors": 30, "change": None}],+ )+ assert len(_build_highlights(digest)) <= 3diff --git a/products/web_analytics/frontend/generated/api.schemas.ts b/products/web_analytics/frontend/generated/api.schemas.tsindex c775f93ca8c0..c26cbbe8a871 100644--- a/products/web_analytics/frontend/generated/api.schemas.ts+++ b/products/web_analytics/frontend/generated/api.schemas.ts@@ -355,6 +355,67 @@ export interface GoalApi {change: WoWChangeApi | null}+export interface RecapPersonaApi {+ /** Stable persona identifier. One of: just_getting_started, conversion_machine, traffic_magnet, crowd_favorite, search_hog, word_of_mouth, loyal_following, rising_star, steady_hog. */+ id: string+ /** Display name for the persona, e.g. 'Traffic Magnet'. */+ name: string+ /** Emoji representing the persona. */+ emoji: string+ /** One-line explanation of why this persona was assigned this week. */+ blurb: string+ /** Hex accent color for rendering the persona card. */+ color: string+}++export interface RecapHighlightApi {+ /** Stable highlight identifier, e.g. 'milestone', 'rising_page', 'top_source'. */+ id: string+ /** Emoji for the highlight. */+ emoji: string+ /** Short headline for the highlight, e.g. 'Rising star page'. */+ title: string+ /** The standout value, e.g. a page path or visitor count. */+ value: string+ /** Supporting sentence for the highlight. */+ detail: string+}++export interface WebAnalyticsRecapResponseApi {+ /** Unique visitors. */+ visitors: NumericMetricApi+ /** Total pageviews. */+ pageviews: NumericMetricApi+ /** Total sessions. */+ sessions: NumericMetricApi+ /** Bounce rate (0–100). */+ bounce_rate: NumericMetricApi+ /** Average session duration. */+ avg_session_duration: DurationMetricApi+ /** Top 5 pages by unique visitors. */+ top_pages: TopPageApi[]+ /** Top 5 traffic sources by unique visitors. */+ top_sources: TopSourceApi[]+ /** Goal conversions. */+ goals: GoalApi[]+ /** Link to the Web analytics dashboard for this project. */+ dashboard_url: string+ /** The single weekly persona assigned from this week's data. */+ persona: RecapPersonaApi+ /** Up to three screenshot-worthy superlatives for the week. */+ highlights: RecapHighlightApi[]+ /** Human-readable period label, e.g. 'Last 7 days'. */+ period_label: string+ /** First date included in the recap period, in the project timezone. */+ period_start: string+ /** Final date included in the recap period, in the project timezone. */+ period_end: string+ /** Name of the project this recap is for. */+ project_name: string+ /** Canonical link to this project's weekly recap. */+ recap_url: string+}+export interface WeeklyDigestResponseApi {/** Unique visitors. */visitors: NumericMetricApi@@ -741,6 +802,17 @@ export type SavedListParams = {type?: string}+export type WebAnalyticsRecapParams = {+ /**+ * When true (default), include period-over-period change for each metric comparing against the prior equal-length period. Set to false to skip the comparison query.+ */+ compare?: boolean+ /**+ * Lookback window in days (1–90). Defaults to 7.+ */+ days?: number+}+export type WebAnalyticsWeeklyDigestParams = {/*** When true (default), include period-over-period change for each metric comparing against the prior equal-length period. Set to false to skip the comparison query (faster).diff --git a/products/web_analytics/frontend/generated/api.ts b/products/web_analytics/frontend/generated/api.tsindex c855fce7a57a..cc011d755b4f 100644--- a/products/web_analytics/frontend/generated/api.ts+++ b/products/web_analytics/frontend/generated/api.ts@@ -29,6 +29,8 @@ import type {SavedListParams,WebAnalyticsFilterPresetApi,WebAnalyticsFilterPresetsListParams,+ WebAnalyticsRecapParams,+ WebAnalyticsRecapResponseApi,WebAnalyticsWeeklyDigestParams,WeeklyDigestResponseApi,} from './api.schemas'@@ -269,6 +271,37 @@ export const savedRegenerateCreate = async (})}+export const getWebAnalyticsRecapUrl = (projectId: string, params?: WebAnalyticsRecapParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/web_analytics/recap/?${stringifiedParams}`+ : `/api/projects/${projectId}/web_analytics/recap/`+}++/**+ * The 'Wrapped'-style weekly recap: everything in the weekly digest (visitors, pageviews, sessions, bounce rate, average session duration with period-over-period comparisons, top pages, top sources, and goals) plus a single derived weekly persona and a short list of screenshot-worthy highlights for the period.+ * @summary Weekly web analytics recap+ */+export const webAnalyticsRecap = async (+ projectId: string,+ params?: WebAnalyticsRecapParams,+ options?: RequestInit+): Promise<WebAnalyticsRecapResponseApi> => {+ return apiMutator<WebAnalyticsRecapResponseApi>(getWebAnalyticsRecapUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getWebAnalyticsWeeklyDigestUrl = (projectId: string, params?: WebAnalyticsWeeklyDigestParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/web_analytics/mcp/tools.yaml b/products/web_analytics/mcp/tools.yamlindex a3000e56bb48..10408bfb66e1 100644--- a/products/web_analytics/mcp/tools.yaml+++ b/products/web_analytics/mcp/tools.yaml@@ -171,6 +171,9 @@ tools:web-analytics-filter-presets-update:operation: web_analytics_filter_presets_updateenabled: false+ web-analytics-recap:+ operation: web_analytics_recap+ enabled: falseweb-analytics-weekly-digest:operation: web_analytics_weekly_digestenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 6a5d383622ff..e807e0885afb 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -46861,6 +46861,32 @@ export namespace Schemas {trigger?: TriggerEnum;}+ export interface RecapHighlight {+ /** Stable highlight identifier, e.g. 'milestone', 'rising_page', 'top_source'. */+ id: string;+ /** Emoji for the highlight. */+ emoji: string;+ /** Short headline for the highlight, e.g. 'Rising star page'. */+ title: string;+ /** The standout value, e.g. a page path or visitor count. */+ value: string;+ /** Supporting sentence for the highlight. */+ detail: string;+ }++ export interface RecapPersona {+ /** Stable persona identifier. One of: just_getting_started, conversion_machine, traffic_magnet, crowd_favorite, search_hog, word_of_mouth, loyal_following, rising_star, steady_hog. */+ id: string;+ /** Display name for the persona, e.g. 'Traffic Magnet'. */+ name: string;+ /** Emoji representing the persona. */+ emoji: string;+ /** One-line explanation of why this persona was assigned this week. */+ blurb: string;+ /** Hex accent color for rendering the persona card. */+ color: string;+ }+export interface RecomputeResult {run: Run;counts_changed: boolean;@@ -52967,6 +52993,41 @@ export namespace Schemas {run_id: string;}+ export interface WebAnalyticsRecapResponse {+ /** Unique visitors. */+ visitors: NumericMetric;+ /** Total pageviews. */+ pageviews: NumericMetric;+ /** Total sessions. */+ sessions: NumericMetric;+ /** Bounce rate (0–100). */+ bounce_rate: NumericMetric;+ /** Average session duration. */+ avg_session_duration: DurationMetric;+ /** Top 5 pages by unique visitors. */+ top_pages: TopPage[];+ /** Top 5 traffic sources by unique visitors. */+ top_sources: TopSource[];+ /** Goal conversions. */+ goals: Goal[];+ /** Link to the Web analytics dashboard for this project. */+ dashboard_url: string;+ /** The single weekly persona assigned from this week's data. */+ persona: RecapPersona;+ /** Up to three screenshot-worthy superlatives for the week. */+ highlights: RecapHighlight[];+ /** Human-readable period label, e.g. 'Last 7 days'. */+ period_label: string;+ /** First date included in the recap period, in the project timezone. */+ period_start: string;+ /** Final date included in the recap period, in the project timezone. */+ period_end: string;+ /** Name of the project this recap is for. */+ project_name: string;+ /** Canonical link to this project's weekly recap. */+ recap_url: string;+ }+export interface WeeklyDigestResponse {/** Unique visitors. */visitors: NumericMetric;@@ -58823,6 +58884,17 @@ export namespace Schemas {search?: string;};+ export type EnvironmentsWebAnalyticsRecapParams = {+ /**+ * When true (default), include period-over-period change for each metric comparing against the prior equal-length period. Set to false to skip the comparison query.+ */+ compare?: boolean;+ /**+ * Lookback window in days (1–90). Defaults to 7.+ */+ days?: number;+ };+export type EnvironmentsWebAnalyticsWeeklyDigestParams = {/*** When true (default), include period-over-period change for each metric comparing against the prior equal-length period. Set to false to skip the comparison query (faster).@@ -66307,6 +66379,17 @@ export namespace Schemas {search?: string;};+ export type WebAnalyticsRecapParams = {+ /**+ * When true (default), include period-over-period change for each metric comparing against the prior equal-length period. Set to false to skip the comparison query.+ */+ compare?: boolean;+ /**+ * Lookback window in days (1–90). Defaults to 7.+ */+ days?: number;+ };+export type WebAnalyticsWeeklyDigestParams = {/*** When true (default), include period-over-period change for each metric comparing against the prior equal-length period. Set to false to skip the comparison query (faster).