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 conversions from AI journeys through a page on the Live page tab (CE-017, part 4a) (#1530)
Cihan92a0534fd282
diff --git a/supabase/migrations/00287_content_page_conversions.sql b/supabase/migrations/00287_content_page_conversions.sqlnew file mode 100644index 000000000..a97509838--- /dev/null+++ b/supabase/migrations/00287_content_page_conversions.sql@@ -0,0 +1,195 @@+-- ============================================================================+-- 00287: conversions from AI journeys through a page, for the editor's Live page tab+-- ============================================================================+-- With conversions on (00286), the AI Traffic snippet follows a visitor who+-- came from an AI assistant to a goal. The Live page tab (CE-016) shows what+-- the page a draft optimizes took part in (Content Editor spec v2 §7, CE-017).+--+-- content_page_conversions(brand, page, days) returns one jsonb over the last+-- N whole UTC days, ending yesterday, as content_page_results (00210):+-- * enabled: whether the brand has conversions on;+-- * page: the page's key, for the tab to find it in the journeys;+-- * goals: per goal, the conversions and their units, of journeys through+-- the page: a conversion whose journey (its visitor id: the snippet+-- makes a new one for each journey) landed on the page, went through it+-- before, or converted on it;+-- * revenue: the value of their orders and bookings per currency (a value+-- without one isn't summed);+-- * sources: per AI source the journey started from (first touch), its+-- conversions;+-- * journeys: the five most frequent (the latest first among as many), each+-- its source, its pages in order (the landing page, the pages after+-- without repeats in a row, the page it converted on, as+-- lower(normalize_page_path) keys), its goal and how many.+-- The journey's first AI visit isn't its key: the server keeps a browser's+-- clock from dating it after the event, so first_at may differ within one.+-- Conversions are read through their own partial index: most events are+-- pageviews. Pages are compared by the keys stored with each event+-- (page_key, first_key, 00286). The reads are bounded whatever a sender+-- stored: a visitor id's pageviews are read once for the page, from a day+-- before its first AI visit; a journey's steps are the latest 100 pageviews+-- before its conversion; and the journeys are the latest 2,000+-- conversions' (the counts take all).+-- A page is one lower(normalize_page_path) key, as in 00209 / 00210.+--+-- Security definer with an organization check, as content_page_results, and+-- planned for each call's own values (plan_cache_mode).++create index if not exists ai_traffic_events_conversions+ on public.ai_traffic_events (brand_id, occurred_at desc)+ where kind = 'conversion';++create or replace function public.content_page_conversions(+ 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_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_conversions: a page and 1 to 366 days are needed'+ using errcode = '22023';+ end if;++ v_from := (v_last_day - p_days + 1)::timestamp at time zone 'utc';+ v_until := (v_last_day + 1)::timestamp at time zone 'utc';++ with conversions as (+ select c.*+ from public.ai_traffic_events c+ where c.brand_id = p_brand_id+ and c.kind = 'conversion'+ and c.occurred_at >= v_from+ and c.occurred_at < v_until+ ),+ -- When each visitor id first saw the page in its journey: read once per+ -- visitor id however many conversions it has, from a day before its first+ -- AI visit (first_at is clamped per event, within the server's clock+ -- allowance) to its last conversion, by the stored keys.+ seen as (+ select v.visitor_id, (+ select min(e.occurred_at)+ from public.ai_traffic_events e+ where e.brand_id = p_brand_id+ and e.visitor_id = v.visitor_id+ and e.kind = 'page'+ and e.page_key = v_key+ and e.occurred_at >= v.since+ and e.occurred_at <= v.last_at+ ) as at+ from (+ select visitor_id, min(first_at) - interval '1 day' as since, max(occurred_at) as last_at+ from conversions+ group by visitor_id+ ) v+ ),+ -- A conversion whose journey landed on the page, went through it, or converted on it.+ through as (+ select c.*+ from conversions c+ left join seen s on s.visitor_id = c.visitor_id+ where c.first_key = v_key+ or c.page_key = v_key+ or (s.at is not null and s.at <= c.occurred_at and s.at >= c.first_at - interval '1 day')+ ),+ -- The paths of the latest 2,000 (the counts above take all): the landing+ -- page, the latest 100 pageviews before the conversion, the page it+ -- converted on.+ paths as (+ select t.first_source, t.goal, t.occurred_at, (+ select array_agg(s.page order by s.ord <> 0, s.at, s.ord)+ from (+ select steps.page, steps.at, steps.ord,+ lag(steps.page) over (order by steps.ord <> 0, steps.at, steps.ord) as before+ from (+ select t.first_key as page, t.first_at as at, 0 as ord+ union all+ select p.page_key, p.occurred_at, 1+ from (+ select e.page_key, e.occurred_at+ from public.ai_traffic_events e+ where e.brand_id = p_brand_id+ and e.visitor_id = t.visitor_id+ and e.kind = 'page'+ and e.occurred_at >= t.first_at - interval '1 day'+ and e.occurred_at <= t.occurred_at+ order by e.occurred_at desc+ limit 100+ ) p+ union all+ select t.page_key, t.occurred_at, 2+ ) steps+ ) s+ where s.before is distinct from s.page+ ) as pages+ from (select * from through order by occurred_at desc limit 2000) t+ )+ select jsonb_build_object(+ 'page', v_key,+ 'enabled', coalesce((select b.conversions_enabled from public.brands b where b.id = p_brand_id), false),+ 'goals', coalesce((+ select jsonb_agg(jsonb_build_object('goal', g.goal, 'count', g.n, 'units', g.units)+ order by g.n desc, g.goal)+ from (+ select goal, count(*)::bigint as n, coalesce(sum(units), 0)::bigint as units+ from through group by goal+ ) g+ ), '[]'::jsonb),+ 'revenue', coalesce((+ select jsonb_agg(jsonb_build_object('currency', r.currency, 'value', r.value)+ order by r.value desc, r.currency)+ from (+ select currency, sum(value)::numeric as value+ from through+ where goal in ('order', 'booking') and value is not null and currency is not null+ group by currency+ ) r+ ), '[]'::jsonb),+ 'sources', coalesce((+ select jsonb_agg(jsonb_build_object('platform', s.first_source, 'conversions', s.n)+ order by s.n desc, s.first_source)+ from (select first_source, count(*)::bigint as n from through group by first_source) s+ ), '[]'::jsonb),+ 'journeys', coalesce((+ select jsonb_agg(jsonb_build_object('source', j.first_source, 'pages', to_jsonb(j.pages),+ 'goal', j.goal, 'count', j.n)+ order by j.n desc, j.latest desc, j.first_source, j.goal)+ from (+ select first_source, pages, goal, count(*)::bigint as n, max(occurred_at) as latest+ from paths+ group by first_source, pages, goal+ order by count(*) desc, max(occurred_at) desc, first_source, goal+ limit 5+ ) j+ ), '[]'::jsonb)+ ) into v_result;+ return v_result;+end;+$$;++revoke all on function public.content_page_conversions(uuid, text, integer) from public, anon;+grant execute on function public.content_page_conversions(uuid, text, integer)+ to authenticated, service_role;++comment on function public.content_page_conversions(uuid, text, integer) is+ 'Content Editor (CE-017, 00287): conversions of AI journeys through one page over the last N whole UTC days (ending yesterday), from the AI Traffic snippet (ai_traffic_events, 00286): per goal with units, value per currency, per first AI source, and the five most frequent journeys (source, pages, goal). Security definer with an organization check.';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 7ce1d74f4..834846bdb 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -40334,6 +40334,205 @@ comment on table public.ai_traffic_events isnotify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00287_content_page_conversions.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00287: conversions from AI journeys through a page, for the editor's Live page tab+-- ============================================================================+-- With conversions on (00286), the AI Traffic snippet follows a visitor who+-- came from an AI assistant to a goal. The Live page tab (CE-016) shows what+-- the page a draft optimizes took part in (Content Editor spec v2 §7, CE-017).+--+-- content_page_conversions(brand, page, days) returns one jsonb over the last+-- N whole UTC days, ending yesterday, as content_page_results (00210):+-- * enabled: whether the brand has conversions on;+-- * page: the page's key, for the tab to find it in the journeys;+-- * goals: per goal, the conversions and their units, of journeys through+-- the page: a conversion whose journey (its visitor id: the snippet+-- makes a new one for each journey) landed on the page, went through it+-- before, or converted on it;+-- * revenue: the value of their orders and bookings per currency (a value+-- without one isn't summed);+-- * sources: per AI source the journey started from (first touch), its+-- conversions;+-- * journeys: the five most frequent (the latest first among as many), each+-- its source, its pages in order (the landing page, the pages after+-- without repeats in a row, the page it converted on, as+-- lower(normalize_page_path) keys), its goal and how many.+-- The journey's first AI visit isn't its key: the server keeps a browser's+-- clock from dating it after the event, so first_at may differ within one.+-- Conversions are read through their own partial index: most events are+-- pageviews. Pages are compared by the keys stored with each event+-- (page_key, first_key, 00286). The reads are bounded whatever a sender+-- stored: a visitor id's pageviews are read once for the page, from a day+-- before its first AI visit; a journey's steps are the latest 100 pageviews+-- before its conversion; and the journeys are the latest 2,000+-- conversions' (the counts take all).+-- A page is one lower(normalize_page_path) key, as in 00209 / 00210.+--+-- Security definer with an organization check, as content_page_results, and+-- planned for each call's own values (plan_cache_mode).++create index if not exists ai_traffic_events_conversions+ on public.ai_traffic_events (brand_id, occurred_at desc)+ where kind = 'conversion';++create or replace function public.content_page_conversions(+ 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_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_conversions: a page and 1 to 366 days are needed'+ using errcode = '22023';+ end if;++ v_from := (v_last_day - p_days + 1)::timestamp at time zone 'utc';+ v_until := (v_last_day + 1)::timestamp at time zone 'utc';++ with conversions as (+ select c.*+ from public.ai_traffic_events c+ where c.brand_id = p_brand_id+ and c.kind = 'conversion'+ and c.occurred_at >= v_from+ and c.occurred_at < v_until+ ),+ -- When each visitor id first saw the page in its journey: read once per+ -- visitor id however many conversions it has, from a day before its first+ -- AI visit (first_at is clamped per event, within the server's clock+ -- allowance) to its last conversion, by the stored keys.+ seen as (+ select v.visitor_id, (+ select min(e.occurred_at)+ from public.ai_traffic_events e+ where e.brand_id = p_brand_id+ and e.visitor_id = v.visitor_id+ and e.kind = 'page'+ and e.page_key = v_key+ and e.occurred_at >= v.since+ and e.occurred_at <= v.last_at+ ) as at+ from (+ select visitor_id, min(first_at) - interval '1 day' as since, max(occurred_at) as last_at+ from conversions+ group by visitor_id+ ) v+ ),+ -- A conversion whose journey landed on the page, went through it, or converted on it.+ through as (+ select c.*+ from conversions c+ left join seen s on s.visitor_id = c.visitor_id+ where c.first_key = v_key+ or c.page_key = v_key+ or (s.at is not null and s.at <= c.occurred_at and s.at >= c.first_at - interval '1 day')+ ),+ -- The paths of the latest 2,000 (the counts above take all): the landing+ -- page, the latest 100 pageviews before the conversion, the page it+ -- converted on.+ paths as (+ select t.first_source, t.goal, t.occurred_at, (+ select array_agg(s.page order by s.ord <> 0, s.at, s.ord)+ from (+ select steps.page, steps.at, steps.ord,+ lag(steps.page) over (order by steps.ord <> 0, steps.at, steps.ord) as before+ from (+ select t.first_key as page, t.first_at as at, 0 as ord+ union all+ select p.page_key, p.occurred_at, 1+ from (+ select e.page_key, e.occurred_at+ from public.ai_traffic_events e+ where e.brand_id = p_brand_id+ and e.visitor_id = t.visitor_id+ and e.kind = 'page'+ and e.occurred_at >= t.first_at - interval '1 day'+ and e.occurred_at <= t.occurred_at+ order by e.occurred_at desc+ limit 100+ ) p+ union all+ select t.page_key, t.occurred_at, 2+ ) steps+ ) s+ where s.before is distinct from s.page+ ) as pages+ from (select * from through order by occurred_at desc limit 2000) t+ )+ select jsonb_build_object(+ 'page', v_key,+ 'enabled', coalesce((select b.conversions_enabled from public.brands b where b.id = p_brand_id), false),+ 'goals', coalesce((+ select jsonb_agg(jsonb_build_object('goal', g.goal, 'count', g.n, 'units', g.units)+ order by g.n desc, g.goal)+ from (+ select goal, count(*)::bigint as n, coalesce(sum(units), 0)::bigint as units+ from through group by goal+ ) g+ ), '[]'::jsonb),+ 'revenue', coalesce((+ select jsonb_agg(jsonb_build_object('currency', r.currency, 'value', r.value)+ order by r.value desc, r.currency)+ from (+ select currency, sum(value)::numeric as value+ from through+ where goal in ('order', 'booking') and value is not null and currency is not null+ group by currency+ ) r+ ), '[]'::jsonb),+ 'sources', coalesce((+ select jsonb_agg(jsonb_build_object('platform', s.first_source, 'conversions', s.n)+ order by s.n desc, s.first_source)+ from (select first_source, count(*)::bigint as n from through group by first_source) s+ ), '[]'::jsonb),+ 'journeys', coalesce((+ select jsonb_agg(jsonb_build_object('source', j.first_source, 'pages', to_jsonb(j.pages),+ 'goal', j.goal, 'count', j.n)+ order by j.n desc, j.latest desc, j.first_source, j.goal)+ from (+ select first_source, pages, goal, count(*)::bigint as n, max(occurred_at) as latest+ from paths+ group by first_source, pages, goal+ order by count(*) desc, max(occurred_at) desc, first_source, goal+ limit 5+ ) j+ ), '[]'::jsonb)+ ) into v_result;+ return v_result;+end;+$$;++revoke all on function public.content_page_conversions(uuid, text, integer) from public, anon;+grant execute on function public.content_page_conversions(uuid, text, integer)+ to authenticated, service_role;++comment on function public.content_page_conversions(uuid, text, integer) is+ 'Content Editor (CE-017, 00287): conversions of AI journeys through one page over the last N whole UTC days (ending yesterday), from the AI Traffic snippet (ai_traffic_events, 00286): per goal with units, value per currency, per first AI source, and the five most frequent journeys (source, pages, goal). Security definer with an organization check.';+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00289_content_draft_restored_at.sql-- ─────────────────────────────────────────────────────────────────────────diff --git a/web/messages/en.json b/web/messages/en.jsonindex 2c4621c12..4eaef4c5d 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -4179,6 +4179,41 @@"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."},+ "conversions": {+ "title": "Conversions from AI journeys",+ "subtitle": "through this page, from the AI Traffic snippet",+ "off": "Conversions aren't on for this brand, so the snippet doesn't follow AI visitors to them.",+ "turnOn": "Turn them on in Brand settings",+ "none": "No conversions from AI journeys through this page in this period.",+ "bySource": "Conversions by AI source",+ "columns": {+ "source": "AI source",+ "conversions": "Conversions"+ },+ "other": "Other",+ "journeys": "Top journeys",+ "thisPage": "This page",+ "journeyCount": "{count, plural, one {# conversion} other {# conversions}}",+ "cards": {+ "signup": "Signups",+ "demo": "Demo forms",+ "order": "Orders",+ "booking": "Bookings",+ "newsletter": "Newsletter signups",+ "custom": "Other conversions",+ "revenue": "Revenue",+ "units": "Units sold"+ },+ "goals": {+ "signup": "Signup",+ "demo": "Demo form",+ "order": "Purchase",+ "booking": "Booking",+ "newsletter": "Newsletter",+ "custom": "Conversion"+ },+ "legend": "A conversion counts here when its journey landed on this page, went through it, or ended on it, credited to the AI assistant of its first visit (30 days). Visitors who refuse cookies and AI visits without a referrer aren't seen."+ },"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-conversions.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-conversions.tsxnew file mode 100644index 000000000..c9840d88c--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-conversions.tsx@@ -0,0 +1,188 @@+'use client';++import { Fragment } from 'react';+import { useTranslations } from 'next-intl';+import { ChevronRight, ExternalLink } from 'lucide-react';+import { Link } from '@/i18n/navigation';+import {+ conversionCards,+ conversionSources,+ journeyPages,+ type ContentConversions,+ type ResultCard,+} from '@/lib/content/conversions';+import { siteTypeOf } from '@/lib/content/page-types';+import { formatNumber } from '@/lib/format';+import { getPlatformName, isNamedPlatform } from '@/lib/traffic-platforms';+import { useBrandStore } from '@/stores/use-brand-store';++/** An amount in its currency, in the app's number format; the code itself where it isn't one. */+function money(value: number, currency: string): string {+ try {+ return new Intl.NumberFormat('en-US', {+ style: 'currency',+ currency,+ maximumFractionDigits: 0,+ }).format(value);+ } catch {+ return `${formatNumber(Math.round(value))} ${currency}`;+ }+}++/**+ * The Live page tab's conversions from AI journeys through the page (spec §7,+ * CE-017): the goals the brand's kind of site counts (signups and demo forms,+ * orders, revenue and units, or bookings, revenue and newsletter signups),+ * per AI source the journey started from, and the most frequent journeys,+ * this page outlined. From the AI Traffic snippet; with conversions off,+ * where to turn them on, and what they counted before.+ */+export function ImpactConversions({+ conversions,+ brandId,+}: {+ conversions: ContentConversions;+ brandId: string;+}) {+ const t = useTranslations('contentEditor.editor.impact.conversions');+ const brand = useBrandStore((s) => s.brands.find((b) => b.id === brandId));+ const site = brand ? siteTypeOf(brand) : 'b2b';+ const cards = conversionCards(conversions, site);+ const sources = conversionSources(conversions);+ // Off, what they counted before still shows, under the note.+ const counted = conversions.goals.length > 0;++ 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>++ {!conversions.enabled && (+ <p className="rounded-lg border border-dashed px-3 py-2 text-xs text-muted-foreground">+ {t('off')}{' '}+ <Link+ href={`/dashboard/brands/${brandId}/settings?tab=tracking`}+ className="inline-flex items-center gap-1 font-medium text-primary hover:underline"+ >+ {t('turnOn')}+ <ExternalLink className="h-3 w-3" />+ </Link>+ </p>+ )}+ {(conversions.enabled || counted) && (+ <>+ <div className="grid grid-cols-2 gap-2">+ {cards.map((card) => (+ <div key={card.key} className="rounded-lg border px-3 py-2">+ <p className="text-xs text-muted-foreground">{t(`cards.${card.key}`)}</p>+ <CardValue card={card} />+ </div>+ ))}+ </div>++ {sources.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.conversions')}+ </th>+ </tr>+ </thead>+ <tbody className="tabular-nums">+ {sources.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.conversions)}</td>+ </tr>+ ))}+ </tbody>+ </table>+ )}++ {conversions.journeys.length > 0 && (+ <div className="space-y-1.5">+ <p className="text-xs font-medium text-muted-foreground">{t('journeys')}</p>+ <ol className="space-y-1.5">+ {conversions.journeys.map((journey, i) => (+ <li key={i} className="flex items-start gap-2 text-[11px]">+ <span className="flex min-w-0 flex-1 flex-wrap items-center gap-1">+ <span className="rounded-md bg-muted px-1.5 py-0.5 text-muted-foreground">+ {isNamedPlatform(journey.source)+ ? getPlatformName(journey.source)+ : t('other')}+ </span>+ {journeyPages(journey.pages, conversions.page).map((page, j) => (+ <Fragment key={j}>+ <ChevronRight+ aria-hidden+ className="h-3 w-3 shrink-0 text-muted-foreground/60"+ />+ {page === null ? (+ <span className="text-muted-foreground">…</span>+ ) : page === conversions.page ? (+ <span className="rounded-md border border-foreground px-1.5 py-0.5 font-medium">+ {t('thisPage')}+ </span>+ ) : (+ <span+ title={page}+ className="min-w-0 truncate rounded-md border px-1.5 py-0.5 text-muted-foreground"+ >+ {page}+ </span>+ )}+ </Fragment>+ ))}+ <ChevronRight+ aria-hidden+ className="h-3 w-3 shrink-0 text-muted-foreground/60"+ />+ <span className="rounded-md bg-emerald-50 px-1.5 py-0.5 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300">+ {t(`goals.${journey.goal}`)}+ </span>+ </span>+ <span className="shrink-0 pt-0.5 tabular-nums text-muted-foreground">+ {formatNumber(journey.count)}+ <span className="sr-only">+ {' '}+ {t('journeyCount', { count: journey.count })}+ </span>+ </span>+ </li>+ ))}+ </ol>+ </div>+ )}++ <p className="text-[11px] leading-relaxed text-muted-foreground">{t('legend')}</p>+ </>+ )}+ </section>+ );+}++function CardValue({ card }: { card: ResultCard }) {+ if (card.key !== 'revenue') {+ return <p className="text-lg font-semibold tabular-nums">{formatNumber(card.value)}</p>;+ }+ if (card.value.length === 0) return <p className="text-lg font-semibold">—</p>;+ return (+ <>+ {card.value.map(({ currency, value }) => (+ <p key={currency} className="text-lg font-semibold tabular-nums">+ {money(value, currency)}+ </p>+ ))}+ </>+ );+}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 64dbd5d9a..890012eed 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,14 +3,22 @@ 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 { ContentConversions } from '@/lib/content/conversions';import type { ContentImpact, ContentResults, ResultSource } from '@/lib/content/impact';import { ImpactTab } from './_impact-tab';const getContentImpact = vi.fn();const getContentResults = vi.fn();+const getContentConversions = vi.fn();vi.mock('@/lib/actions/content-drafts', () => ({getContentImpact: (...args: unknown[]) => getContentImpact(...args),getContentResults: (...args: unknown[]) => getContentResults(...args),+ getContentConversions: (...args: unknown[]) => getContentConversions(...args),+}));+// The brand's kind of site, as the store holds it: guessed (B2B) unless a test says.+const store = vi.hoisted(() => ({ brands: [] as { id: string; siteType?: string }[] }));+vi.mock('@/stores/use-brand-store', () => ({+ useBrandStore: (select: (state: typeof store) => unknown) => select(store),}));vi.mock('@/i18n/navigation', () => ({Link: ({ href, children, ...props }: { href: string; children: React.ReactNode }) => (@@ -111,6 +119,8 @@ beforeEach(() => {root = createRoot(container);getContentImpact.mockReset();getContentResults.mockReset().mockResolvedValue(results());+ getContentConversions.mockReset().mockResolvedValue(null);+ store.brands = [];});afterEach(() => {@@ -330,4 +340,120 @@ describe('the Live page tab', () => {expect(getContentResults).not.toHaveBeenCalled();expect(container.textContent).toContain('This draft is a new page, not live yet');});++ describe('conversions from AI journeys through the page (CE-017)', () => {+ const conversions = (over: Partial<ContentConversions> = {}): ContentConversions => ({+ page: '/pricing',+ enabled: true,+ goals: [+ { goal: 'demo', count: 4, units: 0 },+ { goal: 'signup', count: 2, units: 0 },+ { goal: 'newsletter', count: 1, units: 0 },+ ],+ revenue: [],+ sources: [+ { platform: 'perplexity.ai', conversions: 2 },+ { platform: 'chatgpt.com', conversions: 5 },+ ],+ journeys: [+ {+ source: 'chatgpt.com',+ pages: ['/blog/crm-data-hygiene', '/pricing'],+ goal: 'demo',+ count: 4,+ },+ ],+ ...over,+ });+ const section = () =>+ [...container.querySelectorAll('section')].find((el) =>+ el.textContent?.startsWith('Conversions from AI journeys'),+ )!;++ it('shows a B2B site’s signups and demo forms, by source, and its journeys with this page', async () => {+ getContentImpact.mockResolvedValue(impact());+ getContentConversions.mockResolvedValue(conversions());+ await render();+ expect(getContentConversions).toHaveBeenCalledWith('b1', PAGE, 30);+ const cards = [...section().querySelectorAll('.grid > div')].map((el) => el.textContent);+ // Its own goals first, then a card for each other goal it had.+ expect(cards).toEqual(['Signups2', 'Demo forms4', 'Newsletter signups1']);+ const rows = [...section().querySelectorAll('tbody tr')].map((tr) =>+ [...tr.children].map((cell) => cell.textContent),+ );+ expect(rows).toEqual([+ ['ChatGPT', '5'],+ ['Perplexity', '2'],+ ]);+ const journey = section().querySelector('ol li')!;+ expect(journey.textContent).toBe(+ 'ChatGPT/blog/crm-data-hygieneThis pageDemo form4 4 conversions',+ );+ });++ it('keeps this page in view when a long journey is shortened', async () => {+ getContentImpact.mockResolvedValue(impact());+ getContentConversions.mockResolvedValue(+ conversions({+ journeys: [+ {+ source: 'chatgpt.com',+ pages: ['/blog/a', '/blog/b', '/pricing', '/c', '/d', '/e', '/checkout'],+ goal: 'demo',+ count: 1,+ },+ ],+ }),+ );+ await render();+ expect(section().querySelector('ol li')!.textContent).toBe(+ 'ChatGPT/blog/a…This page…/checkoutDemo form1 1 conversion',+ );+ });++ it('shows a shop’s orders, revenue per currency and units sold', async () => {+ store.brands = [{ id: 'b1', siteType: 'ecommerce' }];+ getContentImpact.mockResolvedValue(impact());+ getContentConversions.mockResolvedValue(+ conversions({+ goals: [{ goal: 'order', count: 3, units: 7 }],+ revenue: [{ currency: 'EUR', value: 1290 }],+ journeys: [],+ }),+ );+ await render();+ const cards = [...section().querySelectorAll('.grid > div')].map((el) => el.textContent);+ expect(cards).toEqual(['Orders3', 'Revenue€1,290', 'Units sold7']);+ });++ it('says where to turn them on while the brand has them off, and what they counted before', async () => {+ getContentImpact.mockResolvedValue(impact());+ getContentConversions.mockResolvedValue(conversions({ enabled: false }));+ await render();+ expect(section().textContent).toContain("Conversions aren't on for this brand");+ expect(section().querySelector('a')!.getAttribute('href')).toBe(+ '/dashboard/brands/b1/settings?tab=tracking',+ );+ expect(section().querySelectorAll('.grid > div')).toHaveLength(3);++ // Nothing counted: the note alone.+ getContentConversions.mockResolvedValue(+ conversions({ enabled: false, goals: [], sources: [], journeys: [] }),+ );+ await act(async () => root.unmount());+ root = createRoot(container);+ await render();+ expect(section().querySelector('.grid')).toBeNull();+ expect(section().querySelector('table')).toBeNull();+ });++ it('leaves the rest of the tab when they can’t be read', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ getContentImpact.mockResolvedValue(impact());+ getContentConversions.mockRejectedValue(new Error('boom'));+ await render();+ expect(metric('Citations')).toBe('Citations45+50%');+ expect(container.textContent).not.toContain('Conversions from AI journeys');+ });+ });});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 7261c74aa..fd1397f15 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@@ -6,7 +6,12 @@ import { Check, ExternalLink } from 'lucide-react';import { Link } from '@/i18n/navigation';import { Button } from '@/components/ui/button';import { LoadingDots } from '@/components/ui/loading-dots';-import { getContentImpact, getContentResults } from '@/lib/actions/content-drafts';+import {+ getContentConversions,+ getContentImpact,+ getContentResults,+} from '@/lib/actions/content-drafts';+import type { ContentConversions } from '@/lib/content/conversions';import {DEFAULT_IMPACT_PERIOD,GSC_PAGE_DAYS,@@ -24,6 +29,7 @@ import { formatNumber } from '@/lib/format';import { formatPctChange } from '@/lib/traffic-kpis';import type { VisitChange } from '@/lib/traffic-change';import { cn } from '@/lib/utils';+import { ImpactConversions } from './_impact-conversions';import { ImpactResults } from './_impact-results';import { WorkingDots } from './_working-dots';@@ -32,6 +38,8 @@ interface ImpactRead {period: ImpactPeriod;impact: ContentImpact | null;results: ContentResults | null;+ /** Conversions of AI journeys through the page (CE-017): null when they couldn't be read. */+ conversions: ContentConversions | null;failed: boolean;}@@ -72,13 +80,20 @@ export function ImpactTab({Promise.all([getContentImpact(brandId, pageUrl, period),getContentResults(brandId, pageUrl, period),+ // Its own: a failure leaves the rest of the tab, without this section.+ getContentConversions(brandId, pageUrl, period).catch((err) => {+ console.error('Failed to read the page conversions:', err);+ return null;+ }),])- .then(([impact, results]) => {- if (!cancelled) setRead({ period, impact, results, failed: false });+ .then(([impact, results, conversions]) => {+ if (!cancelled) setRead({ period, impact, results, conversions, failed: false });}).catch((err) => {console.error('Failed to read the page impact:', err);- if (!cancelled) setRead({ period, impact: null, results: null, failed: true });+ if (!cancelled) {+ setRead({ period, impact: null, results: null, conversions: null, failed: true });+ }});return () => {cancelled = true;@@ -150,6 +165,8 @@ export function ImpactTab({<ImpactBodyimpact={impact}results={current.results}+ conversions={current.conversions}+ brandId={brandId}period={period}pageUrl={pageUrl}rebuilding={rebuilding}@@ -164,6 +181,8 @@ export function ImpactTab({function ImpactBody({impact,results,+ conversions,+ brandId,period,pageUrl,rebuilding,@@ -172,6 +191,8 @@ function ImpactBody({}: {impact: ContentImpact;results: ContentResults | null;+ conversions: ContentConversions | null;+ brandId: string;period: ImpactPeriod;pageUrl: string;rebuilding: boolean;@@ -311,6 +332,8 @@ function ImpactBody({{results && <ImpactResults results={results} />}+ {conversions && <ImpactConversions conversions={conversions} brandId={brandId} />}+{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 7026e299c..3f6275d52 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@@ -52,6 +52,7 @@ const readPublishAddress = vi.hoisted(() => vi.fn(async () => 'https://acme.examconst readLiveUrl = vi.hoisted(() => vi.fn(async () => 'https://acme.example.com/pipeline'));vi.mock('@/lib/content/publish-client', () => ({ publishPage, readPublishAddress, readLiveUrl }));const getContentResults = vi.fn();+const getContentConversions = vi.fn();const getDraftSources = vi.fn();const setDraftSourceIncluded = vi.fn();const readAgentRun = vi.fn();@@ -107,6 +108,7 @@ vi.mock('@/lib/actions/content-drafts', () => ({rebuildDraftBrief: (...args: unknown[]) => rebuildDraftBrief(...args),getContentImpact: (...args: unknown[]) => getContentImpact(...args),getContentResults: (...args: unknown[]) => getContentResults(...args),+ getContentConversions: (...args: unknown[]) => getContentConversions(...args),getContentDraft: (...args: unknown[]) => getContentDraft(...args),markContentDraftReady: (...args: unknown[]) => markContentDraftReady(...args),unmarkContentDraftReady: (...args: unknown[]) => unmarkContentDraftReady(...args),@@ -357,6 +359,7 @@ beforeEach(() => {.mockReset().mockResolvedValue({ ok: true, updatedAt: '2026-10-20T10:00:00Z', bodyHash: 'h0' });getContentImpact.mockReset().mockResolvedValue(null);+ getContentConversions.mockReset().mockResolvedValue(null);publishPage.mockReset();readPublishAddress.mockReset().mockResolvedValue('https://acme.example.com/pipeline');getContentResults.mockReset().mockResolvedValue(null);diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex ec98a0925..4c0f2cf35 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -28,6 +28,7 @@ import {} from '@/lib/content/drafts';import { escapeHtml } from '@/lib/content/attachments';import { IMPACT_PERIODS, type ContentImpact, type ContentResults } from '@/lib/content/impact';+import type { ContentConversions } from '@/lib/content/conversions';import {MAX_BODY_HTML_LENGTH,MAX_TITLE_LENGTH,@@ -1121,6 +1122,26 @@ export async function getContentResults(return (data as ContentResults | null) ?? null;}+/**+ * Conversions of AI journeys through the page (CE-017, 00287), for the Live+ * page tab's period: from the AI Traffic snippet with conversions on.+ */+export async function getContentConversions(+ brandId: string,+ page: string,+ days: number,+): Promise<ContentConversions | null> {+ if (!impactArgsValid(brandId, page, days)) throw new Error('invalid');+ const supabase = await createClient();+ const { data, error } = await supabase.rpc('content_page_conversions', {+ p_brand_id: brandId,+ p_page: page,+ p_days: days,+ });+ if (error) throw new Error(error.message);+ return (data as ContentConversions | 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 (diff --git a/web/src/lib/content/conversions.test.ts b/web/src/lib/content/conversions.test.tsnew file mode 100644index 000000000..b68b028c2--- /dev/null+++ b/web/src/lib/content/conversions.test.ts@@ -0,0 +1,101 @@+import { describe, expect, it } from 'vitest';+import {+ conversionCards,+ conversionSources,+ journeyPages,+ type ContentConversions,+} from './conversions';++const read = (over: Partial<ContentConversions> = {}): ContentConversions => ({+ page: '/pricing',+ enabled: true,+ goals: [],+ revenue: [],+ sources: [],+ journeys: [],+ ...over,+});++describe('conversionCards', () => {+ it('shows each kind of site its own goals, at 0 when there are none', () => {+ expect(conversionCards(read(), 'b2b')).toEqual([+ { key: 'signup', value: 0 },+ { key: 'demo', value: 0 },+ ]);+ expect(conversionCards(read(), 'b2c').map((card) => card.key)).toEqual([+ 'booking',+ 'revenue',+ 'newsletter',+ ]);+ });++ it('reads a shop’s units from its orders, and gives each goal its site leaves out a card of its own', () => {+ const conversions = read({+ goals: [+ { goal: 'order', count: 3, units: 7 },+ { goal: 'signup', count: 2, units: 0 },+ { goal: 'custom', count: 1, units: 0 },+ ],+ revenue: [{ currency: 'USD', value: 120 }],+ });+ expect(conversionCards(conversions, 'ecommerce')).toEqual([+ { key: 'order', value: 3 },+ { key: 'revenue', value: [{ currency: 'USD', value: 120 }] },+ { key: 'units', value: 7 },+ // A shop's newsletter form counts as a signup: it shows as one.+ { key: 'signup', value: 2 },+ { key: 'custom', value: 1 },+ ]);+ });+});++describe('conversionSources', () => {+ it('names each source, ChatGPT’s old host as ChatGPT, keys it can’t name as Other, last', () => {+ expect(+ conversionSources(+ read({+ sources: [+ { platform: 'unknown-ai.example', conversions: 9 },+ { platform: 'chatgpt.com', conversions: 2 },+ { platform: 'chat.openai.com', conversions: 1 },+ { platform: 'perplexity.ai', conversions: 4 },+ ],+ }),+ ),+ ).toEqual([+ { name: 'Perplexity', conversions: 4 },+ { name: 'ChatGPT', conversions: 3 },+ { name: null, conversions: 9 },+ ]);+ });+});++describe('journeyPages', () => {+ it('keeps up to five pages, or the first, a gap and the last three', () => {+ expect(journeyPages(['/a', '/b'])).toEqual(['/a', '/b']);+ expect(journeyPages(['/a', '/b', '/c', '/d', '/e', '/f'])).toEqual([+ '/a',+ null,+ '/d',+ '/e',+ '/f',+ ]);+ });++ it('keeps the page the tab is about in view when it would fall in the gap', () => {+ const pages = ['/a', '/b', '/pricing', '/c', '/d', '/e', '/f'];+ expect(journeyPages(pages, '/pricing')).toEqual(['/a', null, '/pricing', null, '/f']);+ // Shown already, or not in the journey: as without it.+ expect(journeyPages(pages, '/a')).toEqual(['/a', null, '/d', '/e', '/f']);+ expect(journeyPages(pages, '/e')).toEqual(['/a', null, '/d', '/e', '/f']);+ expect(journeyPages(pages, '/other')).toEqual(['/a', null, '/d', '/e', '/f']);+ expect(journeyPages(['/a', '/pricing'], '/pricing')).toEqual(['/a', '/pricing']);+ // Right after the first page: no gap between them.+ expect(journeyPages(['/a', '/pricing', '/b', '/c', '/d', '/e', '/f'], '/pricing')).toEqual([+ '/a',+ '/pricing',+ null,+ '/f',+ ]);+ });+});diff --git a/web/src/lib/content/conversions.ts b/web/src/lib/content/conversions.tsnew file mode 100644index 000000000..488f9dd6a--- /dev/null+++ b/web/src/lib/content/conversions.ts@@ -0,0 +1,104 @@+import { getPlatformName, isNamedPlatform } from '@/lib/traffic-platforms';+import type { SiteType } from './page-types';++/**+ * Conversions of AI journeys through a page (CE-017), as+ * content_page_conversions (00287) reads them for the Live page tab's+ * window: from the AI Traffic snippet with conversions on (00286), credited+ * to the AI source of the journey's first visit.+ */++/** A conversion's goal (server traffic-events.js CONVERSION_GOALS). */+export type ConversionGoal = 'signup' | 'demo' | 'order' | 'booking' | 'newsletter' | 'custom';++export interface ContentConversions {+ /** The page's key, as its journeys name it (lower(normalize_page_path)). */+ page: string;+ /** The brand has conversions on. */+ enabled: boolean;+ goals: { goal: ConversionGoal; count: number; units: number }[];+ /** Orders' and bookings' value per currency: one without a currency isn't summed. */+ revenue: { currency: string; value: number }[];+ /** Per AI source the journey started from. */+ sources: { platform: string; conversions: number }[];+ /** The five most frequent: source, pages in order (page keys), goal. */+ journeys: { source: string; pages: string[]; goal: ConversionGoal; count: number }[];+}++/** What a result card shows: a goal's count, the revenue, or the units ordered. */+export type ResultKey = ConversionGoal | 'revenue' | 'units';++/**+ * What each kind of site counts (spec §7 point 26): a B2B site its signups+ * and demo forms (its revenue comes with CE-024), a shop its orders, revenue+ * and units, a B2C site its bookings, revenue and newsletter signups.+ */+export const SITE_RESULTS: Record<SiteType, readonly ResultKey[]> = {+ b2b: ['signup', 'demo'],+ ecommerce: ['order', 'revenue', 'units'],+ b2c: ['booking', 'revenue', 'newsletter'],+};++export type ResultCard =+ | { key: ConversionGoal | 'units'; value: number }+ | { key: 'revenue'; value: { currency: string; value: number }[] };++/**+ * The cards for a site: its own goals, revenue and units, always, at 0 when+ * there are none; then a card for each other goal it had, the most first (a+ * shop's newsletter form counts as a signup, and shows as one).+ */+export function conversionCards(conversions: ContentConversions, site: SiteType): ResultCard[] {+ const count = (goal: ConversionGoal) =>+ conversions.goals.find((g) => g.goal === goal)?.count ?? 0;+ const keys = SITE_RESULTS[site];+ const cards: ResultCard[] = keys.map((key) => {+ if (key === 'revenue') return { key, value: conversions.revenue };+ if (key === 'units') {+ return { key, value: conversions.goals.find((g) => g.goal === 'order')?.units ?? 0 };+ }+ return { key, value: count(key) };+ });+ const others: ResultCard[] = conversions.goals+ .filter((g) => g.count > 0 && !(keys as readonly string[]).includes(g.goal))+ .map((g) => ({ key: g.goal, value: g.count }));+ return [...cards, ...others];+}++/**+ * The by-source rows: one per platform name (ChatGPT's old hosts are+ * ChatGPT), keys the page can't name folded into Other, last; the most+ * conversions first.+ */+export function conversionSources(+ conversions: ContentConversions,+): { name: string | null; conversions: number }[] {+ const byName = new Map<string | null, number>();+ for (const { platform, conversions: n } of conversions.sources) {+ const name = isNamedPlatform(platform) ? getPlatformName(platform) : null;+ byName.set(name, (byName.get(name) ?? 0) + n);+ }+ return [...byName]+ .map(([name, n]) => ({ name, conversions: n }))+ .sort(+ (a, b) =>+ Number(a.name === null) - Number(b.name === null) ||+ b.conversions - a.conversions ||+ (a.name ?? '').localeCompare(b.name ?? ''),+ );+}++/**+ * A journey's pages as the tab shows them: all of them up to five, or the+ * first, a gap and the last three; with `keep` (the page the tab is about)+ * only in the gap, the first, a gap, that page, a gap and the last, so the+ * page stays in view.+ */+export function journeyPages(pages: string[], keep?: string): (string | null)[] {+ if (pages.length <= 5) return pages;+ const shown = [pages[0], null, ...pages.slice(-3)];+ if (keep === undefined || shown.includes(keep) || !pages.includes(keep)) return shown;+ // A gap only where pages are left out: none before the page right after the first.+ const at = pages.indexOf(keep);+ return [pages[0], ...(at > 1 ? [null] : []), keep, null, pages[pages.length - 1]];+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex df2992228..a17a8f86c 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -4738,6 +4738,10 @@ export type Database = {Args: { p_before: string; p_limit: number }Returns: number}+ content_page_conversions: {+ Args: { p_brand_id: string; p_days: number; p_page: string }+ Returns: Json+ }content_page_impact: {Args: { p_brand_id: string; p_days: number; p_page: string }Returns: Json