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): show what AI cites and what AI visits bring in on the Content plan (#1309)

Cihanf603702f7722
diff --git a/supabase/migrations/00221_content_plan_insights.sql b/supabase/migrations/00221_content_plan_insights.sql
new file mode 100644
index 000000000..7abee579d
--- /dev/null
+++ b/supabase/migrations/00221_content_plan_insights.sql
@@ -0,0 +1,400 @@
+-- ============================================================================
+-- 00221: what AI cites, and what AI visits bring in, for the Content plan
+-- ============================================================================
+-- The Plan (Content Editor CE-014, spec v2 §4) shows, under its cards:
+--
+-- * "What AI cites in your topics": one row per page type with the share
+-- of AI citations in the brand's tracked answers going to that type of
+-- page, and the brand's own mix. Page types are read from the address
+-- and title (lib/content/page-types.ts), so this returns the addresses
+-- over the last p_days whole UTC days to yesterday (as the Plan's pages,
+-- 00220), from the nightly rollup (citation_url_daily, 00118), ChatGPT
+-- Shopping left out: every one of the brand's own (at most a few
+-- thousand, so its mix is whole), and the 1,000 others cited most; with
+-- the total, so the share the list covers is known;
+-- * the AI results strip: what AI-referred visitors did on the whole site
+-- over the same days, as the Impact tab's results (00210) read one page:
+-- visits by ai_traffic_merged's rule (00176), and Google Analytics' AI
+-- key events, purchases and revenue; whether a property is set (the app
+-- checks the connection too), and whether it reported any purchase.
+--
+-- The Plan's period is now 7, 30 or 90 days (a quarter), so
+-- content_plan_pages (00220) is redefined to take 90 as well, and to say
+-- since when the brand is tracked: few brands have 180 days of history, so
+-- at 90 days the earlier window is often only partly tracked, or not at all.
+--
+-- Security definer with an organization check, as 00209–00220.
+
+create or replace function public.content_plan_insights(
+ p_brand_id uuid,
+ p_days integer default 30
+)
+returns jsonb
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+as $$
+declare
+ -- Whole days to yesterday, as the Plan's pages (00220).
+ v_last 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 not in (7, 30, 90) then
+ raise exception 'p_days must be 7, 30 or 90';
+ end if;
+
+ v_day := v_last - p_days + 1;
+ v_from := v_day::timestamp at time zone 'utc';
+ v_until := (v_last + 1)::timestamp at time zone 'utc';
+
+ with own_domains as (
+ select lower(regexp_replace(bd.domain, '^www\.', '')) as domain
+ from public.brand_domains bd
+ where bd.brand_id = p_brand_id
+ ),
+ cited as materialized (
+ select d.url_id, sum(d.citations)::bigint as citations
+ from public.citation_url_daily d
+ where d.brand_id = p_brand_id
+ and d.day >= v_day
+ and d.day <= v_last
+ and d.platform is distinct from 'chatgpt-shopping'
+ group by d.url_id
+ ),
+ addresses as (
+ select c.url_id, c.citations, cu.url, cu.title, cu.domain in (select domain from own_domains) as own
+ from cited c
+ join public.citation_urls cu on cu.id = c.url_id
+ ),
+ top_urls as (
+ select a.* from addresses a where a.own
+ union all
+ (
+ select a.* from addresses a
+ where not a.own
+ order by a.citations desc, a.url_id
+ limit 1000
+ )
+ ),
+ 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 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
+ union all
+ select coalesce(sum(g.sessions), 0)::bigint
+ from public.ga_ai_traffic_stats g
+ where g.brand_id = p_brand_id
+ and g.sessions > 0
+ and g.date >= v_day
+ and g.date <= v_last
+ and not exists (select 1 from snippet_days s where s.day = g.date)
+ ),
+ analytics as (
+ select
+ coalesce(sum(g.key_events), 0)::bigint as key_events,
+ coalesce(sum(g.transactions), 0)::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.date >= v_day
+ and g.date <= v_last
+ )
+ select jsonb_build_object(
+ 'days', p_days,
+ 'totalCitations', (select coalesce(sum(c.citations), 0) from cited c),
+ 'citations', coalesce((
+ select jsonb_agg(
+ jsonb_build_object(
+ 'url', t.url,
+ 'title', t.title,
+ 'own', t.own,
+ 'citations', t.citations
+ )
+ order by t.citations desc, t.url
+ )
+ from top_urls t
+ ), '[]'::jsonb),
+ 'results', (
+ select jsonb_build_object(
+ 'visits', (select coalesce(sum(v.n), 0) from visits v),
+ 'keyEvents', a.key_events,
+ 'transactions', a.transactions,
+ 'revenue', a.revenue,
+ 'analytics', (
+ select nullif(b.ga_property_id, '') is not null
+ from public.brands b where b.id = p_brand_id
+ ),
+ 'purchases', a.transactions > 0 or a.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
+ and (c.transactions > 0 or c.purchase_revenue > 0)
+ )
+ )
+ from analytics a
+ )
+ )
+ into v_result;
+
+ return v_result;
+end;
+$$;
+
+revoke all on function public.content_plan_insights(uuid, integer) from public, anon;
+grant execute on function public.content_plan_insights(uuid, integer) to authenticated, service_role;
+
+comment on function public.content_plan_insights(uuid, integer) is
+ 'Content Editor (CE-014): the addresses AI answers cite for the brand over the last N (7, 30 or 90) whole UTC days to yesterday (from citation_url_daily): every own page and the 1,000 others cited most, with the total; and what AI-referred visitors did on the site: visits, Google Analytics AI key events, purchases and revenue. Security definer with an organization check.';
+
+-- ─── content_plan_pages (00220), taking 90 days too ─────────────────────────
+-- As 00220, with 90 days and the windows' tracking: 'prevFrom' and
+-- 'trackedSince' tell the Plan when the earlier window isn't fully tracked.
+
+create or replace function public.content_plan_pages(
+ p_brand_id uuid,
+ p_days integer default 30
+)
+returns jsonb
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+-- A cached generic plan can't see the brand's size (00207).
+set plan_cache_mode to 'force_custom_plan'
+as $$
+declare
+ v_last date := (now() at time zone 'utc')::date - 1;
+ v_cur_day date;
+ v_prev_day date;
+ v_cur 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_cur_day := v_last - p_days + 1;
+ v_prev_day := v_cur_day - p_days;
+ v_cur := v_cur_day::timestamp at time zone 'utc';
+ v_until := (v_last + 1)::timestamp at time zone 'utc';
+
+ with own_domains as (
+ select lower(regexp_replace(bd.domain, '^www\.', '')) as domain
+ from public.brand_domains bd
+ where bd.brand_id = p_brand_id
+ ),
+ own_urls as materialized (
+ select cu.id, cu.url, cu.title, lower(public.normalize_page_path(cu.url)) as page_key
+ from public.citation_urls cu
+ where cu.domain in (select domain from own_domains)
+ ),
+ url_counts as materialized (
+ select d.url_id, d.platform, d.day >= v_cur_day as is_cur, sum(d.citations)::bigint as n
+ from public.citation_url_daily d
+ where d.brand_id = p_brand_id
+ and d.day >= v_prev_day
+ and d.day <= v_last
+ and d.url_id in (select id from own_urls)
+ and d.platform is distinct from 'chatgpt-shopping'
+ group by d.url_id, d.platform, d.day >= v_cur_day
+ ),
+ url_totals as (
+ select
+ u.page_key,
+ u.url,
+ u.title,
+ coalesce(sum(c.n) filter (where c.is_cur), 0) as cur,
+ coalesce(sum(c.n) filter (where not c.is_cur), 0) as prev
+ from url_counts c
+ join own_urls u on u.id = c.url_id
+ group by u.page_key, u.url, u.title
+ ),
+ pages as materialized (
+ select
+ t.page_key,
+ -- The address cited most often stands for the page.
+ (array_agg(t.url order by t.cur + t.prev desc, t.url))[1] as page,
+ max(t.title) as title,
+ sum(t.cur)::bigint as cur,
+ sum(t.prev)::bigint as prev
+ from url_totals t
+ group by t.page_key
+ order by sum(t.cur + t.prev) desc, t.page_key
+ limit 100
+ ),
+ answers as (
+ select
+ r.platform,
+ coalesce(sum(r.answers) filter (where r.day >= v_cur_day), 0)::bigint as cur,
+ coalesce(sum(r.answers) filter (where r.day < v_cur_day), 0)::bigint as prev
+ from public.citation_result_daily r
+ where r.brand_id = p_brand_id
+ and r.day >= v_prev_day
+ and r.day <= v_last
+ and r.platform is distinct from 'chatgpt-shopping'
+ group by r.platform
+ ),
+ per_platform as (
+ select
+ u.page_key,
+ c.platform,
+ coalesce(sum(c.n) filter (where c.is_cur), 0) as cur,
+ coalesce(sum(c.n) filter (where not c.is_cur), 0) as prev
+ from url_counts c
+ join own_urls u on u.id = c.url_id
+ where u.page_key in (select p.page_key from pages p)
+ and c.platform is not null
+ group by u.page_key, c.platform
+ ),
+ down as (
+ -- A platform tracked in both windows, citing the page at a lower rate.
+ select
+ pp.page_key,
+ array_agg(
+ pp.platform
+ order by pp.prev::numeric / a.prev - pp.cur::numeric / a.cur desc, pp.platform
+ ) as platforms
+ from per_platform pp
+ join answers a on a.platform = pp.platform
+ where a.prev > 0
+ and a.cur > 0
+ and pp.prev::numeric / a.prev > pp.cur::numeric / a.cur
+ group by pp.page_key
+ ),
+ cur_answers as materialized (
+ select pr.id, pr.prompt_id
+ from public.prompt_results pr
+ where pr.brand_id = p_brand_id
+ and pr.created_at >= v_cur
+ and pr.created_at < v_until
+ and pr.platform is distinct from 'chatgpt-shopping'
+ ),
+ page_prompts as (
+ select distinct u.page_key, a.prompt_id
+ from public.prompt_result_citations prc
+ join own_urls u on u.id = prc.url_id
+ join cur_answers a on a.id = prc.prompt_result_id
+ where prc.brand_id = p_brand_id
+ and prc.created_at >= v_cur
+ and prc.created_at < v_until
+ and u.page_key in (select p.page_key from pages p)
+ ),
+ competing as (
+ select a.page_key, b.page_key as other
+ from page_prompts a
+ join page_prompts b on b.prompt_id = a.prompt_id and b.page_key <> a.page_key
+ group by a.page_key, b.page_key
+ having count(*) >= 2
+ ),
+ page_overlaps as (
+ select cm.page_key, count(*) as pages
+ from competing cm
+ group by cm.page_key
+ ),
+ 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_cur
+ and l.created_at < v_until
+ ),
+ visits as (
+ select lower(public.normalize_page_path(l.url)) as page_key, 1::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_cur
+ and l.created_at < v_until
+ union all
+ select lower(public.normalize_page_path(g.landing_page)), g.sessions::bigint
+ from public.ga_ai_traffic_stats g
+ where g.brand_id = p_brand_id
+ and g.sessions > 0
+ -- A session without a landing page would read as the home page.
+ and g.landing_page <> ''
+ and g.date >= v_cur_day
+ and g.date <= v_last
+ and not exists (select 1 from snippet_days s where s.day = g.date)
+ ),
+ page_visits as (
+ select v.page_key, sum(v.n) as visits
+ from visits v
+ where v.page_key in (select p.page_key from pages p)
+ group by v.page_key
+ )
+ select jsonb_build_object(
+ 'days', p_days,
+ -- The earlier window's first day, and the brand's first tracked day: a
+ -- window before it is only partly tracked, or not at all.
+ 'prevFrom', v_prev_day,
+ 'trackedSince', (
+ select min(r.day) from public.citation_result_daily r where r.brand_id = p_brand_id
+ ),
+ 'answers', (
+ select jsonb_build_object(
+ 'cur', coalesce(sum(a.cur), 0),
+ 'prev', coalesce(sum(a.prev), 0)
+ )
+ from answers a
+ ),
+ 'pages', coalesce((
+ select jsonb_agg(
+ jsonb_build_object(
+ 'page', p.page,
+ 'title', p.title,
+ 'citations', jsonb_build_object('cur', p.cur, 'prev', p.prev),
+ 'platformsDown', coalesce(to_jsonb(d.platforms[1:3]), '[]'::jsonb),
+ 'aiVisits', coalesce(pv.visits, 0),
+ 'overlaps', coalesce(o.pages, 0)
+ )
+ order by p.cur + p.prev desc, p.page
+ )
+ from pages p
+ left join down d on d.page_key = p.page_key
+ left join page_overlaps o on o.page_key = p.page_key
+ left join page_visits pv on pv.page_key = p.page_key
+ ), '[]'::jsonb)
+ )
+ into v_result;
+
+ return v_result;
+end;
+$$;
+
+revoke all on function public.content_plan_pages(uuid, integer) from public, anon;
+grant execute on function public.content_plan_pages(uuid, integer) to authenticated, service_role;
+
+comment on function public.content_plan_pages(uuid, integer) is
+ 'Content Editor (CE-014): the brand''s 100 most cited pages over the last N (7, 30 or 90) whole UTC days to yesterday and the N before, from the daily rollups: citations, the brand''s answers in each window, platforms citing at a lower rate, AI visits and how many of its other pages compete for the same prompts; with the earlier window''s first day and the brand''s first tracked day. Security definer with an organization check.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 0d8aef04e..44c8ac4d9 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -30772,3 +30772,407 @@ grant execute on function public.content_plan_pages(uuid, integer) to authentica
comment on function public.content_plan_pages(uuid, integer) is
'Content Editor (CE-014): the brand''s 100 most cited pages over the last N (7 or 30) whole UTC days to yesterday and the N before, from the daily rollups: citations, the brand''s answers in each window, platforms citing at a lower rate, AI visits and how many of its other pages compete for the same prompts. Security definer with an organization check.';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00221_content_plan_insights.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00221: what AI cites, and what AI visits bring in, for the Content plan
+-- ============================================================================
+-- The Plan (Content Editor CE-014, spec v2 §4) shows, under its cards:
+--
+-- * "What AI cites in your topics": one row per page type with the share
+-- of AI citations in the brand's tracked answers going to that type of
+-- page, and the brand's own mix. Page types are read from the address
+-- and title (lib/content/page-types.ts), so this returns the addresses
+-- over the last p_days whole UTC days to yesterday (as the Plan's pages,
+-- 00220), from the nightly rollup (citation_url_daily, 00118), ChatGPT
+-- Shopping left out: every one of the brand's own (at most a few
+-- thousand, so its mix is whole), and the 1,000 others cited most; with
+-- the total, so the share the list covers is known;
+-- * the AI results strip: what AI-referred visitors did on the whole site
+-- over the same days, as the Impact tab's results (00210) read one page:
+-- visits by ai_traffic_merged's rule (00176), and Google Analytics' AI
+-- key events, purchases and revenue; whether a property is set (the app
+-- checks the connection too), and whether it reported any purchase.
+--
+-- The Plan's period is now 7, 30 or 90 days (a quarter), so
+-- content_plan_pages (00220) is redefined to take 90 as well, and to say
+-- since when the brand is tracked: few brands have 180 days of history, so
+-- at 90 days the earlier window is often only partly tracked, or not at all.
+--
+-- Security definer with an organization check, as 00209–00220.
+
+create or replace function public.content_plan_insights(
+ p_brand_id uuid,
+ p_days integer default 30
+)
+returns jsonb
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+as $$
+declare
+ -- Whole days to yesterday, as the Plan's pages (00220).
+ v_last 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 not in (7, 30, 90) then
+ raise exception 'p_days must be 7, 30 or 90';
+ end if;
+
+ v_day := v_last - p_days + 1;
+ v_from := v_day::timestamp at time zone 'utc';
+ v_until := (v_last + 1)::timestamp at time zone 'utc';
+
+ with own_domains as (
+ select lower(regexp_replace(bd.domain, '^www\.', '')) as domain
+ from public.brand_domains bd
+ where bd.brand_id = p_brand_id
+ ),
+ cited as materialized (
+ select d.url_id, sum(d.citations)::bigint as citations
+ from public.citation_url_daily d
+ where d.brand_id = p_brand_id
+ and d.day >= v_day
+ and d.day <= v_last
+ and d.platform is distinct from 'chatgpt-shopping'
+ group by d.url_id
+ ),
+ addresses as (
+ select c.url_id, c.citations, cu.url, cu.title, cu.domain in (select domain from own_domains) as own
+ from cited c
+ join public.citation_urls cu on cu.id = c.url_id
+ ),
+ top_urls as (
+ select a.* from addresses a where a.own
+ union all
+ (
+ select a.* from addresses a
+ where not a.own
+ order by a.citations desc, a.url_id
+ limit 1000
+ )
+ ),
+ 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 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
+ union all
+ select coalesce(sum(g.sessions), 0)::bigint
+ from public.ga_ai_traffic_stats g
+ where g.brand_id = p_brand_id
+ and g.sessions > 0
+ and g.date >= v_day
+ and g.date <= v_last
+ and not exists (select 1 from snippet_days s where s.day = g.date)
+ ),
+ analytics as (
+ select
+ coalesce(sum(g.key_events), 0)::bigint as key_events,
+ coalesce(sum(g.transactions), 0)::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.date >= v_day
+ and g.date <= v_last
+ )
+ select jsonb_build_object(
+ 'days', p_days,
+ 'totalCitations', (select coalesce(sum(c.citations), 0) from cited c),
+ 'citations', coalesce((
+ select jsonb_agg(
+ jsonb_build_object(
+ 'url', t.url,
+ 'title', t.title,
+ 'own', t.own,
+ 'citations', t.citations
+ )
+ order by t.citations desc, t.url
+ )
+ from top_urls t
+ ), '[]'::jsonb),
+ 'results', (
+ select jsonb_build_object(
+ 'visits', (select coalesce(sum(v.n), 0) from visits v),
+ 'keyEvents', a.key_events,
+ 'transactions', a.transactions,
+ 'revenue', a.revenue,
+ 'analytics', (
+ select nullif(b.ga_property_id, '') is not null
+ from public.brands b where b.id = p_brand_id
+ ),
+ 'purchases', a.transactions > 0 or a.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
+ and (c.transactions > 0 or c.purchase_revenue > 0)
+ )
+ )
+ from analytics a
+ )
+ )
+ into v_result;
+
+ return v_result;
+end;
+$$;
+
+revoke all on function public.content_plan_insights(uuid, integer) from public, anon;
+grant execute on function public.content_plan_insights(uuid, integer) to authenticated, service_role;
+
+comment on function public.content_plan_insights(uuid, integer) is
+ 'Content Editor (CE-014): the addresses AI answers cite for the brand over the last N (7, 30 or 90) whole UTC days to yesterday (from citation_url_daily): every own page and the 1,000 others cited most, with the total; and what AI-referred visitors did on the site: visits, Google Analytics AI key events, purchases and revenue. Security definer with an organization check.';
+
+-- ─── content_plan_pages (00220), taking 90 days too ─────────────────────────
+-- As 00220, with 90 days and the windows' tracking: 'prevFrom' and
+-- 'trackedSince' tell the Plan when the earlier window isn't fully tracked.
+
+create or replace function public.content_plan_pages(
+ p_brand_id uuid,
+ p_days integer default 30
+)
+returns jsonb
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+-- A cached generic plan can't see the brand's size (00207).
+set plan_cache_mode to 'force_custom_plan'
+as $$
+declare
+ v_last date := (now() at time zone 'utc')::date - 1;
+ v_cur_day date;
+ v_prev_day date;
+ v_cur 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_cur_day := v_last - p_days + 1;
+ v_prev_day := v_cur_day - p_days;
+ v_cur := v_cur_day::timestamp at time zone 'utc';
+ v_until := (v_last + 1)::timestamp at time zone 'utc';
+
+ with own_domains as (
+ select lower(regexp_replace(bd.domain, '^www\.', '')) as domain
+ from public.brand_domains bd
+ where bd.brand_id = p_brand_id
+ ),
+ own_urls as materialized (
+ select cu.id, cu.url, cu.title, lower(public.normalize_page_path(cu.url)) as page_key
+ from public.citation_urls cu
+ where cu.domain in (select domain from own_domains)
+ ),
+ url_counts as materialized (
+ select d.url_id, d.platform, d.day >= v_cur_day as is_cur, sum(d.citations)::bigint as n
+ from public.citation_url_daily d
+ where d.brand_id = p_brand_id
+ and d.day >= v_prev_day
+ and d.day <= v_last
+ and d.url_id in (select id from own_urls)
+ and d.platform is distinct from 'chatgpt-shopping'
+ group by d.url_id, d.platform, d.day >= v_cur_day
+ ),
+ url_totals as (
+ select
+ u.page_key,
+ u.url,
+ u.title,
+ coalesce(sum(c.n) filter (where c.is_cur), 0) as cur,
+ coalesce(sum(c.n) filter (where not c.is_cur), 0) as prev
+ from url_counts c
+ join own_urls u on u.id = c.url_id
+ group by u.page_key, u.url, u.title
+ ),
+ pages as materialized (
+ select
+ t.page_key,
+ -- The address cited most often stands for the page.
+ (array_agg(t.url order by t.cur + t.prev desc, t.url))[1] as page,
+ max(t.title) as title,
+ sum(t.cur)::bigint as cur,
+ sum(t.prev)::bigint as prev
+ from url_totals t
+ group by t.page_key
+ order by sum(t.cur + t.prev) desc, t.page_key
+ limit 100
+ ),
+ answers as (
+ select
+ r.platform,
+ coalesce(sum(r.answers) filter (where r.day >= v_cur_day), 0)::bigint as cur,
+ coalesce(sum(r.answers) filter (where r.day < v_cur_day), 0)::bigint as prev
+ from public.citation_result_daily r
+ where r.brand_id = p_brand_id
+ and r.day >= v_prev_day
+ and r.day <= v_last
+ and r.platform is distinct from 'chatgpt-shopping'
+ group by r.platform
+ ),
+ per_platform as (
+ select
+ u.page_key,
+ c.platform,
+ coalesce(sum(c.n) filter (where c.is_cur), 0) as cur,
+ coalesce(sum(c.n) filter (where not c.is_cur), 0) as prev
+ from url_counts c
+ join own_urls u on u.id = c.url_id
+ where u.page_key in (select p.page_key from pages p)
+ and c.platform is not null
+ group by u.page_key, c.platform
+ ),
+ down as (
+ -- A platform tracked in both windows, citing the page at a lower rate.
+ select
+ pp.page_key,
+ array_agg(
+ pp.platform
+ order by pp.prev::numeric / a.prev - pp.cur::numeric / a.cur desc, pp.platform
+ ) as platforms
+ from per_platform pp
+ join answers a on a.platform = pp.platform
+ where a.prev > 0
+ and a.cur > 0
+ and pp.prev::numeric / a.prev > pp.cur::numeric / a.cur
+ group by pp.page_key
+ ),
+ cur_answers as materialized (
+ select pr.id, pr.prompt_id
+ from public.prompt_results pr
+ where pr.brand_id = p_brand_id
+ and pr.created_at >= v_cur
+ and pr.created_at < v_until
+ and pr.platform is distinct from 'chatgpt-shopping'
+ ),
+ page_prompts as (
+ select distinct u.page_key, a.prompt_id
+ from public.prompt_result_citations prc
+ join own_urls u on u.id = prc.url_id
+ join cur_answers a on a.id = prc.prompt_result_id
+ where prc.brand_id = p_brand_id
+ and prc.created_at >= v_cur
+ and prc.created_at < v_until
+ and u.page_key in (select p.page_key from pages p)
+ ),
+ competing as (
+ select a.page_key, b.page_key as other
+ from page_prompts a
+ join page_prompts b on b.prompt_id = a.prompt_id and b.page_key <> a.page_key
+ group by a.page_key, b.page_key
+ having count(*) >= 2
+ ),
+ page_overlaps as (
+ select cm.page_key, count(*) as pages
+ from competing cm
+ group by cm.page_key
+ ),
+ 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_cur
+ and l.created_at < v_until
+ ),
+ visits as (
+ select lower(public.normalize_page_path(l.url)) as page_key, 1::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_cur
+ and l.created_at < v_until
+ union all
+ select lower(public.normalize_page_path(g.landing_page)), g.sessions::bigint
+ from public.ga_ai_traffic_stats g
+ where g.brand_id = p_brand_id
+ and g.sessions > 0
+ -- A session without a landing page would read as the home page.
+ and g.landing_page <> ''
+ and g.date >= v_cur_day
+ and g.date <= v_last
+ and not exists (select 1 from snippet_days s where s.day = g.date)
+ ),
+ page_visits as (
+ select v.page_key, sum(v.n) as visits
+ from visits v
+ where v.page_key in (select p.page_key from pages p)
+ group by v.page_key
+ )
+ select jsonb_build_object(
+ 'days', p_days,
+ -- The earlier window's first day, and the brand's first tracked day: a
+ -- window before it is only partly tracked, or not at all.
+ 'prevFrom', v_prev_day,
+ 'trackedSince', (
+ select min(r.day) from public.citation_result_daily r where r.brand_id = p_brand_id
+ ),
+ 'answers', (
+ select jsonb_build_object(
+ 'cur', coalesce(sum(a.cur), 0),
+ 'prev', coalesce(sum(a.prev), 0)
+ )
+ from answers a
+ ),
+ 'pages', coalesce((
+ select jsonb_agg(
+ jsonb_build_object(
+ 'page', p.page,
+ 'title', p.title,
+ 'citations', jsonb_build_object('cur', p.cur, 'prev', p.prev),
+ 'platformsDown', coalesce(to_jsonb(d.platforms[1:3]), '[]'::jsonb),
+ 'aiVisits', coalesce(pv.visits, 0),
+ 'overlaps', coalesce(o.pages, 0)
+ )
+ order by p.cur + p.prev desc, p.page
+ )
+ from pages p
+ left join down d on d.page_key = p.page_key
+ left join page_overlaps o on o.page_key = p.page_key
+ left join page_visits pv on pv.page_key = p.page_key
+ ), '[]'::jsonb)
+ )
+ into v_result;
+
+ return v_result;
+end;
+$$;
+
+revoke all on function public.content_plan_pages(uuid, integer) from public, anon;
+grant execute on function public.content_plan_pages(uuid, integer) to authenticated, service_role;
+
+comment on function public.content_plan_pages(uuid, integer) is
+ 'Content Editor (CE-014): the brand''s 100 most cited pages over the last N (7, 30 or 90) whole UTC days to yesterday and the N before, from the daily rollups: citations, the brand''s answers in each window, platforms citing at a lower rate, AI visits and how many of its other pages compete for the same prompts; with the earlier window''s first day and the brand''s first tracked day. Security definer with an organization check.';
+
diff --git a/web/messages/en.json b/web/messages/en.json
index 0c5ec228e..72383104c 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3105,9 +3105,31 @@
"protect": { "title": "Protect", "hint": "Top pages · edit with care" },
"overlaps": { "title": "Overlaps", "hint": "Pages competing for the same prompts" }
},
+ "results": {
+ "label": "From AI visits · {days} full days to yesterday (UTC):",
+ "visits": "{count, plural, one {{value} visit} other {{value} visits}}",
+ "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."
+ },
+ "mix": {
+ "title": "What AI cites in your topics",
+ "aiShare": "Share of AI citations",
+ "yourShare": "Your pages' mix",
+ "shares": "{ai}% · {yours}%",
+ "pages": "{count, plural, =0 {No page} one {# page} other {# pages}}",
+ "gap": "{count, plural, =0 {Gap · no page} one {Gap · # page} other {Gap · # pages}}",
+ "empty": "No cited pages with a known type in this period yet.",
+ "covered": "The shares cover {pct}% of the period's AI citations: the most cited addresses whose type shows. Forums, encyclopedias, news and the long tail of less cited pages aren't in them."
+ },
"listTitle": "Priority list",
+ "earlier": {
+ "none": "No page reads as losing ground yet: tracking began {since}, so the {days} days before aren't tracked to compare with.",
+ "partial": "The {days} days before are tracked only since {since}: pages are compared per tracked answer."
+ },
"ranked": "Ranked by impact · overlaps checked",
- "filtered": "Filtered · click the card again to clear",
+ "filtered": "Filtered · click it again to clear",
"columns": {
"page": "Page",
"action": "Action",
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
new file mode 100644
index 000000000..7a3f63ec9
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_plan-insights.tsx
@@ -0,0 +1,149 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { Sparkles } from 'lucide-react';
+import { Link } from '@/i18n/navigation';
+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 { cn } from '@/lib/utils';
+
+/**
+ * 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.
+ */
+export function AiResultsStrip({ results, days }: { results: PlanResults; days: PlanPeriod }) {
+ const t = useTranslations('contentEditor.plan.results');
+ const parts = [t('visits', { count: results.visits, value: formatNumber(results.visits) })];
+ if (results.analytics) {
+ parts.push(
+ t('keyEvents', { count: results.keyEvents, value: formatNumber(results.keyEvents) }),
+ );
+ if (results.purchases) {
+ parts.push(
+ t('orders', { count: results.transactions, value: formatNumber(results.transactions) }),
+ t('revenue', { value: formatNumber(Math.round(results.revenue)) }),
+ );
+ }
+ }
+ 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" />
+ <span className="text-muted-foreground">{t('label', { days })}</span>
+ <span className="font-medium">{parts.join(' · ')}</span>
+ {!results.analytics && (
+ <span className="text-muted-foreground">
+ {t.rich('needsAnalytics', {
+ link: (chunks) => (
+ <Link
+ href="/dashboard/traffic"
+ className="font-medium text-foreground underline underline-offset-2 hover:no-underline"
+ >
+ {chunks}
+ </Link>
+ ),
+ })}
+ </span>
+ )}
+ </div>
+ );
+}
+
+/**
+ * "What AI cites in your topics" (CE-014): per page type, the share of AI
+ * citations (light bar) and the type's share of the brand's own cited pages
+ * (dark bar), two mixes of 100 each, with a gap flagged in amber. A row
+ * filters the priority list to its type; clicking it again clears it.
+ */
+export function PageTypeMix({
+ rows,
+ covered,
+ selected,
+ onSelect,
+}: {
+ rows: MixRow[];
+ /** The share of all the period's citations the shares are of, in whole percent. */
+ covered: number;
+ selected: PageType | null;
+ onSelect: (type: PageType | null) => void;
+}) {
+ const t = useTranslations('contentEditor.plan.mix');
+ const tTypes = useTranslations('contentEditor.pageTypes');
+ // The most cited type fills the track; the others are drawn to its scale.
+ const scale = Math.max(1, ...rows.map((r) => r.aiShare));
+
+ return (
+ <section aria-labelledby="plan-mix-title" className="space-y-2">
+ <div className="flex flex-wrap items-baseline justify-between gap-2">
+ <h2 id="plan-mix-title" className="text-sm font-medium">
+ {t('title')}
+ </h2>
+ <span className="flex items-center gap-3 text-xs text-muted-foreground">
+ <span className="flex items-center gap-1.5">
+ <span aria-hidden className="h-2 w-2 rounded-sm bg-muted-foreground/30" />
+ {t('aiShare')}
+ </span>
+ <span className="flex items-center gap-1.5">
+ <span aria-hidden className="h-2 w-2 rounded-sm bg-foreground" />
+ {t('yourShare')}
+ </span>
+ </span>
+ </div>
+ {rows.length === 0 ? (
+ <p className="rounded-xl border px-4 py-3 text-sm text-muted-foreground">{t('empty')}</p>
+ ) : (
+ <ul className="divide-y rounded-xl border">
+ {rows.map((row) => (
+ <li key={row.pageType}>
+ <button
+ type="button"
+ aria-pressed={selected === row.pageType}
+ onClick={() => onSelect(selected === row.pageType ? null : row.pageType)}
+ className={cn(
+ 'grid w-full grid-cols-[minmax(0,10rem)_1fr_auto] items-center gap-3 px-4 py-2 text-left text-sm transition-colors hover:bg-muted/40 sm:grid-cols-[minmax(0,12rem)_1fr_5.5rem_8rem]',
+ selected === row.pageType && 'bg-muted/60',
+ )}
+ >
+ <span className="truncate">{tTypes(row.pageType)}</span>
+ <span aria-hidden className="relative h-2 rounded-full bg-muted">
+ <span
+ className="absolute inset-y-0 left-0 rounded-full bg-muted-foreground/30"
+ style={{ width: `${(row.aiShare / scale) * 100}%` }}
+ />
+ <span
+ className="absolute inset-y-0 left-0 rounded-full bg-foreground"
+ style={{ width: `${(row.yourShare / scale) * 100}%` }}
+ />
+ </span>
+ <span className="text-right text-xs tabular-nums text-muted-foreground">
+ {t('shares', { ai: row.aiShare, yours: row.yourShare })}
+ {/* On a phone the gap goes under the shares. */}
+ {row.gap && (
+ <span className="block font-medium text-amber-700 sm:hidden dark:text-amber-400">
+ {t('gap', { count: row.pages })}
+ </span>
+ )}
+ </span>
+ <span
+ className={cn(
+ 'hidden text-right text-xs sm:block',
+ row.gap
+ ? 'font-medium text-amber-700 dark:text-amber-400'
+ : 'text-muted-foreground',
+ )}
+ >
+ {row.gap ? t('gap', { count: row.pages }) : t('pages', { count: row.pages })}
+ </span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ {rows.length > 0 && covered < 100 && (
+ <p className="text-xs text-muted-foreground">{t('covered', { pct: covered })}</p>
+ )}
+ </section>
+ );
+}
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 0b696cb56..92e549c16 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
@@ -7,8 +7,10 @@ import type { PlanOpportunity, PlanPage } from '@/lib/content/plan';
import ContentPlanPage from './page';
const getContentPlan = vi.fn();
+const getContentPlanInsights = vi.fn();
vi.mock('@/lib/actions/content-plan', () => ({
getContentPlan: (...args: unknown[]) => getContentPlan(...args),
+ getContentPlanInsights: (...args: unknown[]) => getContentPlanInsights(...args),
}));
// New content is new-content-dialog.test.tsx's; here, what the Plan opens it on.
const dialog = vi.hoisted(() => ({ props: null as Record<string, unknown> | null }));
@@ -75,10 +77,35 @@ const PLAN = {
}),
],
answers: { cur: 100, prev: 100 },
+ tracking: { prevFrom: '2026-08-23', trackedSince: '2026-06-01' },
opportunities: [opportunity],
drafts: [],
};
+const INSIGHTS = {
+ // The listed addresses hold 80; the tail beyond them 40 more.
+ totalCitations: 120,
+ citations: [
+ {
+ url: 'https://rival.example/guides/espresso-machines',
+ title: null,
+ own: false,
+ citations: 30,
+ },
+ { url: 'https://acme.example/guides/espresso', title: null, own: true, citations: 10 },
+ { url: 'https://acme.example/blog/latte-art', title: null, own: true, citations: 20 },
+ { url: 'https://www.reddit.com/r/espresso/x', title: null, own: false, citations: 20 },
+ ],
+ results: {
+ visits: 1240,
+ keyEvents: 48,
+ transactions: 12,
+ revenue: 3210.4,
+ analytics: true,
+ purchases: true,
+ },
+};
+
let container: HTMLDivElement;
let root: Root;
@@ -108,6 +135,7 @@ beforeEach(() => {
document.body.appendChild(container);
root = createRoot(container);
getContentPlan.mockReset().mockResolvedValue(PLAN);
+ getContentPlanInsights.mockReset().mockResolvedValue(INSIGHTS);
dialog.props = null;
});
@@ -150,18 +178,24 @@ describe('the Content plan', () => {
await act(async () => button('Overlaps').click());
expect(button('Overlaps').getAttribute('aria-pressed')).toBe('true');
expect(rowTexts().map((r) => r[1])).toEqual(['Protect']);
- expect(container.textContent).toContain('Filtered · click the card again to clear');
+ expect(container.textContent).toContain('Filtered · click it again to clear');
await act(async () => button('Overlaps').click());
expect(rowTexts()).toHaveLength(3);
});
- it('reads the other period, and keeps it in the URL', async () => {
+ it('reads the other periods, a quarter too, and keeps the period in the URL', async () => {
await renderPage();
await act(async () => button('Last 7 days').click());
expect(getContentPlan).toHaveBeenLastCalledWith('brand-1', 7);
expect(window.location.search).toBe('?days=7');
expect(container.querySelector('thead')!.textContent).toContain('Why · last 7 days');
+
+ await act(async () => button('Last 90 days').click());
+ expect(getContentPlan).toHaveBeenLastCalledWith('brand-1', 90);
+ expect(getContentPlanInsights).toHaveBeenLastCalledWith('brand-1', 90);
+ expect(window.location.search).toBe('?days=90');
+ expect(container.textContent).toContain('From AI visits · 90 full days to yesterday (UTC):');
});
it('opens on the period in the URL, read once', async () => {
@@ -226,6 +260,115 @@ describe('the Content plan', () => {
expect(rows[2].querySelector('a')!.getAttribute('href')).toBe('/dashboard/content/editor/d1');
});
+ it('shows what AI visits brought in, and what AI cites by page type', async () => {
+ await renderPage();
+ expect(getContentPlanInsights).toHaveBeenCalledWith('brand-1', 30);
+ expect(container.textContent).toContain(
+ 'From AI visits · 30 full days to yesterday (UTC):1,240 visits · 48 key events · 12 orders · 3,210 revenue',
+ );
+ const mix = container.querySelector('section[aria-labelledby="plan-mix-title"]')!;
+ // AI's mix (guides 40 of 60 typed) against the brand's own pages' (guides 10 of 30).
+ // The gap shows twice: under the shares on a phone, in its column on wider screens.
+ expect([...mix.querySelectorAll('li')].map((li) => li.textContent)).toEqual([
+ 'Guide67% · 33%Gap · 1 pageGap · 1 page',
+ 'Blog post33% · 67%1 page',
+ ]);
+ expect(mix.querySelector('p')!.textContent).toBe(
+ "The shares cover 50% of the period's AI citations: the most cited addresses whose type shows. Forums, encyclopedias, news and the long tail of less cited pages aren't in them.",
+ );
+ });
+
+ it('filters the list by a page type, and clears it on a second click', async () => {
+ await renderPage();
+ const guide = () =>
+ container.querySelector<HTMLButtonElement>(
+ 'section[aria-labelledby="plan-mix-title"] button',
+ )!;
+ await act(async () => guide().click());
+ expect(guide().getAttribute('aria-pressed')).toBe('true');
+ expect(rowTexts().map((r) => r[0])).toEqual([
+ 'Coffee subscriptionsGuide/guides/coffee-subscriptions',
+ 'Espresso guideGuide/guides/espresso⚠ Overlap',
+ ]);
+ await act(async () => guide().click());
+ expect(rowTexts()).toHaveLength(3);
+ });
+
+ it('asks for Google Analytics to show what AI visitors did', async () => {
+ getContentPlanInsights.mockResolvedValue({
+ ...INSIGHTS,
+ results: { ...INSIGHTS.results, analytics: false, purchases: false },
+ });
+ await renderPage();
+ expect(container.textContent).toContain(
+ 'From AI visits · 30 full days to yesterday (UTC):1,240 visitsConnect Google Analytics to see what they did next.',
+ );
+ expect(
+ [...container.querySelectorAll('a')]
+ .find((a) => a.textContent === 'Connect Google Analytics')!
+ .getAttribute('href'),
+ ).toBe('/dashboard/traffic');
+ });
+
+ it('drops a page-type filter the period’s mix no longer lists, and a brand’s filters on switching', async () => {
+ await renderPage();
+ const guide = () =>
+ container.querySelector<HTMLButtonElement>(
+ 'section[aria-labelledby="plan-mix-title"] button',
+ )!;
+ await act(async () => guide().click());
+ await act(async () => button('Overlaps').click());
+ expect(rowTexts()).toHaveLength(1);
+
+ // The 7 days' mix has no guide: the list isn't filtered by it.
+ getContentPlanInsights.mockResolvedValue({
+ ...INSIGHTS,
+ citations: [
+ { url: 'https://acme.example/blog/latte-art', title: null, own: true, citations: 5 },
+ ],
+ });
+ await act(async () => button('Last 7 days').click());
+ await act(async () => button('Overlaps').click());
+ expect(container.textContent).not.toContain('Filtered');
+ expect(rowTexts()).toHaveLength(3);
+
+ await act(async () => button('Overlaps').click());
+ brandState.activeBrandId = 'brand-2';
+ brandState.brands.push({ id: 'brand-2', siteType: 'b2b' });
+ await renderPage();
+ expect(button('Overlaps').getAttribute('aria-pressed')).toBe('false');
+ brandState.brands.pop();
+ });
+
+ it('says when the earlier period is tracked only in part, or not at all', async () => {
+ getContentPlan.mockResolvedValue({
+ ...PLAN,
+ tracking: { prevFrom: '2026-08-23', trackedSince: '2026-09-09' },
+ });
+ await renderPage();
+ expect(container.textContent).toContain(
+ 'The 30 days before are tracked only since Sep 9: pages are compared per tracked answer.',
+ );
+
+ getContentPlan.mockResolvedValue({
+ ...PLAN,
+ answers: { cur: 100, prev: 0 },
+ tracking: { prevFrom: '2026-04-24', trackedSince: '2026-09-09' },
+ });
+ await act(async () => button('Last 90 days').click());
+ expect(container.textContent).toContain(
+ "No page reads as losing ground yet: tracking began Sep 9, so the 90 days before aren't tracked to compare with.",
+ );
+ });
+
+ it('reads the mix again with the period, not after a draft is sent', async () => {
+ await renderPage();
+ expect(getContentPlanInsights).toHaveBeenCalledTimes(1);
+ await act(async () => (dialog.props!.onSent as () => void)());
+ expect(getContentPlan).toHaveBeenCalledTimes(2);
+ expect(getContentPlanInsights).toHaveBeenCalledTimes(1);
+ });
+
it('says so when the plan can’t be read, and tries again', async () => {
getContentPlan.mockRejectedValueOnce(new Error('boom'));
await renderPage();
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 47500c99a..d6589f951 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx
@@ -1,17 +1,20 @@
'use client';
import { useEffect, useMemo, useState } from 'react';
-import { useTranslations } from 'next-intl';
+import { useFormatter, useTranslations } from 'next-intl';
import { Loader2, Plus } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { NewContentDialog, type DialogPreset } from '@/components/content/new-content-dialog';
-import { getContentPlan } from '@/lib/actions/content-plan';
+import { getContentPlan, getContentPlanInsights } from '@/lib/actions/content-plan';
+import type { PageType } from '@/lib/content/drafts';
+import { pageTypeMix } from '@/lib/content/plan-mix';
import { siteTypeOf } from '@/lib/content/page-types';
import {
PLAN_CARDS,
PLAN_PERIODS,
buildPlan,
+ earlierPeriod,
rowsFor,
type PlanCard,
type PlanPeriod,
@@ -21,6 +24,7 @@ import { formatNumber } from '@/lib/format';
import { readUrlChoice, writeUrlParams } from '@/lib/url-state';
import { cn } from '@/lib/utils';
import { useBrandStore } from '@/stores/use-brand-store';
+import { AiResultsStrip, PageTypeMix } from './_plan-insights';
import { PlanTable } from './_plan-table';
type PlanRead = {
@@ -30,6 +34,13 @@ type PlanRead = {
failed: boolean;
};
+/** The page-type mix and results strip, read on their own: either can fail alone. */
+type InsightsRead = {
+ brandId: string;
+ days: PlanPeriod;
+ data: Awaited<ReturnType<typeof getContentPlanInsights>>;
+};
+
/** Each card's color, as its action's tag: Create blue, Optimize amber, Protect green, Overlaps red. */
const CARD_DOT: Record<PlanCard, string> = {
create: 'bg-blue-600 dark:bg-blue-400',
@@ -40,28 +51,38 @@ const CARD_DOT: Record<PlanCard, string> = {
/**
* The Content plan (Content Editor CE-014, spec v2 §4): what to create,
- * optimize or protect next, for the last 7 or 30 days. Four cards count the
- * work and filter the list; the list ranks it, and each row starts it in New
- * content (Start for an opportunity, an existing page read to optimize) or
- * opens the draft already being written. The period lives in the URL
- * (?days=7).
+ * optimize or protect next, for the last 7, 30 or 90 days. Four cards count
+ * the work and filter the list, as a row of the page-type mix does; the list
+ * ranks it, and each row starts it in New content (Start for an opportunity,
+ * an existing page read to optimize) or opens the draft already being
+ * written. The period lives in the URL (?days=7).
*/
export default function ContentPlanPage() {
const t = useTranslations('contentEditor.plan');
+ const format = useFormatter();
const activeBrandId = useBrandStore((s) => s.activeBrandId);
const activeBrand = useBrandStore((s) => s.brands.find((b) => b.id === s.activeBrandId));
const siteType = siteTypeOf(activeBrand ?? {});
// Null until the URL is read, so ?days=7 reads 7 days once, not 30 first.
const [days, setDays] = useState<PlanPeriod | null>(null);
const [card, setCard] = useState<PlanCard | null>(null);
+ const [mixType, setMixType] = useState<PageType | null>(null);
+ const [insights, setInsights] = useState<InsightsRead | null>(null);
const [read, setRead] = useState<PlanRead | null>(null);
const [attempt, setAttempt] = useState(0);
const [starting, setStarting] = useState(false);
const [preset, setPreset] = useState<DialogPreset | null>(null);
+ // Another brand starts unfiltered: its cards and types are its own.
+ const [filtersFor, setFiltersFor] = useState(activeBrandId);
+ if (filtersFor !== activeBrandId) {
+ setFiltersFor(activeBrandId);
+ setCard(null);
+ setMixType(null);
+ }
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect -- one read of the URL after mount
- setDays(Number(readUrlChoice('days', ['7', '30'], '30')) as PlanPeriod);
+ setDays(Number(readUrlChoice('days', ['7', '30', '90'], '30')) as PlanPeriod);
}, []);
useEffect(() => {
@@ -81,12 +102,39 @@ export default function ContentPlanPage() {
};
}, [activeBrandId, days, attempt]);
+ // Read again with the brand or the period only: a draft sent changes nothing in them.
+ useEffect(() => {
+ if (!activeBrandId || days === null) return;
+ let cancelled = false;
+ getContentPlanInsights(activeBrandId, days)
+ .then((data) => {
+ if (!cancelled) setInsights({ brandId: activeBrandId, days, data });
+ })
+ .catch((err) => {
+ // The list still works without them; the sections stay hidden.
+ console.error('Failed to load what AI cites for the content plan:', err);
+ if (!cancelled) setInsights({ brandId: activeBrandId, days, data: null });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [activeBrandId, days]);
+
// A read for another brand or period (just switched) counts as still loading.
const current = read?.brandId === activeBrandId && read.days === days ? read : null;
const plan = useMemo(
() => (current?.data ? buildPlan({ ...current.data, siteType }) : null),
[current, siteType],
);
+ const shown =
+ insights?.brandId === activeBrandId && insights.days === days ? insights.data : null;
+ const mix = useMemo(
+ () => (shown ? pageTypeMix(shown.citations, siteType, shown.totalCitations) : null),
+ [shown, siteType],
+ );
+ // A type picked in another period's mix filters only while this one lists it.
+ const typeFilter = mix?.rows.some((r) => r.pageType === mixType) ? mixType : null;
+ const earlier = current?.data ? earlierPeriod(current.data.answers, current.data.tracking) : null;
const changeDays = (next: PlanPeriod) => {
setDays(next);
@@ -115,7 +163,8 @@ export default function ContentPlanPage() {
);
}
- const rows = plan ? rowsFor(plan.rows, card) : [];
+ const rows = plan ? rowsFor(plan.rows, card, typeFilter) : [];
+ const filtered = card !== null || typeFilter !== null;
return (
<div className="space-y-6">
@@ -196,11 +245,35 @@ export default function ContentPlanPage() {
))}
</div>
+ {shown && current && <AiResultsStrip results={shown.results} days={current.days} />}
+ {mix && (
+ <PageTypeMix
+ rows={mix.rows}
+ covered={mix.covered}
+ selected={typeFilter}
+ onSelect={setMixType}
+ />
+ )}
+
<div className="space-y-2">
<div className="flex flex-wrap items-baseline justify-between gap-2">
<h2 className="text-sm font-medium">{t('listTitle')}</h2>
- <p className="text-xs text-muted-foreground">{card ? t('filtered') : t('ranked')}</p>
+ <p className="text-xs text-muted-foreground">{filtered ? t('filtered') : t('ranked')}</p>
</div>
+ {current?.data && earlier !== 'full' && earlier !== null && (
+ <p className="text-xs text-muted-foreground">
+ {t(earlier === 'none' ? 'earlier.none' : 'earlier.partial', {
+ days: current.days,
+ since: current.data.tracking.trackedSince
+ ? format.dateTime(new Date(`${current.data.tracking.trackedSince}T00:00:00Z`), {
+ month: 'short',
+ day: 'numeric',
+ timeZone: 'UTC',
+ })
+ : '—',
+ })}
+ </p>
+ )}
<Card className="py-0">
<CardContent className="px-0">
{current?.failed ? (
@@ -223,7 +296,7 @@ export default function ContentPlanPage() {
</div>
) : rows.length === 0 ? (
<p className="px-6 py-12 text-center text-sm text-muted-foreground">
- {card ? t('emptyFiltered') : t('empty')}
+ {filtered ? t('emptyFiltered') : t('empty')}
</p>
) : (
<PlanTable rows={rows} days={current?.days ?? 30} onStart={startRow} />
diff --git a/web/src/lib/actions/content-plan.test.ts b/web/src/lib/actions/content-plan.test.ts
index 521cb98f9..4ea3766ea 100644
--- a/web/src/lib/actions/content-plan.test.ts
+++ b/web/src/lib/actions/content-plan.test.ts
@@ -33,13 +33,18 @@ vi.mock('@/lib/supabase/server', () => ({
})),
}));
-const { getContentPlan } = await import('./content-plan');
+const getSuggestionSourceStates = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/actions/integrations', () => ({ getSuggestionSourceStates }));
+const GA_CONNECTED = { configured: true, connected: true, mapped: true, lastDataAt: '2026-10-20' };
+
+const { getContentPlan, getContentPlanInsights } = await import('./content-plan');
beforeEach(() => {
reads = {};
rpcResult = { days: 30, pages: [] };
rpcCalls = [];
filters = [];
+ getSuggestionSourceStates.mockReset().mockResolvedValue({ ga: GA_CONNECTED });
});
describe('getContentPlan', () => {
@@ -47,6 +52,8 @@ describe('getContentPlan', () => {
rpcResult = {
days: 7,
answers: { cur: 120, prev: 140 },
+ prevFrom: '2026-10-07',
+ trackedSince: '2026-09-09',
pages: [
{
page: 'https://acme.example/guides/espresso',
@@ -99,6 +106,7 @@ describe('getContentPlan', () => {
},
],
answers: { cur: 120, prev: 140 },
+ tracking: { prevFrom: '2026-10-07', trackedSince: '2026-09-09' },
opportunities: [
{
id: 'o1',
@@ -143,7 +151,50 @@ describe('getContentPlan', () => {
it('reads nothing of another organization’s brand, and refuses another period', async () => {
rpcResult = null;
await expect(getContentPlan(BRAND, 30)).resolves.toBeNull();
- await expect(getContentPlan(BRAND, 90 as 30)).rejects.toThrow('invalid');
+ await expect(getContentPlan(BRAND, 14 as 30)).rejects.toThrow('invalid');
await expect(getContentPlan('nope', 30)).rejects.toThrow('invalid');
});
});
+
+describe('getContentPlanInsights', () => {
+ it('reads what AI cites and what AI visits brought in', async () => {
+ rpcResult = {
+ days: 30,
+ totalCitations: 120,
+ citations: [
+ { url: 'https://acme.example/vs/hubspot', title: null, own: true, citations: '7' },
+ ],
+ results: { visits: 40, keyEvents: 5, analytics: true, purchases: false },
+ };
+ await expect(getContentPlanInsights(BRAND, 30)).resolves.toEqual({
+ totalCitations: 120,
+ citations: [{ url: 'https://acme.example/vs/hubspot', title: null, own: true, citations: 7 }],
+ results: {
+ visits: 40,
+ keyEvents: 5,
+ transactions: 0,
+ revenue: 0,
+ analytics: true,
+ purchases: false,
+ },
+ });
+ expect(rpcCalls).toEqual([['content_plan_insights', { p_brand_id: BRAND, p_days: 30 }]]);
+ });
+
+ it('counts Analytics as connected only as AI Traffic does: connected and synced', async () => {
+ rpcResult = { totalCitations: 0, citations: [], results: { analytics: true } };
+ getSuggestionSourceStates.mockResolvedValue({ ga: { ...GA_CONNECTED, lastDataAt: null } });
+ expect((await getContentPlanInsights(BRAND, 30))!.results.analytics).toBe(false);
+ getSuggestionSourceStates.mockResolvedValue({ ga: { ...GA_CONNECTED, connected: false } });
+ expect((await getContentPlanInsights(BRAND, 30))!.results.analytics).toBe(false);
+ // The connection can't be read: the property set says it.
+ getSuggestionSourceStates.mockRejectedValue(new Error('down'));
+ expect((await getContentPlanInsights(BRAND, 30))!.results.analytics).toBe(true);
+ });
+
+ it('reads nothing of another organization’s brand', async () => {
+ rpcResult = null;
+ await expect(getContentPlanInsights(BRAND, 7)).resolves.toBeNull();
+ await expect(getContentPlanInsights(BRAND, 14 as 7)).rejects.toThrow('invalid');
+ });
+});
diff --git a/web/src/lib/actions/content-plan.ts b/web/src/lib/actions/content-plan.ts
index 1d7c42bb7..6f198f12c 100644
--- a/web/src/lib/actions/content-plan.ts
+++ b/web/src/lib/actions/content-plan.ts
@@ -2,7 +2,9 @@
import { z } from 'zod';
import { createClient } from '@/lib/supabase/server';
+import { getSuggestionSourceStates } from '@/lib/actions/integrations';
import type { DraftMethod } from '@/lib/content/drafts';
+import type { CitedAddress, PlanResults } from '@/lib/content/plan-mix';
import {
PLAN_PERIODS,
type PlanAnswers,
@@ -10,7 +12,9 @@ import {
type PlanOpportunity,
type PlanPage,
type PlanPeriod,
+ type PlanTracking,
} from '@/lib/content/plan';
+import { googleSourceStatus } from '@/lib/traffic-sources';
/**
* What the Content plan (CE-014) is built from, read through the signed-in
@@ -26,7 +30,11 @@ const DRAFT_LIMIT = 500;
const planInput = z.object({
brandId: z.guid(),
- days: z.union(PLAN_PERIODS.map((d) => z.literal(d)) as [z.ZodLiteral<7>, z.ZodLiteral<30>]),
+ days: z.union([
+ z.literal(PLAN_PERIODS[0]),
+ z.literal(PLAN_PERIODS[1]),
+ z.literal(PLAN_PERIODS[2]),
+ ]),
});
const text = (value: unknown) => (typeof value === 'string' ? value.trim() : '');
@@ -37,6 +45,7 @@ export async function getContentPlan(
): Promise<{
pages: PlanPage[];
answers: PlanAnswers;
+ tracking: PlanTracking;
opportunities: PlanOpportunity[];
drafts: PlanDraft[];
} | null> {
@@ -68,11 +77,20 @@ export async function getContentPlan(
if (!pagesRes.data) return null;
const me = userRes.data.user?.id ?? null;
- const read = pagesRes.data as unknown as { pages?: PlanPage[]; answers?: Partial<PlanAnswers> };
+ const read = pagesRes.data as unknown as {
+ pages?: PlanPage[];
+ answers?: Partial<PlanAnswers>;
+ prevFrom?: string;
+ trackedSince?: string | null;
+ };
const answers = {
cur: Number(read.answers?.cur ?? 0),
prev: Number(read.answers?.prev ?? 0),
};
+ const tracking = {
+ prevFrom: read.prevFrom ?? null,
+ trackedSince: read.trackedSince ?? null,
+ };
const pages = (read.pages ?? []).map((p) => ({
page: p.page,
title: p.title ?? null,
@@ -115,5 +133,53 @@ export async function getContentPlan(
}),
);
- return { pages, answers, opportunities, drafts };
+ return { pages, answers, tracking, opportunities, drafts };
+}
+
+/**
+ * What AI cites in the brand's tracked answers, and what AI visits brought
+ * in, for the Plan's page-type mix and results strip (content_plan_insights,
+ * 00221). Analytics counts as connected as AI Traffic says it is: the
+ * property set, the connection live and data synced (googleSourceStatus).
+ * Null outside the member's organization.
+ */
+export async function getContentPlanInsights(
+ brandId: string,
+ days: PlanPeriod,
+): Promise<{ citations: CitedAddress[]; totalCitations: number; results: PlanResults } | null> {
+ if (!planInput.safeParse({ brandId, days }).success) throw new Error('invalid');
+ const supabase = await createClient();
+ const [{ data, error }, gaConnected] = 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,
+ ),
+ ]);
+ if (error) throw new Error(error.message);
+ if (!data) return null;
+ const read = data as unknown as {
+ totalCitations?: number;
+ citations?: CitedAddress[];
+ results?: Partial<PlanResults>;
+ };
+ const r = read.results ?? {};
+ return {
+ totalCitations: Number(read.totalCitations ?? 0),
+ citations: (read.citations ?? []).map((c) => ({
+ url: c.url,
+ title: c.title ?? null,
+ own: Boolean(c.own),
+ citations: Number(c.citations ?? 0),
+ })),
+ results: {
+ visits: Number(r.visits ?? 0),
+ keyEvents: Number(r.keyEvents ?? 0),
+ transactions: Number(r.transactions ?? 0),
+ revenue: Number(r.revenue ?? 0),
+ analytics: Boolean(r.analytics) && gaConnected !== false,
+ purchases: Boolean(r.purchases),
+ },
+ };
}
diff --git a/web/src/lib/content/plan-mix.test.ts b/web/src/lib/content/plan-mix.test.ts
new file mode 100644
index 000000000..89df3947f
--- /dev/null
+++ b/web/src/lib/content/plan-mix.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from 'vitest';
+import { pageTypeMix, type CitedAddress } from './plan-mix';
+
+/**
+ * "What AI cites in your topics" (CE-014): the share of AI citations by page
+ * type against the brand's own pages' mix, each of the citations whose type
+ * is known, and what share of all citations that is.
+ */
+
+const cited = (url: string, citations: number, over: Partial<CitedAddress> = {}): CitedAddress => ({
+ url,
+ title: null,
+ own: false,
+ citations,
+ ...over,
+});
+
+describe('pageTypeMix', () => {
+ it('sets AI’s mix by page type against the brand’s own pages’ mix, gaps flagged', () => {
+ const { rows, covered } = pageTypeMix(
+ [
+ cited('https://rival.example/compare/acme-vs-rival', 30),
+ cited('https://review.example/alternatives/crm', 10),
+ cited('https://acme.example/vs/hubspot', 5, { own: true }),
+ cited('https://acme.example/features/forecasting', 25, { own: true }),
+ cited('https://acme.example/features/email-sync/', 5, { own: true }),
+ cited('https://acme.example/pricing', 25, { own: true }),
+ // No type in the address or title: not in the whole.
+ cited('https://www.reddit.com/r/sales/comments/x', 40),
+ ],
+ 'b2b',
+ // The tail beyond the list: 60 more citations.
+ 200,
+ );
+ // AI: comparison 40, features 30, pricing 25 of 100 typed. The brand's
+ // own: comparison 5, features 30, pricing 25 of 60 (8%, 50%, 42%).
+ expect(rows).toEqual([
+ { pageType: 'comparison', aiShare: 45, yourShare: 8, pages: 1, gap: true },
+ { pageType: 'feature_page', aiShare: 30, yourShare: 50, pages: 2, gap: false },
+ { pageType: 'pricing', aiShare: 25, yourShare: 42, pages: 1, gap: false },
+ ]);
+ // 100 typed of the period's 200.
+ expect(covered).toBe(50);
+ });
+
+ it('reads another site’s /p/ or /products/ address by its title, not as a product page', () => {
+ const { rows } = pageTypeMix(
+ [
+ cited('https://writer.substack.com/p/my-coffee-notes', 10),
+ cited('https://blog.google/products/search/ai-mode', 10, { title: 'The best of AI Mode' }),
+ cited('https://shop.example/products/beans', 5, { own: true }),
+ ],
+ 'ecommerce',
+ 25,
+ );
+ expect(rows.map((r) => [r.pageType, r.aiShare])).toEqual([
+ ['best_of', 67],
+ ['product_page', 33],
+ ]);
+ });
+
+ it('reads a type from the title when the address has none, for the site’s own types', () => {
+ const { rows, covered } = pageTypeMix(
+ [
+ cited('https://blog.example/x/123', 4, { title: 'The 10 best coffee subscriptions' }),
+ cited('https://shop.example/products/beans', 6, { own: true }),
+ ],
+ 'ecommerce',
+ 10,
+ );
+ expect(rows).toEqual([
+ { pageType: 'product_page', aiShare: 60, yourShare: 100, pages: 1, gap: false },
+ { pageType: 'best_of', aiShare: 40, yourShare: 0, pages: 0, gap: true },
+ ]);
+ expect(covered).toBe(100);
+ });
+
+ it('has nothing to show without a cited page of a known type', () => {
+ expect(pageTypeMix([], 'ecommerce', 0)).toEqual({ rows: [], covered: 0 });
+ expect(pageTypeMix([cited('https://en.wikipedia.org/wiki/Coffee', 9)], 'ecommerce', 9)).toEqual(
+ { rows: [], covered: 0 },
+ );
+ });
+});
diff --git a/web/src/lib/content/plan-mix.ts b/web/src/lib/content/plan-mix.ts
new file mode 100644
index 000000000..b9aa7733e
--- /dev/null
+++ b/web/src/lib/content/plan-mix.ts
@@ -0,0 +1,122 @@
+/**
+ * "What AI cites in your topics" on the Content plan (CE-014, spec v2 §4):
+ * one row per page type of the brand's kind of site, with two mixes side by
+ * side: the share of AI citations in the brand's tracked answers going to
+ * that type of page, and the share of the brand's own cited pages' citations
+ * that type holds. A type AI leans on 10 points or more beyond the brand's
+ * own mix is a gap: AI cites it, the brand's cited pages don't cover it. The
+ * addresses come from content_plan_insights (00221): every own page and the
+ * others cited most; their type is read from the address and title, as the
+ * editor detects a page's (page-types.ts).
+ */
+
+import { SITE_PAGE_TYPES, detectPageType, type SiteType } from './page-types';
+import type { PageType } from './drafts';
+import { pageKey } from './sources';
+
+/** One cited address, as content_plan_insights returns it. */
+export interface CitedAddress {
+ url: string;
+ title: string | null;
+ /** One of the brand's own pages. */
+ own: boolean;
+ citations: number;
+}
+
+export interface MixRow {
+ pageType: PageType;
+ /** The type's share of the citations whose type is known, in whole percent. */
+ aiShare: number;
+ /** The type's share of the brand's own pages' citations whose type is known. */
+ yourShare: number;
+ /** The brand's pages of the type AI cited. */
+ pages: number;
+ /** AI leans on the type 10 points or more beyond the brand's own mix. */
+ gap: boolean;
+}
+
+export const GAP_POINTS = 10;
+
+/**
+ * A path sign written for the brand's own site that misreads others: a
+ * Substack or Instagram post (/p/…) or a blog's /products/ section isn't a
+ * product or feature page. Another site's address with it is typed by its
+ * title alone.
+ */
+const OWN_SITE_PATH = /\/(products?|p|dp|items?)\/[^/]+/;
+
+function pathOf(url: string): string {
+ try {
+ return new URL(url).pathname;
+ } catch {
+ return url;
+ }
+}
+
+/**
+ * The page types AI cites, the most cited first; types neither AI nor the
+ * brand cites are left out. The shares are of the addresses whose type can
+ * be read: `covered` says what share of all the period's citations
+ * (`totalCitations`, the long tail beyond the list included) that is, in
+ * whole percent. Forum threads, encyclopedia entries and the tail aren't in it.
+ */
+export function pageTypeMix(
+ cited: CitedAddress[],
+ siteType: SiteType,
+ totalCitations: number,
+): { rows: MixRow[]; covered: number } {
+ const types = SITE_PAGE_TYPES[siteType];
+ const byType = new Map<PageType, { all: number; own: number; pages: Set<string> }>();
+ let total = 0;
+ let ownTotal = 0;
+ let listed = 0;
+ for (const address of cited) {
+ if (address.citations <= 0) continue;
+ listed += address.citations;
+ const url = address.own || !OWN_SITE_PATH.test(pathOf(address.url)) ? address.url : null;
+ const type = detectPageType({ url, title: address.title }, siteType);
+ if (!type || !types.includes(type)) continue;
+ total += address.citations;
+ const entry = byType.get(type) ?? { all: 0, own: 0, pages: new Set<string>() };
+ entry.all += address.citations;
+ if (address.own) {
+ entry.own += address.citations;
+ ownTotal += address.citations;
+ entry.pages.add(pageKey(address.url) ?? address.url);
+ }
+ byType.set(type, entry);
+ }
+ const whole = Math.max(totalCitations, listed);
+ const covered = whole ? Math.round((total / whole) * 100) : 0;
+ if (!total) return { rows: [], covered };
+ const rows = types
+ .flatMap((pageType) => {
+ const entry = byType.get(pageType);
+ if (!entry) return [];
+ const aiShare = Math.round((entry.all / total) * 100);
+ const yourShare = ownTotal ? Math.round((entry.own / ownTotal) * 100) : 0;
+ return [
+ {
+ pageType,
+ aiShare,
+ yourShare,
+ pages: entry.pages.size,
+ gap: aiShare - yourShare >= GAP_POINTS,
+ },
+ ];
+ })
+ .sort((a, b) => b.aiShare - a.aiShare || b.yourShare - a.yourShare);
+ return { rows, covered };
+}
+
+/** What AI-referred visitors did on the site, as content_plan_insights reads it. */
+export interface PlanResults {
+ visits: number;
+ keyEvents: number;
+ transactions: number;
+ revenue: number;
+ /** Google Analytics is connected for the brand and has synced, as AI Traffic says. */
+ analytics: boolean;
+ /** The property reported purchases in the period. */
+ purchases: boolean;
+}
diff --git a/web/src/lib/content/plan.ts b/web/src/lib/content/plan.ts
index e9a6387d5..65febba6c 100644
--- a/web/src/lib/content/plan.ts
+++ b/web/src/lib/content/plan.ts
@@ -13,7 +13,8 @@ import { detectPageType, type SiteType } from './page-types';
import type { DraftMethod, PageType } from './drafts';
import { pageKey } from './sources';
-export const PLAN_PERIODS = [7, 30] as const;
+/** The Plan's periods: a week, a month, a quarter. */
+export const PLAN_PERIODS = [7, 30, 90] as const;
export type PlanPeriod = (typeof PLAN_PERIODS)[number];
export type PlanAction = 'create' | 'optimize' | 'protect';
@@ -27,6 +28,16 @@ export interface PlanAnswers {
prev: number;
}
+/**
+ * When the brand's tracking began, against the earlier period's first day
+ * (UTC dates): an earlier period before it is only partly tracked, or not
+ * at all, so pages are compared per answer, or not at all.
+ */
+export interface PlanTracking {
+ prevFrom: string | null;
+ trackedSince: string | null;
+}
+
/** One of the brand's pages, as content_plan_pages (00220) reads it. */
export interface PlanPage {
page: string;
@@ -259,14 +270,35 @@ export function buildPlan({
};
}
-/** The rows a card shows, the first MAX_ROWS: its action's, or the pages competing; all without a card. */
-export function rowsFor(rows: PlanRow[], card: PlanCard | null): PlanRow[] {
- const shown = !card
- ? rows
- : card === 'overlaps'
- ? rows.filter((r) => r.overlaps > 0)
- : rows.filter((r) => r.action === card);
- return shown.slice(0, MAX_ROWS);
+/**
+ * The rows a card shows, the first MAX_ROWS: its action's, or the pages
+ * competing; all without a card. A page type (the mix's filter) narrows them
+ * before the cut, so its rows are never cut off by others.
+ */
+export function rowsFor(
+ rows: PlanRow[],
+ card: PlanCard | null,
+ pageType: PageType | null = null,
+): PlanRow[] {
+ return rows
+ .filter(
+ (r) =>
+ (!card || (card === 'overlaps' ? r.overlaps > 0 : r.action === card)) &&
+ (!pageType || r.pageType === pageType),
+ )
+ .slice(0, MAX_ROWS);
+}
+
+/** Whether the earlier period was tracked in full, partly, or not at all. */
+export function earlierPeriod(
+ answers: PlanAnswers,
+ tracking: PlanTracking,
+): 'full' | 'partial' | 'none' {
+ if (answers.prev <= 0) return 'none';
+ if (tracking.prevFrom && tracking.trackedSince && tracking.trackedSince > tracking.prevFrom) {
+ return 'partial';
+ }
+ return 'full';
}
/**
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index e14513d12..adac6e552 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -3670,6 +3670,10 @@ export type Database = {
Args: { p_brand_id: string; p_days: number; p_page: string }
Returns: Json
}
+ content_plan_insights: {
+ Args: { p_brand_id: string; p_days?: number }
+ Returns: Json
+ }
content_plan_pages: {
Args: { p_brand_id: string; p_days?: number }
Returns: Json