Skip to content

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.

feat(content): add the goals AI visitors reached and the top journey to the Content plan's AI results strip (CE-017, part 4b) (#1531)

Cihan4b05f7d25bd2
diff --git a/supabase/migrations/00288_brand_ai_conversions.sql b/supabase/migrations/00288_brand_ai_conversions.sql
new file mode 100644
index 000000000..6a1fb1659
--- /dev/null
+++ b/supabase/migrations/00288_brand_ai_conversions.sql
@@ -0,0 +1,123 @@
+-- ============================================================================
+-- 00288: the brand's conversions from AI journeys, for the Content plan's strip
+-- ============================================================================
+-- The Content plan's AI results strip (spec v2 §4 point 8, CE-014) says what
+-- AI visits brought in: "48 signups · 20 demo forms · 10 orders", and the top
+-- journey. With conversions on (00286), the AI Traffic snippet's journeys
+-- give it the goals (CE-017), beside Google Analytics' key events.
+--
+-- brand_ai_conversions(brand, days) returns one jsonb over the last 7, 30 or
+-- 90 whole UTC days, ending yesterday, as content_plan_insights (00226):
+-- * enabled: whether the brand has conversions on;
+-- * goals: per goal, its conversions, the most first;
+-- * journey: the most frequent journey to a conversion among the period's
+-- latest 2,000 (the latest first among as many), its source, pages and
+-- goal, as content_page_conversions (00287) builds them (the latest 100
+-- pageviews before the conversion), and how many; null without one. The
+-- bounds keep a big brand's 90 days, or a visitor id with a long
+-- history, from holding the Plan page up: the goals still count every
+-- conversion.
+--
+-- Security definer with an organization check, as content_plan_insights.
+
+create or replace function public.brand_ai_conversions(
+ p_brand_id uuid,
+ p_days integer default 30
+)
+returns jsonb
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+set plan_cache_mode to 'force_custom_plan'
+as $$
+declare
+ v_last 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 not in (7, 30, 90) then
+ raise exception 'p_days must be 7, 30 or 90';
+ end if;
+
+ v_from := (v_last - p_days + 1)::timestamp at time zone 'utc';
+ v_until := (v_last + 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
+ ),
+ -- The latest 2,000's paths (the goals take all): the landing page, the
+ -- latest 100 pageviews before the conversion, from a day before its first
+ -- AI visit (first_at is clamped per event, within the server's clock
+ -- allowance), the page it converted on; by the keys stored with each
+ -- event (00286).
+ 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 conversions order by occurred_at desc limit 2000) t
+ )
+ select jsonb_build_object(
+ '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) order by g.n desc, g.goal)
+ from (select goal, count(*)::bigint as n from conversions group by goal) g
+ ), '[]'::jsonb),
+ 'journey', (
+ select jsonb_build_object('source', j.first_source, 'pages', to_jsonb(j.pages),
+ 'goal', j.goal, 'count', j.n)
+ from (
+ select first_source, pages, goal, count(*)::bigint as n
+ from paths
+ group by first_source, pages, goal
+ order by count(*) desc, max(occurred_at) desc, first_source, goal
+ limit 1
+ ) j
+ )
+ ) into v_result;
+ return v_result;
+end;
+$$;
+
+revoke all on function public.brand_ai_conversions(uuid, integer) from public, anon;
+grant execute on function public.brand_ai_conversions(uuid, integer)
+ to authenticated, service_role;
+
+comment on function public.brand_ai_conversions(uuid, integer) is
+ 'Content plan (CE-017, 00288): the brand''s conversions from AI journeys over the last 7, 30 or 90 whole UTC days (ending yesterday), from the AI Traffic snippet (ai_traffic_events, 00286): per goal, and the most frequent journey (source, pages, goal, count). Security definer with an organization check.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 834846bdb..edd276cca 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -40533,6 +40533,133 @@ grant execute on function public.content_page_conversions(uuid, text, integer)
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/00288_brand_ai_conversions.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00288: the brand's conversions from AI journeys, for the Content plan's strip
+-- ============================================================================
+-- The Content plan's AI results strip (spec v2 §4 point 8, CE-014) says what
+-- AI visits brought in: "48 signups · 20 demo forms · 10 orders", and the top
+-- journey. With conversions on (00286), the AI Traffic snippet's journeys
+-- give it the goals (CE-017), beside Google Analytics' key events.
+--
+-- brand_ai_conversions(brand, days) returns one jsonb over the last 7, 30 or
+-- 90 whole UTC days, ending yesterday, as content_plan_insights (00226):
+-- * enabled: whether the brand has conversions on;
+-- * goals: per goal, its conversions, the most first;
+-- * journey: the most frequent journey to a conversion among the period's
+-- latest 2,000 (the latest first among as many), its source, pages and
+-- goal, as content_page_conversions (00287) builds them (the latest 100
+-- pageviews before the conversion), and how many; null without one. The
+-- bounds keep a big brand's 90 days, or a visitor id with a long
+-- history, from holding the Plan page up: the goals still count every
+-- conversion.
+--
+-- Security definer with an organization check, as content_plan_insights.
+
+create or replace function public.brand_ai_conversions(
+ p_brand_id uuid,
+ p_days integer default 30
+)
+returns jsonb
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+set plan_cache_mode to 'force_custom_plan'
+as $$
+declare
+ v_last 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 not in (7, 30, 90) then
+ raise exception 'p_days must be 7, 30 or 90';
+ end if;
+
+ v_from := (v_last - p_days + 1)::timestamp at time zone 'utc';
+ v_until := (v_last + 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
+ ),
+ -- The latest 2,000's paths (the goals take all): the landing page, the
+ -- latest 100 pageviews before the conversion, from a day before its first
+ -- AI visit (first_at is clamped per event, within the server's clock
+ -- allowance), the page it converted on; by the keys stored with each
+ -- event (00286).
+ 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 conversions order by occurred_at desc limit 2000) t
+ )
+ select jsonb_build_object(
+ '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) order by g.n desc, g.goal)
+ from (select goal, count(*)::bigint as n from conversions group by goal) g
+ ), '[]'::jsonb),
+ 'journey', (
+ select jsonb_build_object('source', j.first_source, 'pages', to_jsonb(j.pages),
+ 'goal', j.goal, 'count', j.n)
+ from (
+ select first_source, pages, goal, count(*)::bigint as n
+ from paths
+ group by first_source, pages, goal
+ order by count(*) desc, max(occurred_at) desc, first_source, goal
+ limit 1
+ ) j
+ )
+ ) into v_result;
+ return v_result;
+end;
+$$;
+
+revoke all on function public.brand_ai_conversions(uuid, integer) from public, anon;
+grant execute on function public.brand_ai_conversions(uuid, integer)
+ to authenticated, service_role;
+
+comment on function public.brand_ai_conversions(uuid, integer) is
+ 'Content plan (CE-017, 00288): the brand''s conversions from AI journeys over the last 7, 30 or 90 whole UTC days (ending yesterday), from the AI Traffic snippet (ai_traffic_events, 00286): per goal, and the most frequent journey (source, pages, goal, count). Security definer with an organization check.';
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00289_content_draft_restored_at.sql
-- ─────────────────────────────────────────────────────────────────────────
diff --git a/web/messages/en.json b/web/messages/en.json
index 4eaef4c5d..34d3c1d59 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3239,7 +3239,27 @@
"keyEvents": "{count, plural, one {{value} key event} other {{value} key events}}",
"orders": "{count, plural, one {{value} order} other {{value} orders}}",
"revenue": "{value} revenue",
- "needsAnalytics": "<link>Connect Google Analytics</link> to see what they did next."
+ "needsAnalytics": "<link>Connect Google Analytics</link> to see what they did next.",
+ "needsAnalyticsMore": "<link>Connect Google Analytics</link> for key events and revenue.",
+ "goals": {
+ "signup": "{count, plural, one {{value} signup} other {{value} signups}}",
+ "demo": "{count, plural, one {{value} demo form} other {{value} demo forms}}",
+ "order": "{count, plural, one {{value} order from a journey} other {{value} orders from journeys}}",
+ "booking": "{count, plural, one {{value} booking} other {{value} bookings}}",
+ "newsletter": "{count, plural, one {{value} newsletter signup} other {{value} newsletter signups}}",
+ "custom": "{count, plural, one {{value} other conversion} other {{value} other conversions}}"
+ },
+ "topJourney": "Top journey:",
+ "journeyCount": "{count, plural, one {{value} conversion} other {{value} conversions}}",
+ "otherSource": "Other",
+ "journeyGoals": {
+ "signup": "Signup",
+ "demo": "Demo form",
+ "order": "Purchase",
+ "booking": "Booking",
+ "newsletter": "Newsletter",
+ "custom": "Conversion"
+ }
},
"mix": {
"title": "What AI cites in your topics",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_plan-insights.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_plan-insights.tsx
index 3e4e1031c..562dd682d 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_plan-insights.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_plan-insights.tsx
@@ -1,21 +1,36 @@
'use client';
-import { useId, useState } from 'react';
+import { Fragment, useId, useState } from 'react';
import { useTranslations } from 'next-intl';
-import { ChevronDown, Sparkles, X } from 'lucide-react';
+import { ChevronDown, ChevronRight, Sparkles, X } from 'lucide-react';
import { Link } from '@/i18n/navigation';
+import { journeyPages, type PlanConversions } from '@/lib/content/conversions';
import type { PageType } from '@/lib/content/drafts';
import type { MixRow, PlanResults } from '@/lib/content/plan-mix';
import type { PlanPeriod } from '@/lib/content/plan';
import { formatNumber } from '@/lib/format';
+import { getPlatformName, isNamedPlatform } from '@/lib/traffic-platforms';
import { cn } from '@/lib/utils';
+/** Goals on the strip: the four with the most conversions. */
+const STRIP_GOALS = 4;
+
/**
* The AI results strip (CE-014): what visitors from AI assistants did on the
* site in the period. Key events need Google Analytics; orders and revenue
- * show when its property reports purchases.
+ * show when its property reports purchases. With conversions on (CE-017),
+ * the goals the AI Traffic snippet followed them to, and the top journey.
*/
-export function AiResultsStrip({ results, days }: { results: PlanResults; days: PlanPeriod }) {
+export function AiResultsStrip({
+ results,
+ conversions = null,
+ days,
+}: {
+ results: PlanResults;
+ /** The snippet's conversions, or null when they couldn't be read. */
+ conversions?: PlanConversions | null;
+ days: PlanPeriod;
+}) {
const t = useTranslations('contentEditor.plan.results');
const parts = [t('visits', { count: results.visits, value: formatNumber(results.visits) })];
if (results.analytics) {
@@ -29,6 +44,11 @@ export function AiResultsStrip({ results, days }: { results: PlanResults; days:
);
}
}
+ const goals = conversions?.goals.slice(0, STRIP_GOALS) ?? [];
+ for (const { goal, count } of goals) {
+ parts.push(t(`goals.${goal}`, { count, value: formatNumber(count) }));
+ }
+ const journey = conversions?.journey ?? null;
return (
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 rounded-xl border bg-muted/40 px-4 py-2.5 text-sm">
<Sparkles aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />
@@ -36,7 +56,7 @@ export function AiResultsStrip({ results, days }: { results: PlanResults; days:
<span className="font-medium">{parts.join(' · ')}</span>
{!results.analytics && (
<span className="text-muted-foreground">
- {t.rich('needsAnalytics', {
+ {t.rich(goals.length > 0 ? 'needsAnalyticsMore' : 'needsAnalytics', {
link: (chunks) => (
<Link
href="/dashboard/traffic"
@@ -48,6 +68,33 @@ export function AiResultsStrip({ results, days }: { results: PlanResults; days:
})}
</span>
)}
+ {journey && (
+ <p className="flex w-full min-w-0 flex-wrap items-center gap-1 text-xs text-muted-foreground">
+ <span>{t('topJourney')}</span>
+ <span className="rounded-md bg-muted px-1.5 py-0.5">
+ {isNamedPlatform(journey.source) ? getPlatformName(journey.source) : t('otherSource')}
+ </span>
+ {journeyPages(journey.pages).map((page, i) => (
+ <Fragment key={i}>
+ <ChevronRight aria-hidden className="h-3 w-3 shrink-0 text-muted-foreground/60" />
+ {page === null ? (
+ <span>…</span>
+ ) : (
+ <span title={page} className="min-w-0 truncate rounded-md border px-1.5 py-0.5">
+ {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(`journeyGoals.${journey.goal}`)}
+ </span>
+ <span>
+ · {t('journeyCount', { count: journey.count, value: formatNumber(journey.count) })}
+ </span>
+ </p>
+ )}
</div>
);
}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx
index 5d0cdedd3..1623c1023 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx
@@ -420,6 +420,50 @@ describe('the Content plan', () => {
expect(section().textContent).not.toContain('Priority list filtered to');
});
+ it('adds the four goals the snippet followed AI visitors to most, and the top journey (CE-017)', async () => {
+ getContentPlanInsights.mockResolvedValue({
+ ...INSIGHTS,
+ conversions: {
+ enabled: true,
+ goals: [
+ { goal: 'signup', count: 48 },
+ { goal: 'demo', count: 20 },
+ { goal: 'order', count: 10 },
+ { goal: 'newsletter', count: 3 },
+ { goal: 'custom', count: 1 },
+ ],
+ // A long journey: the first page, a gap and the last three.
+ journey: {
+ source: 'chatgpt.com',
+ pages: ['/blog/crm-data-hygiene', '/a', '/b', '/c', '/d', '/pricing'],
+ goal: 'demo',
+ count: 4,
+ },
+ },
+ });
+ await renderPage();
+ expect(container.textContent).toContain(
+ '1,240 visits · 48 key events · 12 orders · 3,210 revenue · 48 signups · 20 demo forms · 10 orders from journeys · 3 newsletter signups',
+ );
+ expect(container.textContent).not.toContain('other conversion');
+ expect(container.textContent).toContain(
+ 'Top journey:ChatGPT/blog/crm-data-hygiene…/c/d/pricingDemo form· 4 conversions',
+ );
+ });
+
+ it('asks for Google Analytics beside the goals, without a journey line when there’s none', async () => {
+ getContentPlanInsights.mockResolvedValue({
+ ...INSIGHTS,
+ results: { ...INSIGHTS.results, analytics: false, purchases: false },
+ conversions: { enabled: true, goals: [{ goal: 'signup', count: 1 }], journey: null },
+ });
+ await renderPage();
+ expect(container.textContent).toContain(
+ '1,240 visits · 1 signupConnect Google Analytics for key events and revenue.',
+ );
+ expect(container.textContent).not.toContain('Top journey');
+ });
+
it('asks for Google Analytics to show what AI visitors did', async () => {
getContentPlanInsights.mockResolvedValue({
...INSIGHTS,
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx
index 88f9f9346..8262e130a 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx
@@ -373,7 +373,13 @@ export default function ContentPlanPage() {
</div>
) : (
<>
- {shown && current && <AiResultsStrip results={shown.results} days={current.days} />}
+ {shown && current && (
+ <AiResultsStrip
+ results={shown.results}
+ conversions={shown.conversions}
+ days={current.days}
+ />
+ )}
{mix && (
<PageTypeMix
rows={mix.rows}
diff --git a/web/src/lib/actions/content-plan.test.ts b/web/src/lib/actions/content-plan.test.ts
index eebd00baa..cbceca611 100644
--- a/web/src/lib/actions/content-plan.test.ts
+++ b/web/src/lib/actions/content-plan.test.ts
@@ -10,6 +10,8 @@ const O9 = '99999999-9999-9999-9999-999999999999';
let reads: Record<string, unknown>;
let rpcResult: unknown;
+/** A function's own answer, where a test gives one (else rpcResult). */
+let rpcByName: Record<string, { data?: unknown; error?: { message: string } }>;
let rpcCalls: [string, unknown][];
let filters: [string, string, string, unknown][];
/** One row a .maybeSingle() read or write returns, by table (null: none). */
@@ -21,7 +23,9 @@ vi.mock('@/lib/supabase/server', () => ({
auth: { getUser: async () => ({ data: { user: { id: 'u1' } } }) },
rpc: async (name: string, args: unknown) => (
rpcCalls.push([name, args]),
- { data: rpcResult, error: null }
+ name in rpcByName
+ ? { data: rpcByName[name].data ?? null, error: rpcByName[name].error ?? null }
+ : { data: rpcResult, error: null }
),
from: (table: string) => {
// A read by id (the hidden opportunities) answers from `${table}#id`.
@@ -78,6 +82,8 @@ const {
beforeEach(() => {
reads = {};
rpcResult = { days: 30, pages: [] };
+ // Read the insights alone: the snippet's conversions as none.
+ rpcByName = { brand_ai_conversions: { data: null } };
rpcCalls = [];
filters = [];
single = {};
@@ -339,7 +345,13 @@ describe('getPlanPriorities', () => {
});
describe('getContentPlanInsights', () => {
- it('reads what AI cites and what AI visits brought in', async () => {
+ it('reads what AI cites and what AI visits brought in, with the snippet’s conversions', async () => {
+ const conversions = {
+ enabled: true,
+ goals: [{ goal: 'demo', count: 2 }],
+ journey: { source: 'chatgpt.com', pages: ['/blog', '/pricing'], goal: 'demo', count: 2 },
+ };
+ rpcByName = { brand_ai_conversions: { data: conversions } };
rpcResult = {
days: 30,
totalCitations: 120,
@@ -359,8 +371,30 @@ describe('getContentPlanInsights', () => {
analytics: true,
purchases: false,
},
+ conversions,
});
- expect(rpcCalls).toEqual([['content_plan_insights', { p_brand_id: BRAND, p_days: 30 }]]);
+ expect(rpcCalls).toEqual([
+ ['content_plan_insights', { p_brand_id: BRAND, p_days: 30 }],
+ ['brand_ai_conversions', { p_brand_id: BRAND, p_days: 30 }],
+ ]);
+ });
+
+ it('reads the rest when the conversions can’t be read (a database before 00288)', async () => {
+ const logged = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ rpcByName = {
+ brand_ai_conversions: {
+ error: { message: 'function brand_ai_conversions does not exist' },
+ },
+ };
+ rpcResult = { totalCitations: 3, citations: [], results: { visits: 4 } };
+ const read = (await getContentPlanInsights(BRAND, 30))!;
+ expect(read.conversions).toBeNull();
+ expect(read.results.visits).toBe(4);
+ expect(logged).toHaveBeenCalled();
+ } finally {
+ logged.mockRestore();
+ }
});
it('counts Analytics as connected only as AI Traffic does: connected and synced', async () => {
diff --git a/web/src/lib/actions/content-plan.ts b/web/src/lib/actions/content-plan.ts
index f973328bd..23b5a03a0 100644
--- a/web/src/lib/actions/content-plan.ts
+++ b/web/src/lib/actions/content-plan.ts
@@ -7,6 +7,7 @@ import { updateOpportunityStatus } from '@/lib/actions/content';
import { readAssignees } from '@/lib/action-center/assignees';
import { memberLabel } from '@/lib/action-center/display';
import type { DraftMethod } from '@/lib/content/drafts';
+import type { PlanConversions } from '@/lib/content/conversions';
import type { CitedAddress, PlanResults } from '@/lib/content/plan-mix';
import {
PLAN_PERIODS,
@@ -374,16 +375,32 @@ export async function showPlanRow(brandId: string, rowKey: string): Promise<void
export async function getContentPlanInsights(
brandId: string,
days: PlanPeriod,
-): Promise<{ citations: CitedAddress[]; totalCitations: number; results: PlanResults } | null> {
+): Promise<{
+ citations: CitedAddress[];
+ totalCitations: number;
+ results: PlanResults;
+ /** The snippet's conversions (CE-017, 00288): null when they couldn't be read. */
+ conversions: PlanConversions | null;
+} | null> {
if (!planInput.safeParse({ brandId, days }).success) throw new Error('invalid');
const supabase = await createClient();
- const [{ data, error }, gaConnected] = await Promise.all([
+ const [{ data, error }, gaConnected, conversions] = await Promise.all([
supabase.rpc('content_plan_insights', { p_brand_id: brandId, p_days: days }),
getSuggestionSourceStates(brandId).then(
(states) => googleSourceStatus(states.ga) === 'connected',
// The property alone decides then, as before.
() => null,
),
+ // Its own read: the strip goes on without it.
+ Promise.resolve(supabase.rpc('brand_ai_conversions', { p_brand_id: brandId, p_days: days }))
+ .then(({ data: read, error: readError }) => {
+ if (readError) throw new Error(readError.message);
+ return (read as PlanConversions | null) ?? null;
+ })
+ .catch((err) => {
+ console.error('Failed to read the conversions from AI journeys:', err);
+ return null;
+ }),
]);
if (error) throw new Error(error.message);
if (!data) return null;
@@ -409,5 +426,6 @@ export async function getContentPlanInsights(
analytics: Boolean(r.analytics) && gaConnected !== false,
purchases: Boolean(r.purchases),
},
+ conversions,
};
}
diff --git a/web/src/lib/content/conversions.ts b/web/src/lib/content/conversions.ts
index 488f9dd6a..028dd1dd9 100644
--- a/web/src/lib/content/conversions.ts
+++ b/web/src/lib/content/conversions.ts
@@ -25,6 +25,19 @@ export interface ContentConversions {
journeys: { source: string; pages: string[]; goal: ConversionGoal; count: number }[];
}
+/**
+ * The brand's conversions from AI journeys in the Plan's period
+ * (brand_ai_conversions, 00288), for its AI results strip.
+ */
+export interface PlanConversions {
+ /** The brand has conversions on. */
+ enabled: boolean;
+ /** Per goal, the most first. */
+ goals: { goal: ConversionGoal; count: number }[];
+ /** The most frequent journey to a conversion, or null. */
+ journey: { source: string; pages: string[]; goal: ConversionGoal; count: number } | null;
+}
+
/** What a result card shows: a goal's count, the revenue, or the units ordered. */
export type ResultKey = ConversionGoal | 'revenue' | 'units';
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index a17a8f86c..e4771804e 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -4415,6 +4415,10 @@ export type Database = {
Returns: Json
}
apply_prompt_locations: { Args: { p_updates: Json }; Returns: number }
+ brand_ai_conversions: {
+ Args: { p_brand_id: string; p_days?: number }
+ Returns: Json
+ }
citation_competitor_sources: {
Args: {
p_brand_domains: string[]