Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(content): show the results from AI visits per AI source in the Impact tab (#1291)
Cihan0ceac8659d1c
diff --git a/supabase/migrations/00210_content_page_results.sql b/supabase/migrations/00210_content_page_results.sqlnew file mode 100644index 000000000..a40913437--- /dev/null+++ b/supabase/migrations/00210_content_page_results.sql@@ -0,0 +1,164 @@+-- ============================================================================+-- 00210: results from AI visits per AI source, for the editor's Impact tab+-- ============================================================================+-- The Impact tab's "Results from AI visits" (Content Editor spec v2 §7,+-- CE-016) shows what visitors from AI assistants did after landing on the+-- page a draft optimizes, and which assistant sent them.+--+-- content_page_results(brand, page, days) returns one jsonb over the last N+-- whole UTC days, ending yesterday, as content_page_impact (00209) counts them:+-- * analytics: whether the brand has a Google Analytics property mapped;+-- conversions come only from it until the snippet records goals (CE-017);+-- * purchases: whether the property reported purchases in the window, on+-- any page or channel, so the tab shows orders and revenue even where+-- this page had none;+-- * sources: one row per AI source key (the AI source list's, 00175) with+-- - visits: AI-referred visits, by ai_traffic_merged's rule (00176):+-- the snippet on days it was active for the brand, Google Analytics+-- on other days, never both; they add up to the tab's AI visits;+-- - sessions, key_events, key_event_sessions, transactions, revenue:+-- Google Analytics' AI sessions that landed on the page, with their+-- key events, sessions with a key event (the rate, 00177), purchases+-- and purchase revenue, on every day of the window.+-- A page is one lower(normalize_page_path) key, as in 00209. Analytics rows+-- without a landing page are left out: normalize_page_path('') is '/'.+--+-- Security definer with an organization check, as content_page_impact, and+-- planned for each call's own values, as it is (plan_cache_mode).++create or replace function public.content_page_results(+ p_brand_id uuid,+ p_page text,+ p_days integer+)+returns jsonb+language plpgsql+stable+security definer+set search_path to 'public'+set plan_cache_mode to 'force_custom_plan'+as $$+declare+ v_key text := lower(public.normalize_page_path(p_page));+ -- The last whole day.+ v_last_day date := (now() at time zone 'utc')::date - 1;+ v_day date;+ v_from timestamptz;+ v_until timestamptz;+ v_result jsonb;+begin+ if not exists (+ select 1 from public.brands b+ join public.profiles pf on pf.organization_id = b.organization_id+ where b.id = p_brand_id and pf.id = auth.uid()+ ) and auth.role() is distinct from 'service_role' then+ return null;+ end if;+ if p_days is null or p_days < 1 or p_days > 366 or p_page is null then+ raise exception 'content_page_results: a page and 1 to 366 days are needed'+ using errcode = '22023';+ end if;++ v_day := v_last_day - p_days + 1;+ v_from := v_day::timestamp at time zone 'utc';+ v_until := (v_last_day + 1)::timestamp at time zone 'utc';++ with snippet_days as (+ select distinct (l.created_at at time zone 'utc')::date as day+ from public.ai_traffic_logs l+ where l.brand_id = p_brand_id+ and l.visit_of is null+ and l.created_at >= v_from+ and l.created_at < v_until+ ),+ visits as (+ select coalesce(nullif(l.source_platform, ''), 'unknown') as platform, count(*)::bigint as n+ from public.ai_traffic_logs l+ where l.brand_id = p_brand_id+ and l.visit_of is null+ and l.created_at >= v_from+ and l.created_at < v_until+ and lower(public.normalize_page_path(l.url)) = v_key+ group by 1+ union all+ select coalesce(g.platform, g.source), sum(g.sessions)::bigint+ from public.ga_ai_traffic_stats g+ where g.brand_id = p_brand_id+ and g.sessions > 0+ and g.landing_page <> ''+ and g.date >= v_day+ and g.date <= v_last_day+ and lower(public.normalize_page_path(g.landing_page)) = v_key+ and not exists (select 1 from snippet_days s where s.day = g.date)+ group by 1+ ),+ analytics as (+ select+ coalesce(g.platform, g.source) as platform,+ sum(g.sessions)::bigint as sessions,+ sum(g.key_events)::bigint as key_events,+ sum(g.key_event_sessions)::bigint as key_event_sessions,+ sum(g.transactions)::bigint as transactions,+ coalesce(sum(g.purchase_revenue), 0)::numeric as revenue+ from public.ga_ai_traffic_stats g+ where g.brand_id = p_brand_id+ and g.landing_page <> ''+ and g.date >= v_day+ and g.date <= v_last_day+ and lower(public.normalize_page_path(g.landing_page)) = v_key+ group by 1+ ),+ sources as (+ select+ p.platform,+ coalesce(v.n, 0) as visits,+ coalesce(a.sessions, 0) as sessions,+ coalesce(a.key_events, 0) as key_events,+ coalesce(a.key_event_sessions, 0) as key_event_sessions,+ coalesce(a.transactions, 0) as transactions,+ coalesce(a.revenue, 0) as revenue+ from (select platform from visits union select platform from analytics) p+ left join (select platform, sum(n) as n from visits group by platform) v on v.platform = p.platform+ left join analytics a on a.platform = p.platform+ )+ select jsonb_build_object(+ 'analytics', (+ select nullif(b.ga_property_id, '') is not null+ from public.brands b where b.id = p_brand_id+ ),+ 'purchases', exists (+ select 1 from public.ga_ai_traffic_stats g+ where g.brand_id = p_brand_id+ and g.date >= v_day+ and g.date <= v_last_day+ and (g.transactions > 0 or g.purchase_revenue > 0)+ ) or exists (+ select 1 from public.ga_channel_stats c+ where c.brand_id = p_brand_id+ and c.date >= v_day+ and c.date <= v_last_day+ and (c.transactions > 0 or c.purchase_revenue > 0)+ ),+ 'sources', coalesce((+ select jsonb_agg(jsonb_build_object(+ 'platform', s.platform,+ 'visits', s.visits,+ 'sessions', s.sessions,+ 'keyEvents', s.key_events,+ 'keyEventSessions', s.key_event_sessions,+ 'transactions', s.transactions,+ 'revenue', s.revenue+ ) order by s.visits desc, s.sessions desc, s.platform)+ from sources s+ ), '[]'::jsonb)+ ) into v_result;+ return v_result;+end;+$$;++revoke all on function public.content_page_results(uuid, text, integer) from public, anon;+grant execute on function public.content_page_results(uuid, text, integer)+ to authenticated, service_role;++comment on function public.content_page_results(uuid, text, integer) is+ 'Content Editor (CE-016): one page''s AI visits per AI source over the last N whole UTC days (ending yesterday), with Google Analytics'' AI sessions landing on it, their key events, purchases and revenue. Security definer with an organization check.';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 9025dc611..8104cdbf5 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -29374,3 +29374,171 @@ grant execute on function public.content_page_impact(uuid, text, integer)comment on function public.content_page_impact(uuid, text, integer) is'Content Editor (CE-016): one page''s citations, AI visits, Google clicks and citing prompts over the last N whole UTC days (ending yesterday) and the N before. Security definer with an organization check.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00210_content_page_results.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00210: results from AI visits per AI source, for the editor's Impact tab+-- ============================================================================+-- The Impact tab's "Results from AI visits" (Content Editor spec v2 §7,+-- CE-016) shows what visitors from AI assistants did after landing on the+-- page a draft optimizes, and which assistant sent them.+--+-- content_page_results(brand, page, days) returns one jsonb over the last N+-- whole UTC days, ending yesterday, as content_page_impact (00209) counts them:+-- * analytics: whether the brand has a Google Analytics property mapped;+-- conversions come only from it until the snippet records goals (CE-017);+-- * purchases: whether the property reported purchases in the window, on+-- any page or channel, so the tab shows orders and revenue even where+-- this page had none;+-- * sources: one row per AI source key (the AI source list's, 00175) with+-- - visits: AI-referred visits, by ai_traffic_merged's rule (00176):+-- the snippet on days it was active for the brand, Google Analytics+-- on other days, never both; they add up to the tab's AI visits;+-- - sessions, key_events, key_event_sessions, transactions, revenue:+-- Google Analytics' AI sessions that landed on the page, with their+-- key events, sessions with a key event (the rate, 00177), purchases+-- and purchase revenue, on every day of the window.+-- A page is one lower(normalize_page_path) key, as in 00209. Analytics rows+-- without a landing page are left out: normalize_page_path('') is '/'.+--+-- Security definer with an organization check, as content_page_impact, and+-- planned for each call's own values, as it is (plan_cache_mode).++create or replace function public.content_page_results(+ p_brand_id uuid,+ p_page text,+ p_days integer+)+returns jsonb+language plpgsql+stable+security definer+set search_path to 'public'+set plan_cache_mode to 'force_custom_plan'+as $$+declare+ v_key text := lower(public.normalize_page_path(p_page));+ -- The last whole day.+ v_last_day date := (now() at time zone 'utc')::date - 1;+ v_day date;+ v_from timestamptz;+ v_until timestamptz;+ v_result jsonb;+begin+ if not exists (+ select 1 from public.brands b+ join public.profiles pf on pf.organization_id = b.organization_id+ where b.id = p_brand_id and pf.id = auth.uid()+ ) and auth.role() is distinct from 'service_role' then+ return null;+ end if;+ if p_days is null or p_days < 1 or p_days > 366 or p_page is null then+ raise exception 'content_page_results: a page and 1 to 366 days are needed'+ using errcode = '22023';+ end if;++ v_day := v_last_day - p_days + 1;+ v_from := v_day::timestamp at time zone 'utc';+ v_until := (v_last_day + 1)::timestamp at time zone 'utc';++ with snippet_days as (+ select distinct (l.created_at at time zone 'utc')::date as day+ from public.ai_traffic_logs l+ where l.brand_id = p_brand_id+ and l.visit_of is null+ and l.created_at >= v_from+ and l.created_at < v_until+ ),+ visits as (+ select coalesce(nullif(l.source_platform, ''), 'unknown') as platform, count(*)::bigint as n+ from public.ai_traffic_logs l+ where l.brand_id = p_brand_id+ and l.visit_of is null+ and l.created_at >= v_from+ and l.created_at < v_until+ and lower(public.normalize_page_path(l.url)) = v_key+ group by 1+ union all+ select coalesce(g.platform, g.source), sum(g.sessions)::bigint+ from public.ga_ai_traffic_stats g+ where g.brand_id = p_brand_id+ and g.sessions > 0+ and g.landing_page <> ''+ and g.date >= v_day+ and g.date <= v_last_day+ and lower(public.normalize_page_path(g.landing_page)) = v_key+ and not exists (select 1 from snippet_days s where s.day = g.date)+ group by 1+ ),+ analytics as (+ select+ coalesce(g.platform, g.source) as platform,+ sum(g.sessions)::bigint as sessions,+ sum(g.key_events)::bigint as key_events,+ sum(g.key_event_sessions)::bigint as key_event_sessions,+ sum(g.transactions)::bigint as transactions,+ coalesce(sum(g.purchase_revenue), 0)::numeric as revenue+ from public.ga_ai_traffic_stats g+ where g.brand_id = p_brand_id+ and g.landing_page <> ''+ and g.date >= v_day+ and g.date <= v_last_day+ and lower(public.normalize_page_path(g.landing_page)) = v_key+ group by 1+ ),+ sources as (+ select+ p.platform,+ coalesce(v.n, 0) as visits,+ coalesce(a.sessions, 0) as sessions,+ coalesce(a.key_events, 0) as key_events,+ coalesce(a.key_event_sessions, 0) as key_event_sessions,+ coalesce(a.transactions, 0) as transactions,+ coalesce(a.revenue, 0) as revenue+ from (select platform from visits union select platform from analytics) p+ left join (select platform, sum(n) as n from visits group by platform) v on v.platform = p.platform+ left join analytics a on a.platform = p.platform+ )+ select jsonb_build_object(+ 'analytics', (+ select nullif(b.ga_property_id, '') is not null+ from public.brands b where b.id = p_brand_id+ ),+ 'purchases', exists (+ select 1 from public.ga_ai_traffic_stats g+ where g.brand_id = p_brand_id+ and g.date >= v_day+ and g.date <= v_last_day+ and (g.transactions > 0 or g.purchase_revenue > 0)+ ) or exists (+ select 1 from public.ga_channel_stats c+ where c.brand_id = p_brand_id+ and c.date >= v_day+ and c.date <= v_last_day+ and (c.transactions > 0 or c.purchase_revenue > 0)+ ),+ 'sources', coalesce((+ select jsonb_agg(jsonb_build_object(+ 'platform', s.platform,+ 'visits', s.visits,+ 'sessions', s.sessions,+ 'keyEvents', s.key_events,+ 'keyEventSessions', s.key_event_sessions,+ 'transactions', s.transactions,+ 'revenue', s.revenue+ ) order by s.visits desc, s.sessions desc, s.platform)+ from sources s+ ), '[]'::jsonb)+ ) into v_result;+ return v_result;+end;+$$;++revoke all on function public.content_page_results(uuid, text, integer) from public, anon;+grant execute on function public.content_page_results(uuid, text, integer)+ to authenticated, service_role;++comment on function public.content_page_results(uuid, text, integer) is+ 'Content Editor (CE-016): one page''s AI visits per AI source over the last N whole UTC days (ending yesterday), with Google Analytics'' AI sessions landing on it, their key events, purchases and revenue. Security definer with an organization check.';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 9448e4986..83edaa8f4 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3452,6 +3452,29 @@"wasCitedOn": "Was cited on {platforms}","seeInCitations": "See in Citations"},+ "results": {+ "title": "Results from AI visits",+ "subtitle": "AI visits that landed here",+ "keyEvents": "Key events",+ "rate": "Key event rate",+ "rateLow": "Low sample · {sessions, plural, one {# session} other {# sessions}}",+ "rateUnknown": "Not reported by Google Analytics yet",+ "orders": "Orders",+ "revenue": "Revenue",+ "needsAnalytics": "Key events, orders and revenue come from Google Analytics. Connect it to see what AI visitors do after landing here.",+ "openTraffic": "Open AI Traffic",+ "bySource": "Results by AI source",+ "none": "No AI visits to this page in this period.",+ "other": "Other",+ "columns": {+ "source": "AI source",+ "visits": "Visits",+ "keyEvents": "Key events",+ "revenue": "Revenue"+ },+ "legend": "Visits come from the tracking snippet, or from Google Analytics on days without it. Key events, orders and revenue are Google Analytics' sessions that started on this page from an AI assistant.",+ "legendVisits": "Visits come from the tracking snippet."+ },"overlap": {"title": "Your other pages for these prompts","only": "{count, plural, one {The only page cited for its prompt} other {The only page cited for its # prompts}} · no overlap",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-results.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-results.tsxnew file mode 100644index 000000000..35f6bb40e--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-results.tsx@@ -0,0 +1,129 @@+'use client';++import { useTranslations } from 'next-intl';+import { ExternalLink } from 'lucide-react';+import { Link } from '@/i18n/navigation';+import { resultSources, resultTotals, type ContentResults } from '@/lib/content/impact';+import { formatNumber } from '@/lib/format';+import { conversionRate } from '@/lib/traffic-conversions';++/**+ * The Impact tab's results from AI visits (spec §7): what visitors from AI+ * assistants did after landing on the page — Google Analytics' key events,+ * and orders and revenue when the property reports purchases — and, per AI+ * source, the visits it sent with what they did. Without Analytics, the+ * visits per source, and where to connect it.+ */+export function ImpactResults({ results }: { results: ContentResults }) {+ const t = useTranslations('contentEditor.editor.impact.results');+ const totals = resultTotals(results.sources);+ const rows = resultSources(results.sources);+ const revenue = results.analytics && results.purchases;+ const rate = conversionRate({+ aiVisits: totals.sessions,+ keyEvents: totals.keyEvents,+ keyEventSessions: totals.keyEventSessions,+ });++ return (+ <section className="space-y-2">+ <h4 className="text-xs font-medium text-muted-foreground">+ {t('title')} <span className="font-normal">· {t('subtitle')}</span>+ </h4>++ {results.analytics ? (+ <div className="grid grid-cols-2 gap-2">+ <ResultCard label={t('keyEvents')} value={formatNumber(totals.keyEvents)} />+ <ResultCard+ label={t('rate')}+ value={rate.kind === 'rate' ? `${formatNumber(rate.pct)}%` : '—'}+ hint={+ rate.kind === 'low'+ ? t('rateLow', { sessions: totals.sessions })+ : rate.kind === 'unknown'+ ? t('rateUnknown')+ : undefined+ }+ />+ {revenue && (+ <>+ <ResultCard label={t('orders')} value={formatNumber(totals.transactions)} />+ <ResultCard label={t('revenue')} value={formatNumber(Math.round(totals.revenue))} />+ </>+ )}+ </div>+ ) : (+ <p className="rounded-lg border border-dashed px-3 py-2 text-xs text-muted-foreground">+ {t('needsAnalytics')}{' '}+ <Link+ href="/dashboard/traffic"+ className="inline-flex items-center gap-1 font-medium text-primary hover:underline"+ >+ {t('openTraffic')}+ <ExternalLink className="h-3 w-3" />+ </Link>+ </p>+ )}++ {rows.length === 0 ? (+ <p className="text-xs text-muted-foreground">{t('none')}</p>+ ) : (+ <table className="w-full text-xs">+ <caption className="sr-only">{t('bySource')}</caption>+ <thead>+ <tr className="border-b text-muted-foreground">+ <th scope="col" className="py-1.5 text-left font-medium">+ {t('columns.source')}+ </th>+ <th scope="col" className="py-1.5 text-right font-medium">+ {t('columns.visits')}+ </th>+ {results.analytics && (+ <th scope="col" className="py-1.5 text-right font-medium">+ {t('columns.keyEvents')}+ </th>+ )}+ {revenue && (+ <th scope="col" className="py-1.5 text-right font-medium">+ {t('columns.revenue')}+ </th>+ )}+ </tr>+ </thead>+ <tbody className="tabular-nums">+ {rows.map((row) => (+ <tr key={row.name ?? 'other'} className="border-b last:border-b-0">+ <th scope="row" className="py-1.5 text-left font-normal">+ {row.name ?? t('other')}+ </th>+ <td className="py-1.5 text-right">{formatNumber(row.visits)}</td>+ {results.analytics && (+ <td className="py-1.5 text-right">{formatNumber(row.keyEvents)}</td>+ )}+ {revenue && (+ <td className="py-1.5 text-right">{formatNumber(Math.round(row.revenue))}</td>+ )}+ </tr>+ ))}+ </tbody>+ </table>+ )}++ {rows.length > 0 && (+ <p className="text-[11px] leading-relaxed text-muted-foreground">+ {results.analytics ? t('legend') : t('legendVisits')}+ </p>+ )}+ </section>+ );+}++function ResultCard({ label, value, hint }: { label: string; value: string; hint?: string }) {+ return (+ <div className="rounded-lg border px-3 py-2" title={hint}>+ <p className="text-xs text-muted-foreground">{label}</p>+ <p className="text-lg font-semibold tabular-nums">{value}</p>+ {hint && <p className="truncate text-xs text-muted-foreground">{hint}</p>}+ </div>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.test.tsxindex 6494ae57d..a3b9059f6 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.test.tsx@@ -3,12 +3,14 @@ import { createRoot, type Root } from 'react-dom/client';import { NextIntlClientProvider } from 'next-intl';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import messages from '../../../../../../../../messages/en.json';-import type { ContentImpact } from '@/lib/content/impact';+import type { ContentImpact, ContentResults, ResultSource } from '@/lib/content/impact';import { ImpactTab } from './_impact-tab';const getContentImpact = vi.fn();+const getContentResults = vi.fn();vi.mock('@/lib/actions/content-drafts', () => ({getContentImpact: (...args: unknown[]) => getContentImpact(...args),+ getContentResults: (...args: unknown[]) => getContentResults(...args),}));vi.mock('@/i18n/navigation', () => ({Link: ({ href, children, ...props }: { href: string; children: React.ReactNode }) => (@@ -54,6 +56,28 @@ const impact = (over: Partial<ContentImpact> = {}): ContentImpact => ({...over,});+const source = (platform: string, over: Partial<ResultSource> = {}): ResultSource => ({+ platform,+ visits: 0,+ sessions: 0,+ keyEvents: 0,+ keyEventSessions: 0,+ transactions: 0,+ revenue: 0,+ ...over,+});++const results = (over: Partial<ContentResults> = {}): ContentResults => ({+ analytics: true,+ purchases: false,+ sources: [+ source('chatgpt.com', { visits: 30, sessions: 40, keyEvents: 6, keyEventSessions: 4 }),+ source('perplexity.ai', { visits: 8, sessions: 2, keyEvents: 1, keyEventSessions: 1 }),+ source('unknown', { visits: 3 }),+ ],+ ...over,+});+let container: HTMLDivElement;let root: Root;@@ -80,6 +104,7 @@ beforeEach(() => {document.body.appendChild(container);root = createRoot(container);getContentImpact.mockReset();+ getContentResults.mockReset().mockResolvedValue(results());});afterEach(() => {@@ -94,6 +119,7 @@ describe('the Impact tab', () => {await render();expect(getContentImpact).toHaveBeenCalledWith('b1', PAGE, 30);+ expect(getContentResults).toHaveBeenCalledWith('b1', PAGE, 30);expect(periodButton('30d').getAttribute('aria-pressed')).toBe('true');expect(metric('Citations')).toBe('Citations45+50%');expect(metric('AI visits')).toBe('AI visits4Low sample');@@ -142,6 +168,7 @@ describe('the Impact tab', () => {await render();await act(async () => periodButton('90d').click());expect(getContentImpact).toHaveBeenLastCalledWith('b1', PAGE, 90);+ expect(getContentResults).toHaveBeenLastCalledWith('b1', PAGE, 90);expect(periodButton('90d').getAttribute('aria-pressed')).toBe('true');expect(container.textContent).toContain('The last 90 days against the 90 before');});@@ -185,9 +212,96 @@ describe('the Impact tab', () => {expect(metric('Citations')).toBe('Citations45+50%');});+ describe('results from AI visits', () => {+ const resultRows = () =>+ [...container.querySelectorAll('tbody tr')].map((tr) =>+ [...tr.children].map((cell) => cell.textContent),+ );+ const headers = () => [...container.querySelectorAll('thead th')].map((th) => th.textContent);++ it('shows the key events from AI visits and each source’s visits and key events', async () => {+ getContentImpact.mockResolvedValue(impact());+ await render();++ expect(container.textContent).toContain('Results from AI visits');+ expect(metric('Key events')).toBe('Key events7');+ // 5 of 42 Analytics sessions had a key event.+ expect(metric('Key event rate')).toBe('Key event rate11.9%');+ expect(metric('Orders')).toBeUndefined();+ expect(headers()).toEqual(['AI source', 'Visits', 'Key events']);+ expect(resultRows()).toEqual([+ ['ChatGPT', '30', '6'],+ ['Perplexity', '8', '1'],+ ['Other', '3', '0'],+ ]);+ });++ it('adds orders and revenue when the property reports purchases', async () => {+ getContentImpact.mockResolvedValue(impact());+ getContentResults.mockResolvedValue(+ results({+ purchases: true,+ sources: [+ source('chatgpt.com', {+ visits: 12,+ sessions: 12,+ keyEvents: 3,+ keyEventSessions: 3,+ transactions: 2,+ revenue: 1234.6,+ }),+ ],+ }),+ );+ await render();++ expect(metric('Orders')).toBe('Orders2');+ expect(metric('Revenue')).toBe('Revenue1,235');+ // 12 sessions: too few for a rate.+ expect(metric('Key event rate')).toBe('Key event rate—Low sample · 12 sessions');+ expect(headers()).toEqual(['AI source', 'Visits', 'Key events', 'Revenue']);+ expect(resultRows()).toEqual([['ChatGPT', '12', '3', '1,235']]);+ });++ it('lists the visits per source, and where to connect Google Analytics, without it', async () => {+ getContentImpact.mockResolvedValue(impact());+ getContentResults.mockResolvedValue(+ results({ analytics: false, sources: [source('claude.ai', { visits: 5 })] }),+ );+ await render();++ expect(metric('Key events')).toBeUndefined();+ expect(container.textContent).toContain('come from Google Analytics');+ expect(container.querySelector('a[href="/dashboard/traffic"]')!.textContent).toBe(+ 'Open AI Traffic',+ );+ expect(headers()).toEqual(['AI source', 'Visits']);+ expect(resultRows()).toEqual([['Claude', '5']]);+ expect(container.textContent).toContain('Visits come from the tracking snippet.');+ });++ it('says when no AI visits reached the page', async () => {+ getContentImpact.mockResolvedValue(impact());+ getContentResults.mockResolvedValue(results({ sources: [] }));+ await render();+ expect(metric('Key events')).toBe('Key events0');+ expect(container.textContent).toContain('No AI visits to this page in this period.');+ expect(container.querySelector('table')).toBeNull();+ });++ it('counts a failed read of the results as a failed tab', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ getContentImpact.mockResolvedValue(impact());+ getContentResults.mockRejectedValueOnce(new Error('boom'));+ await render();+ expect(container.textContent).toContain("Couldn't load the page's impact.");+ });+ });+it('has nothing to measure for a new page', async () => {await render(null);expect(getContentImpact).not.toHaveBeenCalled();+ expect(getContentResults).not.toHaveBeenCalled();expect(container.textContent).toContain('This draft is a new page, not live yet');});});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.tsxindex 9a22e3cfc..db18b9ada 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.tsx@@ -4,7 +4,7 @@ import { useEffect, useState } from 'react';import { useTranslations } from 'next-intl';import { Check, ExternalLink, Loader2 } from 'lucide-react';import { Link } from '@/i18n/navigation';-import { getContentImpact } from '@/lib/actions/content-drafts';+import { getContentImpact, getContentResults } from '@/lib/actions/content-drafts';import {DEFAULT_IMPACT_PERIOD,GSC_PAGE_DAYS,@@ -14,6 +14,7 @@ import {isLost,platformNames,type ContentImpact,+ type ContentResults,type ImpactPeriod,} from '@/lib/content/impact';import { pagePath } from '@/lib/content/overlap';@@ -21,11 +22,13 @@ import { formatNumber } from '@/lib/format';import { formatPctChange } from '@/lib/traffic-kpis';import type { VisitChange } from '@/lib/traffic-change';import { cn } from '@/lib/utils';+import { ImpactResults } from './_impact-results';/** One read of the tab, for one period: null while it runs. */interface ImpactRead {period: ImpactPeriod;impact: ContentImpact | null;+ results: ContentResults | null;failed: boolean;}@@ -33,8 +36,9 @@ interface ImpactRead {* The Impact tab (Content Editor CE-016, spec §7): what the page a draft* optimizes earns. Every number follows the period: citations, AI visits,* Google clicks and prompts cited, each against the period before; the- * prompts themselves, always listed, the ones it lost marked; the brand's- * other pages cited for them; and where the numbers come from.+ * prompts themselves, always listed, the ones it lost marked; the results+ * from AI visits, per AI source; the brand's other pages cited for the same+ * prompts; and where the numbers come from.*/export function ImpactTab({ brandId, pageUrl }: { brandId: string; pageUrl: string | null }) {const t = useTranslations('contentEditor.editor.impact');@@ -45,13 +49,16 @@ export function ImpactTab({ brandId, pageUrl }: { brandId: string; pageUrl: striuseEffect(() => {if (!pageUrl) return;let cancelled = false;- getContentImpact(brandId, pageUrl, period)- .then((impact) => {- if (!cancelled) setRead({ period, impact, failed: false });+ Promise.all([+ getContentImpact(brandId, pageUrl, period),+ getContentResults(brandId, pageUrl, period),+ ])+ .then(([impact, results]) => {+ if (!cancelled) setRead({ period, impact, results, failed: false });}).catch((err) => {console.error('Failed to read the page impact:', err);- if (!cancelled) setRead({ period, impact: null, failed: true });+ if (!cancelled) setRead({ period, impact: null, results: null, failed: true });});return () => {cancelled = true;@@ -111,7 +118,7 @@ export function ImpactTab({ brandId, pageUrl }: { brandId: string; pageUrl: stri</button></p>) : (- <ImpactBody impact={impact} period={period} pageUrl={pageUrl} />+ <ImpactBody impact={impact} results={current.results} period={period} pageUrl={pageUrl} />)}</div>);@@ -119,10 +126,12 @@ export function ImpactTab({ brandId, pageUrl }: { brandId: string; pageUrl: strifunction ImpactBody({impact,+ results,period,pageUrl,}: {impact: ContentImpact;+ results: ContentResults | null;period: ImpactPeriod;pageUrl: string;}) {@@ -239,6 +248,8 @@ function ImpactBody({</Link></section>+ {results && <ImpactResults results={results} />}+{cited.cur > 0 && (<section className="space-y-1.5"><h4 className="text-xs font-medium text-muted-foreground">{t('overlap.title')}</h4>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsxindex 6a7e1de89..ee63d7b51 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx@@ -11,8 +11,10 @@ const markContentDraftReady = vi.fn();const saveContentDraft = vi.fn();const setContentDraftPageType = vi.fn();const getContentImpact = vi.fn();+const getContentResults = vi.fn();vi.mock('@/lib/actions/content-drafts', () => ({getContentImpact: (...args: unknown[]) => getContentImpact(...args),+ getContentResults: (...args: unknown[]) => getContentResults(...args),getContentDraft: (...args: unknown[]) => getContentDraft(...args),markContentDraftReady: (...args: unknown[]) => markContentDraftReady(...args),saveContentDraft: (...args: unknown[]) => saveContentDraft(...args),@@ -139,6 +141,7 @@ beforeEach(() => {setContentDraftPageType.mockReset().mockResolvedValue(undefined);saveContentDraft.mockReset().mockResolvedValue({ updatedAt: '2026-10-20T10:00:00Z' });getContentImpact.mockReset().mockResolvedValue(null);+ getContentResults.mockReset().mockResolvedValue(null);localStorage.clear();brandState.activeBrandId = 'b1';brandState.setActiveBrand.mockReset();@@ -579,6 +582,7 @@ describe('the side panel', () => {expect(panel()!.textContent).toContain('Impact');// The page the draft optimizes, over 30 days.expect(getContentImpact).toHaveBeenCalledWith('b1', 'https://acme.example.com/pricing', 30);+ expect(getContentResults).toHaveBeenCalledWith('b1', 'https://acme.example.com/pricing', 30);expect(button('Hide side panel')!.getAttribute('aria-pressed')).toBe('true');});diff --git a/web/src/lib/actions/content-drafts-impact.test.ts b/web/src/lib/actions/content-drafts-impact.test.tsindex 161b6d1e7..2b1575cc3 100644--- a/web/src/lib/actions/content-drafts-impact.test.ts+++ b/web/src/lib/actions/content-drafts-impact.test.ts@@ -18,7 +18,7 @@ vi.mock('@/lib/supabase/server', () => ({})),}));-const { getContentImpact } = await import('./content-drafts');+const { getContentImpact, getContentResults } = await import('./content-drafts');beforeEach(() => {rpcCalls = [];@@ -59,3 +59,41 @@ describe('getContentImpact', () => {expect(rpcCalls).toEqual([]);});});++describe('getContentResults', () => {+ it('reads the page’s results over the period asked for', async () => {+ const results = {+ analytics: true,+ purchases: false,+ sources: [+ {+ platform: 'chatgpt.com',+ visits: 9,+ sessions: 12,+ keyEvents: 5,+ keyEventSessions: 4,+ transactions: 0,+ revenue: 0,+ },+ ],+ };+ rpcResult = { data: results, error: null };+ expect(await getContentResults(BRAND, PAGE, 7)).toEqual(results);+ expect(rpcCalls).toEqual([+ { fn: 'content_page_results', args: { p_brand_id: BRAND, p_page: PAGE, p_days: 7 } },+ ]);+ });++ it('returns null outside the organization and throws when the read fails', async () => {+ expect(await getContentResults(BRAND, PAGE, 30)).toBeNull();+ rpcResult = { data: null, error: { message: 'boom' } };+ await expect(getContentResults(BRAND, PAGE, 30)).rejects.toThrow('boom');+ });++ it('reads nothing for a malformed brand, a period not offered, or a page without an address', async () => {+ await expect(getContentResults('b1', PAGE, 30)).rejects.toThrow('invalid');+ await expect(getContentResults(BRAND, PAGE, 60)).rejects.toThrow('invalid');+ await expect(getContentResults(BRAND, '/pricing', 30)).rejects.toThrow('invalid');+ expect(rpcCalls).toEqual([]);+ });+});diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex fdecb712f..12190b89d 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -20,7 +20,7 @@ import {PAGE_IMPORT_ERRORS,} from '@/lib/content/drafts';import { escapeHtml } from '@/lib/content/attachments';-import { IMPACT_PERIODS, type ContentImpact } from '@/lib/content/impact';+import { IMPACT_PERIODS, type ContentImpact, type ContentResults } from '@/lib/content/impact';import {MAX_BODY_HTML_LENGTH,MAX_TITLE_LENGTH,@@ -371,13 +371,7 @@ export async function getContentImpact(page: string,days: number,): Promise<ContentImpact | null> {- if (- !draftId.safeParse(brandId).success ||- !(IMPACT_PERIODS as readonly number[]).includes(days) ||- !/^https?:\/\//i.test(page)- ) {- throw new Error('invalid');- }+ if (!impactArgsValid(brandId, page, days)) throw new Error('invalid');const supabase = await createClient();const { data, error } = await supabase.rpc('content_page_impact', {p_brand_id: brandId,@@ -388,6 +382,37 @@ export async function getContentImpact(return (data as ContentImpact | null) ?? null;}+/**+ * The Impact tab's results from AI visits (CE-016): the page's AI visits per+ * AI source over the last `days`, with Google Analytics' key events,+ * purchases and revenue from them (content_page_results, 00210). Null when+ * the member can't read the brand.+ */+export async function getContentResults(+ brandId: string,+ page: string,+ days: number,+): Promise<ContentResults | null> {+ if (!impactArgsValid(brandId, page, days)) throw new Error('invalid');+ const supabase = await createClient();+ const { data, error } = await supabase.rpc('content_page_results', {+ p_brand_id: brandId,+ p_page: page,+ p_days: days,+ });+ if (error) throw new Error(error.message);+ return (data as ContentResults | null) ?? null;+}++/** A brand id, a period the tab offers and a web page's address. */+function impactArgsValid(brandId: string, page: string, days: number): boolean {+ return (+ draftId.safeParse(brandId).success &&+ (IMPACT_PERIODS as readonly number[]).includes(days) &&+ /^https?:\/\//i.test(page)+ );+}+const overlapSource = startInput.shape.source;/**diff --git a/web/src/lib/content/impact.test.ts b/web/src/lib/content/impact.test.tsindex 595765d90..6c1136f14 100644--- a/web/src/lib/content/impact.test.ts+++ b/web/src/lib/content/impact.test.ts@@ -5,7 +5,10 @@ import {impactWindows,isLost,platformNames,+ resultSources,+ resultTotals,type ImpactPrompt,+ type ResultSource,} from './impact';const TODAY = new Date('2026-10-20T22:30:00Z');@@ -76,3 +79,61 @@ describe('prompts', () => {expect(platformNames(['new-engine'])).toEqual(['new-engine']);});});++describe('results from AI visits', () => {+ const source = (platform: string, over: Partial<ResultSource> = {}): ResultSource => ({+ platform,+ visits: 0,+ sessions: 0,+ keyEvents: 0,+ keyEventSessions: 0,+ transactions: 0,+ revenue: 0,+ ...over,+ });+ const sources = [+ source('perplexity.ai', { visits: 4, sessions: 2, keyEvents: 1, keyEventSessions: 1 }),+ source('chatgpt.com', {+ visits: 9,+ sessions: 12,+ keyEvents: 5,+ keyEventSessions: 4,+ transactions: 1,+ revenue: 40,+ }),+ source('chat.openai.com', { visits: 1, sessions: 1 }),+ source('unknown', { visits: 20 }),+ source('made-up.example', { visits: 2, keyEvents: 1 }),+ source('gemini.google.com', { sessions: 4, keyEvents: 1, keyEventSessions: 1 }),+ // Sessions on a snippet day, with nothing else: no row.+ source('claude.ai', { sessions: 3 }),+ ];++ it('adds every source up for the cards', () => {+ expect(resultTotals(sources)).toEqual({+ visits: 36,+ sessions: 22,+ keyEvents: 8,+ keyEventSessions: 6,+ transactions: 1,+ revenue: 40,+ });+ expect(resultTotals([])).toEqual({+ visits: 0,+ sessions: 0,+ keyEvents: 0,+ keyEventSessions: 0,+ transactions: 0,+ revenue: 0,+ });+ });++ it('lists one row per platform name, the most visits first, and the rest as Other', () => {+ expect(resultSources(sources).map((row) => [row.name, row.visits, row.keyEvents])).toEqual([+ ['ChatGPT', 10, 5],+ ['Perplexity', 4, 1],+ ['Gemini', 0, 1],+ [null, 22, 1],+ ]);+ });+});diff --git a/web/src/lib/content/impact.ts b/web/src/lib/content/impact.tsindex b5b8e2fd2..e1bea5698 100644--- a/web/src/lib/content/impact.ts+++ b/web/src/lib/content/impact.ts@@ -1,5 +1,6 @@import { PLATFORM_LABELS } from '@/config/platform-labels';import { visitChange, type VisitChange } from '@/lib/traffic-change';+import { getPlatformName, isNamedPlatform } from '@/lib/traffic-platforms';/*** The editor's Impact tab (Content Editor CE-016, spec §7): what the page a@@ -80,3 +81,83 @@ export function isLost(prompt: ImpactPrompt): boolean {export function platformNames(platforms: string[]): string[] {return [...new Set(platforms.map((p) => PLATFORM_LABELS[p] ?? p))];}++/**+ * Results from AI visits (spec §7), as content_page_results (00210) reads+ * them for the same window: one row per AI source key, with its AI visits+ * (the snippet or Analytics, never both, as the AI visits card) and Google+ * Analytics' AI sessions landing on the page, their key events and purchases.+ */+export interface ResultSource {+ platform: string;+ visits: number;+ sessions: number;+ keyEvents: number;+ keyEventSessions: number;+ transactions: number;+ revenue: number;+}++export interface ContentResults {+ /** A Google Analytics property is mapped: key events and purchases come only from it. */+ analytics: boolean;+ /** The property reported purchases in the window, on any page. */+ purchases: boolean;+ sources: ResultSource[];+}++/** A source row as the tab lists it; a null name is "Other", the keys the page can't name. */+export interface NamedResultSource extends Omit<ResultSource, 'platform'> {+ name: string | null;+}++type ResultFigures = Omit<ResultSource, 'platform'>;++const NO_RESULTS: ResultFigures = {+ visits: 0,+ sessions: 0,+ keyEvents: 0,+ keyEventSessions: 0,+ transactions: 0,+ revenue: 0,+};++function addFigures(a: ResultFigures, b: ResultFigures): ResultFigures {+ return {+ visits: a.visits + b.visits,+ sessions: a.sessions + b.sessions,+ keyEvents: a.keyEvents + b.keyEvents,+ keyEventSessions: a.keyEventSessions + b.keyEventSessions,+ transactions: a.transactions + b.transactions,+ revenue: a.revenue + b.revenue,+ };+}++/** All sources together: the result cards. */+export function resultTotals(sources: ResultSource[]): ResultFigures {+ return sources.reduce<ResultFigures>(addFigures, NO_RESULTS);+}++/**+ * The by-source table: one row per platform name (ChatGPT's old hosts are+ * ChatGPT), keys the page can't name folded into Other, last; the most+ * visits first, then Analytics sessions. A source with nothing to show is+ * left out: Analytics sessions on a day the snippet counted the visits.+ */+export function resultSources(sources: ResultSource[]): NamedResultSource[] {+ const byName = new Map<string | null, ResultFigures>();+ for (const { platform, ...figures } of sources) {+ const name = isNamedPlatform(platform) ? getPlatformName(platform) : null;+ byName.set(name, addFigures(byName.get(name) ?? NO_RESULTS, figures));+ }+ return [...byName]+ .map(([name, figures]) => ({ name, ...figures }))+ .filter((row) => row.visits > 0 || row.keyEvents > 0 || row.transactions > 0 || row.revenue > 0)+ .sort(+ (a, b) =>+ Number(a.name === null) - Number(b.name === null) ||+ b.visits - a.visits ||+ b.sessions - a.sessions ||+ (a.name ?? '').localeCompare(b.name ?? ''),+ );+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 4e28b10d1..b9283aa4d 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -3436,6 +3436,10 @@ export type Database = {Args: { p_brand_id: string; p_days: number; p_page: string }Returns: Json}+ content_page_results: {+ Args: { p_brand_id: string; p_days: number; p_page: string }+ Returns: Json+ }content_page_overlap: {Args: { p_brand_id: string; p_prompt_ids: string[]; p_since?: string }Returns: {