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(action-center): store Getting started per brand and work out its steps from the brand's data (#1234)

Cihan068589834d8e
diff --git a/supabase/migrations/00196_getting_started.sql b/supabase/migrations/00196_getting_started.sql
new file mode 100644
index 000000000..7130339b2
--- /dev/null
+++ b/supabase/migrations/00196_getting_started.sql
@@ -0,0 +1,272 @@
+-- ============================================================================
+-- 00196: Getting started, per brand (New Ansvisor, AC-ALT2 §4)
+-- ============================================================================
+-- Getting started is a fixed set of 17 steps in the Actions page. It walks a
+-- brand through setup (KPIs, competitors, topics, prompts, Search Console,
+-- Analytics, the AI Traffic snippet), a first look at the analytics pages and
+-- its first content. It sits beside the Action Center's generated actions
+-- and never touches them: no signal, no Priority Score, no row in actions.
+--
+-- Most steps are done when the brand's own data says so (3 competitors, a
+-- first AI visit, a finished audit…), so only what the data can't tell is
+-- stored here:
+--
+-- * getting_started: one row per brand that runs it. Every brand created
+-- from now on gets one (trigger below). An existing brand has none until
+-- someone starts it from the Actions page. dismissed_at: skipped.
+-- * getting_started_steps: what a person did that leaves no other trace.
+-- They opened one of the analytics pages after the first answers came in
+-- (the explore steps), skipped an optional step, or saved the KPIs from
+-- the KPI screen. The ready-made KPIs (00163) appear on a visit, so they
+-- don't count as set.
+--
+-- getting_started_facts reads everything the step list needs in one call;
+-- the web turns it into the 17 steps (web/src/lib/getting-started/steps.ts).
+
+create table if not exists public.getting_started (
+ brand_id uuid primary key references public.brands(id) on delete cascade,
+ started_at timestamptz not null default now(),
+ dismissed_at timestamptz
+);
+
+comment on table public.getting_started is
+ 'Getting started (AC-ALT2): brands that run the setup steps in the Actions page. dismissed_at = skipped.';
+
+create table if not exists public.getting_started_steps (
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ -- A step key from the web's list. Not an enum: a new step must not take a
+ -- migration.
+ step text not null check (step ~ '^[a-z_]{1,40}$'),
+ state text not null check (state in ('opened', 'skipped', 'done')),
+ updated_at timestamptz not null default now(),
+ primary key (brand_id, step)
+);
+
+comment on table public.getting_started_steps is
+ 'Getting started (AC-ALT2): steps a person finished that the brand''s data can''t show (a page opened, a step skipped, KPIs saved).';
+
+alter table public.getting_started enable row level security;
+alter table public.getting_started_steps enable row level security;
+
+create policy "getting_started: member select"
+ on public.getting_started
+ for select
+ using (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+create policy "getting_started_steps: member select"
+ on public.getting_started_steps
+ for select
+ using (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+-- Any member records a page they opened; skipping a step or marking one
+-- done is for admins and managers, who set the steps up (as kpi_definitions'
+-- and getting_started's writes).
+create policy "getting_started_steps: member insert"
+ on public.getting_started_steps
+ for insert
+ with check (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ and (
+ state = 'opened'
+ or exists (
+ select 1 from public.profiles p
+ where p.id = auth.uid()
+ and p.role = any (array['admin'::public.user_role, 'manager'::public.user_role])
+ )
+ )
+ );
+
+create policy "getting_started_steps: member update"
+ on public.getting_started_steps
+ for update
+ using (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ )
+ with check (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ and (
+ state = 'opened'
+ or exists (
+ select 1 from public.profiles p
+ where p.id = auth.uid()
+ and p.role = any (array['admin'::public.user_role, 'manager'::public.user_role])
+ )
+ )
+ );
+
+-- A new brand runs Getting started. Whoever adds it (onboarding, the brands
+-- page, the API), its row is here before anyone opens the Actions page.
+create or replace function public.start_brand_getting_started()
+returns trigger
+language plpgsql
+security definer
+set search_path to 'public'
+as $$
+begin
+ insert into public.getting_started (brand_id)
+ values (new.id)
+ on conflict (brand_id) do nothing;
+ return new;
+end;
+$$;
+
+revoke all on function public.start_brand_getting_started() from public, anon, authenticated;
+
+drop trigger if exists trg_brands_start_getting_started on public.brands;
+create trigger trg_brands_start_getting_started
+ after insert on public.brands
+ for each row execute function public.start_brand_getting_started();
+
+-- An explore step is done when its page was opened once the brand's first
+-- answers are in: opened before them, the page had nothing to show. True when
+-- the step is recorded (now or earlier).
+create or replace function public.getting_started_page_opened(p_brand_id uuid, p_step text)
+returns boolean
+language plpgsql
+security invoker
+set search_path to 'public'
+as $$
+begin
+ if exists (select 1 from public.prompt_results r where r.brand_id = p_brand_id) then
+ insert into public.getting_started_steps (brand_id, step, state)
+ values (p_brand_id, p_step, 'opened')
+ on conflict (brand_id, step) do nothing;
+ end if;
+ return exists (
+ select 1 from public.getting_started_steps s
+ where s.brand_id = p_brand_id and s.step = p_step
+ );
+end;
+$$;
+
+revoke all on function public.getting_started_page_opened(uuid, text) from public, anon;
+grant execute on function public.getting_started_page_opened(uuid, text) to authenticated;
+
+-- Everything the step list reads, for one brand. Security invoker: RLS
+-- decides the brand, and a brand the caller can't see returns null.
+create or replace function public.getting_started_facts(p_brand_id uuid)
+returns jsonb
+language sql
+stable
+security invoker
+set search_path to 'public'
+as $$
+ select jsonb_build_object(
+ 'started_at', gs.started_at,
+ 'dismissed_at', gs.dismissed_at,
+ 'steps', coalesce((
+ select jsonb_object_agg(s.step, jsonb_build_object('state', s.state, 'at', s.updated_at))
+ from public.getting_started_steps s
+ where s.brand_id = p_brand_id
+ ), '{}'::jsonb),
+ 'kpi_setup_at', b.kpi_setup_at,
+ 'competitors', (
+ select count(*) from public.competitors c where c.brand_id = p_brand_id
+ ),
+ -- Active prompts in each active topic, oldest topic first.
+ 'topic_prompts', coalesce((
+ select jsonb_agg(n.prompts order by t.created_at, t.id)
+ from public.topics t
+ cross join lateral (
+ select count(*) as prompts
+ from public.prompts p
+ join public.prompt_sets ps on ps.id = p.prompt_set_id
+ where p.topic_id = t.id
+ and p.is_active
+ and ps.brand_id = p_brand_id
+ ) n
+ where t.brand_id = p_brand_id
+ and t.is_active
+ ), '[]'::jsonb),
+ -- Connected for the organization and mapped to a property for the brand,
+ -- as Settings › Integrations shows it.
+ 'gsc', nullif(b.gsc_property, '') is not null and exists (
+ select 1 from public.integration_connections ic
+ where ic.organization_id = b.organization_id
+ and ic.provider = 'google-search-console'
+ and ic.status = 'connected'
+ ),
+ 'ga', nullif(b.ga_property_id, '') is not null and exists (
+ select 1 from public.integration_connections ic
+ where ic.organization_id = b.organization_id
+ and ic.provider = 'google-analytics'
+ and ic.status = 'connected'
+ ),
+ 'first_answer', exists (
+ select 1 from public.prompt_results r where r.brand_id = p_brand_id
+ ),
+ 'first_visit', exists (
+ select 1 from public.ai_traffic_logs l where l.brand_id = p_brand_id
+ ),
+ -- Prompt suggestions built from Search Console and Analytics data.
+ 'data_suggestions', (
+ select count(*) from public.prompt_suggestions s
+ where s.brand_id = p_brand_id and s.source in ('gsc', 'ga')
+ ),
+ 'data_tracked', (
+ select count(*) from public.prompt_suggestions s
+ where s.brand_id = p_brand_id and s.source in ('gsc', 'ga') and s.status = 'added'
+ ),
+ 'content_suggestions', (
+ select count(*) from public.content_opportunities o where o.brand_id = p_brand_id
+ ),
+ -- Picked: reviewed, sent to the Action Center or given a brief (00106).
+ 'content_picked', (
+ select count(*) from public.content_opportunities o
+ where o.brand_id = p_brand_id
+ and (o.status in ('reviewed', 'sent', 'in_progress', 'done') or o.brief is not null)
+ ),
+ -- Created: its work was completed, or it went to the CMS webhook. There
+ -- is no published state until the Content Editor.
+ 'content_created', (
+ select count(*) from public.content_opportunities o
+ where o.brand_id = p_brand_id
+ and (o.status = 'done' or o.webhook_sent_at is not null)
+ ),
+ -- Audits a person ran (not the automatic sweep, 00167) that finished.
+ 'audits', (
+ select count(*) from public.site_audits a
+ where a.brand_id = p_brand_id and a.source = 'user' and a.status = 'completed'
+ )
+ )
+ from public.brands b
+ left join public.getting_started gs on gs.brand_id = b.id
+ where b.id = p_brand_id;
+$$;
+
+revoke all on function public.getting_started_facts(uuid) from public, anon;
+grant execute on function public.getting_started_facts(uuid) to authenticated;
+
+comment on function public.getting_started_facts(uuid) is
+ 'Getting started (AC-ALT2): the counts and flags the 17 steps read, for one brand. Security invoker: RLS decides the brand.';
+
+notify pgrst, 'reload schema';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 5c61b07b3..dc8e48110 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -26624,6 +26624,282 @@ comment on function public.ai_traffic_platforms_seen(uuid, timestamptz, text[])
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00196_getting_started.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00196: Getting started, per brand (New Ansvisor, AC-ALT2 §4)
+-- ============================================================================
+-- Getting started is a fixed set of 17 steps in the Actions page. It walks a
+-- brand through setup (KPIs, competitors, topics, prompts, Search Console,
+-- Analytics, the AI Traffic snippet), a first look at the analytics pages and
+-- its first content. It sits beside the Action Center's generated actions
+-- and never touches them: no signal, no Priority Score, no row in actions.
+--
+-- Most steps are done when the brand's own data says so (3 competitors, a
+-- first AI visit, a finished audit…), so only what the data can't tell is
+-- stored here:
+--
+-- * getting_started: one row per brand that runs it. Every brand created
+-- from now on gets one (trigger below). An existing brand has none until
+-- someone starts it from the Actions page. dismissed_at: skipped.
+-- * getting_started_steps: what a person did that leaves no other trace.
+-- They opened one of the analytics pages after the first answers came in
+-- (the explore steps), skipped an optional step, or saved the KPIs from
+-- the KPI screen. The ready-made KPIs (00163) appear on a visit, so they
+-- don't count as set.
+--
+-- getting_started_facts reads everything the step list needs in one call;
+-- the web turns it into the 17 steps (web/src/lib/getting-started/steps.ts).
+
+create table if not exists public.getting_started (
+ brand_id uuid primary key references public.brands(id) on delete cascade,
+ started_at timestamptz not null default now(),
+ dismissed_at timestamptz
+);
+
+comment on table public.getting_started is
+ 'Getting started (AC-ALT2): brands that run the setup steps in the Actions page. dismissed_at = skipped.';
+
+create table if not exists public.getting_started_steps (
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ -- A step key from the web's list. Not an enum: a new step must not take a
+ -- migration.
+ step text not null check (step ~ '^[a-z_]{1,40}$'),
+ state text not null check (state in ('opened', 'skipped', 'done')),
+ updated_at timestamptz not null default now(),
+ primary key (brand_id, step)
+);
+
+comment on table public.getting_started_steps is
+ 'Getting started (AC-ALT2): steps a person finished that the brand''s data can''t show (a page opened, a step skipped, KPIs saved).';
+
+alter table public.getting_started enable row level security;
+alter table public.getting_started_steps enable row level security;
+
+create policy "getting_started: member select"
+ on public.getting_started
+ for select
+ using (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+create policy "getting_started_steps: member select"
+ on public.getting_started_steps
+ for select
+ using (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+-- Any member records a page they opened; skipping a step or marking one
+-- done is for admins and managers, who set the steps up (as kpi_definitions'
+-- and getting_started's writes).
+create policy "getting_started_steps: member insert"
+ on public.getting_started_steps
+ for insert
+ with check (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ and (
+ state = 'opened'
+ or exists (
+ select 1 from public.profiles p
+ where p.id = auth.uid()
+ and p.role = any (array['admin'::public.user_role, 'manager'::public.user_role])
+ )
+ )
+ );
+
+create policy "getting_started_steps: member update"
+ on public.getting_started_steps
+ for update
+ using (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ )
+ with check (
+ brand_id in (
+ select b.id
+ from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ and (
+ state = 'opened'
+ or exists (
+ select 1 from public.profiles p
+ where p.id = auth.uid()
+ and p.role = any (array['admin'::public.user_role, 'manager'::public.user_role])
+ )
+ )
+ );
+
+-- A new brand runs Getting started. Whoever adds it (onboarding, the brands
+-- page, the API), its row is here before anyone opens the Actions page.
+create or replace function public.start_brand_getting_started()
+returns trigger
+language plpgsql
+security definer
+set search_path to 'public'
+as $$
+begin
+ insert into public.getting_started (brand_id)
+ values (new.id)
+ on conflict (brand_id) do nothing;
+ return new;
+end;
+$$;
+
+revoke all on function public.start_brand_getting_started() from public, anon, authenticated;
+
+drop trigger if exists trg_brands_start_getting_started on public.brands;
+create trigger trg_brands_start_getting_started
+ after insert on public.brands
+ for each row execute function public.start_brand_getting_started();
+
+-- An explore step is done when its page was opened once the brand's first
+-- answers are in: opened before them, the page had nothing to show. True when
+-- the step is recorded (now or earlier).
+create or replace function public.getting_started_page_opened(p_brand_id uuid, p_step text)
+returns boolean
+language plpgsql
+security invoker
+set search_path to 'public'
+as $$
+begin
+ if exists (select 1 from public.prompt_results r where r.brand_id = p_brand_id) then
+ insert into public.getting_started_steps (brand_id, step, state)
+ values (p_brand_id, p_step, 'opened')
+ on conflict (brand_id, step) do nothing;
+ end if;
+ return exists (
+ select 1 from public.getting_started_steps s
+ where s.brand_id = p_brand_id and s.step = p_step
+ );
+end;
+$$;
+
+revoke all on function public.getting_started_page_opened(uuid, text) from public, anon;
+grant execute on function public.getting_started_page_opened(uuid, text) to authenticated;
+
+-- Everything the step list reads, for one brand. Security invoker: RLS
+-- decides the brand, and a brand the caller can't see returns null.
+create or replace function public.getting_started_facts(p_brand_id uuid)
+returns jsonb
+language sql
+stable
+security invoker
+set search_path to 'public'
+as $$
+ select jsonb_build_object(
+ 'started_at', gs.started_at,
+ 'dismissed_at', gs.dismissed_at,
+ 'steps', coalesce((
+ select jsonb_object_agg(s.step, jsonb_build_object('state', s.state, 'at', s.updated_at))
+ from public.getting_started_steps s
+ where s.brand_id = p_brand_id
+ ), '{}'::jsonb),
+ 'kpi_setup_at', b.kpi_setup_at,
+ 'competitors', (
+ select count(*) from public.competitors c where c.brand_id = p_brand_id
+ ),
+ -- Active prompts in each active topic, oldest topic first.
+ 'topic_prompts', coalesce((
+ select jsonb_agg(n.prompts order by t.created_at, t.id)
+ from public.topics t
+ cross join lateral (
+ select count(*) as prompts
+ from public.prompts p
+ join public.prompt_sets ps on ps.id = p.prompt_set_id
+ where p.topic_id = t.id
+ and p.is_active
+ and ps.brand_id = p_brand_id
+ ) n
+ where t.brand_id = p_brand_id
+ and t.is_active
+ ), '[]'::jsonb),
+ -- Connected for the organization and mapped to a property for the brand,
+ -- as Settings › Integrations shows it.
+ 'gsc', nullif(b.gsc_property, '') is not null and exists (
+ select 1 from public.integration_connections ic
+ where ic.organization_id = b.organization_id
+ and ic.provider = 'google-search-console'
+ and ic.status = 'connected'
+ ),
+ 'ga', nullif(b.ga_property_id, '') is not null and exists (
+ select 1 from public.integration_connections ic
+ where ic.organization_id = b.organization_id
+ and ic.provider = 'google-analytics'
+ and ic.status = 'connected'
+ ),
+ 'first_answer', exists (
+ select 1 from public.prompt_results r where r.brand_id = p_brand_id
+ ),
+ 'first_visit', exists (
+ select 1 from public.ai_traffic_logs l where l.brand_id = p_brand_id
+ ),
+ -- Prompt suggestions built from Search Console and Analytics data.
+ 'data_suggestions', (
+ select count(*) from public.prompt_suggestions s
+ where s.brand_id = p_brand_id and s.source in ('gsc', 'ga')
+ ),
+ 'data_tracked', (
+ select count(*) from public.prompt_suggestions s
+ where s.brand_id = p_brand_id and s.source in ('gsc', 'ga') and s.status = 'added'
+ ),
+ 'content_suggestions', (
+ select count(*) from public.content_opportunities o where o.brand_id = p_brand_id
+ ),
+ -- Picked: reviewed, sent to the Action Center or given a brief (00106).
+ 'content_picked', (
+ select count(*) from public.content_opportunities o
+ where o.brand_id = p_brand_id
+ and (o.status in ('reviewed', 'sent', 'in_progress', 'done') or o.brief is not null)
+ ),
+ -- Created: its work was completed, or it went to the CMS webhook. There
+ -- is no published state until the Content Editor.
+ 'content_created', (
+ select count(*) from public.content_opportunities o
+ where o.brand_id = p_brand_id
+ and (o.status = 'done' or o.webhook_sent_at is not null)
+ ),
+ -- Audits a person ran (not the automatic sweep, 00167) that finished.
+ 'audits', (
+ select count(*) from public.site_audits a
+ where a.brand_id = p_brand_id and a.source = 'user' and a.status = 'completed'
+ )
+ )
+ from public.brands b
+ left join public.getting_started gs on gs.brand_id = b.id
+ where b.id = p_brand_id;
+$$;
+
+revoke all on function public.getting_started_facts(uuid) from public, anon;
+grant execute on function public.getting_started_facts(uuid) to authenticated;
+
+comment on function public.getting_started_facts(uuid) is
+ 'Getting started (AC-ALT2): the counts and flags the 17 steps read, for one brand. Security invoker: RLS decides the brand.';
+
+notify pgrst, 'reload schema';
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00198_webhook_event_subscriptions.sql
-- ─────────────────────────────────────────────────────────────────────────
diff --git a/web/src/app/[locale]/(dashboard)/layout.tsx b/web/src/app/[locale]/(dashboard)/layout.tsx
index 8c889f994..abdfbea02 100644
--- a/web/src/app/[locale]/(dashboard)/layout.tsx
+++ b/web/src/app/[locale]/(dashboard)/layout.tsx
@@ -8,6 +8,7 @@ import { PlanProvider } from '@/components/providers/plan-provider';
import { RoleProvider, type TeamRole } from '@/components/providers/role-provider';
import { BrandLoader } from '@/components/providers/brand-loader';
import { BrandGuard } from '@/components/providers/brand-guard';
+import { GettingStartedPageOpened } from '@/components/getting-started/page-opened';
import { getBrands } from '@/lib/actions/brand';
import { getPlan, isCloud, type PlanId } from '@/config/plans';
import { evaluateSubscriptionAccess } from '@/lib/billing/subscription-access';
@@ -83,6 +84,7 @@ export default async function DashboardLayout({ children }: { children: React.Re
<>
<AuthProvider user={user} />
<BrandLoader brands={brands} />
+ <GettingStartedPageOpened />
<PlanProvider planId={planId} allowedModelIds={allowedModelIds}>
<RoleProvider role={role}>
<div className="flex h-screen overflow-hidden">
diff --git a/web/src/components/getting-started/page-opened.test.tsx b/web/src/components/getting-started/page-opened.test.tsx
new file mode 100644
index 000000000..02bb76a5a
--- /dev/null
+++ b/web/src/components/getting-started/page-opened.test.tsx
@@ -0,0 +1,95 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Getting started's explore steps are done when their page is opened. The
+ * layout asks the server once per brand and step, until it records it.
+ */
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const { markGettingStartedPageOpened, nav } = vi.hoisted(() => ({
+ markGettingStartedPageOpened: vi.fn(),
+ nav: { pathname: '/dashboard/mentions', brandId: 'b1' as string | null },
+}));
+
+vi.mock('@/i18n/navigation', () => ({ usePathname: () => nav.pathname }));
+vi.mock('@/stores/use-brand-store', () => ({
+ useBrandStore: (selector: (state: { activeBrandId: string | null }) => unknown) =>
+ selector({ activeBrandId: nav.brandId }),
+}));
+vi.mock('@/lib/actions/getting-started', () => ({ markGettingStartedPageOpened }));
+
+const { GettingStartedPageOpened } = await import('./page-opened');
+
+// An in-memory localStorage: the test environment has none.
+const store = new Map<string, string>();
+Object.defineProperty(window, 'localStorage', {
+ configurable: true,
+ value: {
+ getItem: (key: string) => store.get(key) ?? null,
+ setItem: (key: string, value: string) => void store.set(key, value),
+ removeItem: (key: string) => void store.delete(key),
+ clear: () => store.clear(),
+ },
+});
+
+let container: HTMLDivElement;
+let root: Root;
+
+async function render() {
+ await act(async () => root.render(<GettingStartedPageOpened />));
+}
+
+beforeEach(() => {
+ localStorage.clear();
+ markGettingStartedPageOpened.mockReset();
+ nav.pathname = '/dashboard/mentions';
+ nav.brandId = 'b1';
+ container = document.createElement('div');
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+});
+
+describe('GettingStartedPageOpened', () => {
+ it('records an explore page once, then remembers it in this browser', async () => {
+ markGettingStartedPageOpened.mockResolvedValue(true);
+ await render();
+ expect(markGettingStartedPageOpened).toHaveBeenCalledWith('b1', 'mentions');
+ expect(localStorage.getItem('aeo:getting-started:b1:mentions')).toBe('1');
+
+ act(() => root.unmount());
+ root = createRoot(container);
+ await render();
+ expect(markGettingStartedPageOpened).toHaveBeenCalledTimes(1);
+ });
+
+ it('asks again next time when the server did not record it (no answers yet)', async () => {
+ markGettingStartedPageOpened.mockResolvedValue(false);
+ await render();
+ expect(localStorage.getItem('aeo:getting-started:b1:mentions')).toBeNull();
+ });
+
+ it('leaves other pages, and a missing brand, alone', async () => {
+ nav.pathname = '/dashboard/action-center/actions';
+ await render();
+ nav.pathname = '/dashboard/mentions';
+ nav.brandId = null;
+ await render();
+ expect(markGettingStartedPageOpened).not.toHaveBeenCalled();
+ });
+
+ it('keeps the page working when the server call fails', async () => {
+ markGettingStartedPageOpened.mockRejectedValue(new Error('offline'));
+ await render();
+ expect(localStorage.getItem('aeo:getting-started:b1:mentions')).toBeNull();
+ });
+});
diff --git a/web/src/components/getting-started/page-opened.tsx b/web/src/components/getting-started/page-opened.tsx
new file mode 100644
index 000000000..364fdefb2
--- /dev/null
+++ b/web/src/components/getting-started/page-opened.tsx
@@ -0,0 +1,44 @@
+'use client';
+
+import { useEffect } from 'react';
+import { usePathname } from '@/i18n/navigation';
+import { useBrandStore } from '@/stores/use-brand-store';
+import { markGettingStartedPageOpened } from '@/lib/actions/getting-started';
+import { pageOpenedStep } from '@/lib/getting-started/steps';
+
+/**
+ * Getting started's explore steps ("See where you stand in Visibility" and
+ * the like) are done when their page is opened. Mounted once in the
+ * dashboard layout, so it counts the page however it was reached: the step's
+ * button, the sidebar or a link. Each brand and step is sent until the
+ * server records it, then remembered in this browser.
+ */
+export function GettingStartedPageOpened() {
+ const pathname = usePathname();
+ const brandId = useBrandStore((s) => s.activeBrandId);
+
+ useEffect(() => {
+ const step = pageOpenedStep(pathname);
+ if (!step || !brandId) return;
+ const key = `aeo:getting-started:${brandId}:${step}`;
+ try {
+ if (localStorage.getItem(key)) return;
+ } catch {
+ // Storage blocked: ask the server, which keeps it once.
+ }
+ markGettingStartedPageOpened(brandId, step)
+ .then((recorded) => {
+ if (!recorded) return;
+ try {
+ localStorage.setItem(key, '1');
+ } catch {
+ // Nothing to remember it in; the next visit asks again.
+ }
+ })
+ .catch(() => {
+ // A database without 00196, or offline: the step stays open.
+ });
+ }, [pathname, brandId]);
+
+ return null;
+}
diff --git a/web/src/lib/actions/getting-started.ts b/web/src/lib/actions/getting-started.ts
new file mode 100644
index 000000000..3fcbbdb3c
--- /dev/null
+++ b/web/src/lib/actions/getting-started.ts
@@ -0,0 +1,60 @@
+'use server';
+
+/**
+ * Getting started (New Ansvisor, AC-ALT2 §4): the 17 setup steps in the
+ * Actions page. Reads the brand's facts in one call (getting_started_facts,
+ * 00196) and turns them into steps in lib/getting-started/steps.ts; stores
+ * only what the data can't show — a page opened, an optional step skipped.
+ */
+
+import { createClient } from '@/lib/supabase/server';
+import {
+ GETTING_STARTED_STEPS,
+ buildGettingStarted,
+ isPageOpenedStep,
+ parseGettingStartedFacts,
+ type GettingStartedStatus,
+} from '@/lib/getting-started/steps';
+
+/** The brand's steps, or null for a brand the caller can't see. */
+export async function getGettingStarted(brandId: string): Promise<GettingStartedStatus | null> {
+ const supabase = await createClient();
+ const { data, error } = await supabase.rpc('getting_started_facts', { p_brand_id: brandId });
+ if (error) throw new Error(error.message);
+ const facts = parseGettingStartedFacts(data);
+ return facts ? buildGettingStarted(facts) : null;
+}
+
+/**
+ * One of the explore pages was opened. Recorded once the brand's first
+ * answers are in, so a page opened while it had nothing to show doesn't
+ * count. True when the step is recorded, now or before.
+ */
+export async function markGettingStartedPageOpened(
+ brandId: string,
+ step: string,
+): Promise<boolean> {
+ if (!isPageOpenedStep(step)) throw new Error('not a page step');
+ const supabase = await createClient();
+ const { data, error } = await supabase.rpc('getting_started_page_opened', {
+ p_brand_id: brandId,
+ p_step: step,
+ });
+ if (error) throw new Error(error.message);
+ return data === true;
+}
+
+/** Skip an optional step (Search Console, Analytics). It counts as complete. */
+export async function skipGettingStartedStep(brandId: string, step: string): Promise<void> {
+ if (!GETTING_STARTED_STEPS.some((s) => s.key === step && s.optional)) {
+ throw new Error('not an optional step');
+ }
+ const supabase = await createClient();
+ const { error } = await supabase
+ .from('getting_started_steps')
+ .upsert(
+ { brand_id: brandId, step, state: 'skipped', updated_at: new Date().toISOString() },
+ { onConflict: 'brand_id,step' },
+ );
+ if (error) throw new Error(error.message);
+}
diff --git a/web/src/lib/actions/kpis.ts b/web/src/lib/actions/kpis.ts
index dbaa349b9..a84dbe519 100644
--- a/web/src/lib/actions/kpis.ts
+++ b/web/src/lib/actions/kpis.ts
@@ -445,6 +445,17 @@ export async function saveKpiFramework(
.eq('brand_id', brandId)
.not('kpi_key', 'in', `(${entries.map((e) => e.key).join(',')})`);
if (deactivateErr) throw new Error(deactivateErr.message);
+
+ // Getting started's KPI step (00196). The ready-made set appears on a visit
+ // to the KPI tab, so only a save from here counts. The KPIs are saved
+ // either way; a failed mark only leaves the step open.
+ const { error: stepErr } = await supabase
+ .from('getting_started_steps')
+ .upsert(
+ { brand_id: brandId, step: 'kpis', state: 'done', updated_at: now },
+ { onConflict: 'brand_id,step' },
+ );
+ if (stepErr) console.error('[getting-started] KPI step not marked:', stepErr.message);
}
/**
diff --git a/web/src/lib/getting-started/steps.test.ts b/web/src/lib/getting-started/steps.test.ts
new file mode 100644
index 000000000..96e866e2d
--- /dev/null
+++ b/web/src/lib/getting-started/steps.test.ts
@@ -0,0 +1,319 @@
+import { describe, expect, it } from 'vitest';
+import {
+ GETTING_STARTED_STEPS,
+ buildGettingStarted,
+ isPageOpenedStep,
+ pageOpenedStep,
+ parseGettingStartedFacts,
+ type GettingStartedFacts,
+ type GettingStartedStepKey,
+} from './steps';
+
+/**
+ * Getting started (AC-ALT2 §4): seventeen fixed steps whose state follows
+ * from the brand's data. Steps unlock when their data is ready, optional
+ * steps can be skipped, and Ready waits for everything above it.
+ */
+
+const facts = (over: Partial<GettingStartedFacts> = {}): GettingStartedFacts => ({
+ startedAt: '2026-10-20T10:00:00Z',
+ dismissedAt: null,
+ records: {},
+ recordedAt: {},
+ kpiSetupAt: null,
+ competitors: 0,
+ topicPrompts: [],
+ gsc: false,
+ ga: false,
+ firstAnswer: false,
+ firstVisit: false,
+ dataSuggestions: 0,
+ dataTracked: 0,
+ contentSuggestions: 0,
+ contentPicked: 0,
+ contentCreated: 0,
+ audits: 0,
+ ...over,
+});
+
+const step = (f: GettingStartedFacts, key: GettingStartedStepKey) =>
+ buildGettingStarted(f).steps.find((s) => s.key === key)!;
+
+describe('the step list', () => {
+ it('has the seventeen steps in order, by stage', () => {
+ expect(GETTING_STARTED_STEPS.map((s) => `${s.stage}:${s.key}`)).toEqual([
+ 'setup:kpis',
+ 'setup:competitors',
+ 'setup:topics',
+ 'setup:prompts',
+ 'setup:gsc',
+ 'setup:ga',
+ 'setup:snippet',
+ 'explore:visibility',
+ 'explore:answers',
+ 'explore:data_prompts',
+ 'explore:mentions',
+ 'explore:citations',
+ 'explore:traffic',
+ 'act:pick_content',
+ 'act:create_content',
+ 'act:optimize_page',
+ 'ready:ready',
+ ]);
+ expect(GETTING_STARTED_STEPS.filter((s) => s.optional).map((s) => s.key)).toEqual([
+ 'gsc',
+ 'ga',
+ ]);
+ });
+});
+
+describe('buildGettingStarted', () => {
+ it('opens a new brand on the setup steps, with the rest waiting for data', () => {
+ const status = buildGettingStarted(facts());
+ expect(status.active).toBe(true);
+ expect(status.total).toBe(17);
+ expect(status.done).toBe(0);
+ const states = Object.fromEntries(status.steps.map((s) => [s.key, s.state]));
+ expect(states).toEqual({
+ kpis: 'new',
+ competitors: 'new',
+ topics: 'new',
+ prompts: 'new',
+ gsc: 'new',
+ ga: 'new',
+ snippet: 'new',
+ visibility: 'waiting',
+ answers: 'waiting',
+ data_prompts: 'waiting',
+ mentions: 'waiting',
+ citations: 'waiting',
+ traffic: 'waiting',
+ pick_content: 'waiting',
+ create_content: 'waiting',
+ optimize_page: 'waiting',
+ ready: 'waiting',
+ });
+ });
+
+ it('counts KPIs saved from the KPI screen, or set up before the start', () => {
+ // The ready-made set appeared after the start: not set yet.
+ expect(step(facts({ kpiSetupAt: '2026-10-20T11:00:00Z' }), 'kpis').state).toBe('new');
+ expect(step(facts({ records: { kpis: 'done' } }), 'kpis').state).toBe('done');
+ // An existing customer's KPIs, from before Getting started.
+ expect(step(facts({ kpiSetupAt: '2026-09-01T00:00:00Z' }), 'kpis').state).toBe('done');
+ expect(step(facts({ startedAt: null, kpiSetupAt: '2026-10-20T11:00:00Z' }), 'kpis').state).toBe(
+ 'done',
+ );
+ });
+
+ it('wants three competitors and three topics, with progress', () => {
+ expect(step(facts({ competitors: 2 }), 'competitors')).toMatchObject({
+ state: 'new',
+ progress: { value: 2, target: 3 },
+ });
+ expect(step(facts({ competitors: 7 }), 'competitors')).toMatchObject({
+ state: 'done',
+ progress: { value: 3, target: 3 },
+ });
+ expect(step(facts({ topicPrompts: [0, 0] }), 'topics')).toMatchObject({
+ state: 'new',
+ progress: { value: 2, target: 3 },
+ });
+ expect(step(facts({ topicPrompts: [0, 0, 0] }), 'topics').state).toBe('done');
+ });
+
+ it('wants three prompts in every topic, and at least three topics of them', () => {
+ // Two full topics of three: 6/9 until a third topic has its prompts.
+ expect(step(facts({ topicPrompts: [3, 4] }), 'prompts')).toMatchObject({
+ state: 'new',
+ progress: { value: 6, target: 9 },
+ });
+ expect(step(facts({ topicPrompts: [3, 5, 3] }), 'prompts')).toMatchObject({
+ state: 'done',
+ progress: { value: 9, target: 9 },
+ });
+ // A fourth topic raises the bar; extra prompts elsewhere don't make up for it.
+ expect(step(facts({ topicPrompts: [9, 3, 3, 1] }), 'prompts')).toMatchObject({
+ state: 'new',
+ progress: { value: 10, target: 12 },
+ });
+ });
+
+ it('lets Search Console and Analytics be skipped, and done when connected anyway', () => {
+ const skipped = facts({ records: { gsc: 'skipped', ga: 'skipped' } });
+ expect(step(skipped, 'gsc').state).toBe('skipped');
+ expect(step(skipped, 'ga').state).toBe('skipped');
+ expect(step({ ...skipped, gsc: true }, 'gsc').state).toBe('done');
+ expect(buildGettingStarted(skipped).done).toBe(3); // both, and the step that needs them
+ });
+
+ it('marks the snippet done on the first AI visit', () => {
+ expect(step(facts({ firstVisit: true }), 'snippet').state).toBe('done');
+ });
+
+ it('unlocks the explore pages with the first answers, done once opened', () => {
+ expect(step(facts({ records: { mentions: 'opened' } }), 'mentions').state).toBe('done');
+ const answered = facts({ firstAnswer: true });
+ expect(step(answered, 'visibility').state).toBe('new');
+ expect(step({ ...answered, records: { visibility: 'opened' } }, 'visibility').state).toBe(
+ 'done',
+ );
+ expect(step(answered, 'traffic').state).toBe('new');
+ });
+
+ it('waits for prompt suggestions from Search Console or Analytics, done at five tracked', () => {
+ const connected = facts({ firstAnswer: true, gsc: true });
+ expect(step(connected, 'data_prompts')).toMatchObject({
+ state: 'waiting',
+ progress: { value: 0, target: 5 },
+ });
+ expect(
+ step({ ...connected, dataSuggestions: 12, dataTracked: 2 }, 'data_prompts'),
+ ).toMatchObject({ state: 'new', progress: { value: 2, target: 5 } });
+ expect(step({ ...connected, dataSuggestions: 12, dataTracked: 6 }, 'data_prompts').state).toBe(
+ 'done',
+ );
+ });
+
+ it('goes with both sources when both are skipped, but not with one', () => {
+ expect(step(facts({ records: { gsc: 'skipped', ga: 'skipped' } }), 'data_prompts').state).toBe(
+ 'skipped',
+ );
+ expect(step(facts({ records: { gsc: 'skipped' } }), 'data_prompts').state).toBe('waiting');
+ // Skipped, then connected after all: the suggestions can still come.
+ expect(
+ step(facts({ ga: true, records: { gsc: 'skipped', ga: 'skipped' } }), 'data_prompts').state,
+ ).toBe('waiting');
+ });
+
+ it('unlocks the act steps with the first content suggestions', () => {
+ const suggested = facts({ contentSuggestions: 4 });
+ expect(step(suggested, 'pick_content').state).toBe('new');
+ expect(step(suggested, 'create_content').state).toBe('new');
+ expect(step(suggested, 'optimize_page').state).toBe('new');
+ expect(step({ ...suggested, contentPicked: 1 }, 'pick_content').state).toBe('done');
+ expect(step({ ...suggested, contentCreated: 1 }, 'create_content').state).toBe('done');
+ // Done counts before the unlock: an audit run before the suggestions came.
+ expect(step(facts({ audits: 1 }), 'optimize_page').state).toBe('done');
+ });
+
+ it('is ready once every other step is done or skipped', () => {
+ const all = facts({
+ records: {
+ kpis: 'done',
+ ga: 'skipped',
+ visibility: 'opened',
+ answers: 'opened',
+ mentions: 'opened',
+ citations: 'opened',
+ traffic: 'opened',
+ },
+ competitors: 5,
+ topicPrompts: [3, 3, 3],
+ gsc: true,
+ firstAnswer: true,
+ firstVisit: true,
+ dataSuggestions: 8,
+ dataTracked: 5,
+ contentSuggestions: 3,
+ contentPicked: 1,
+ contentCreated: 1,
+ audits: 2,
+ });
+ const status = buildGettingStarted(all);
+ expect(step(all, 'ready').state).toBe('done');
+ expect(status.done).toBe(17);
+ expect(step({ ...all, audits: 0 }, 'ready').state).toBe('waiting');
+ });
+
+ it('dates the steps a person acted on, and only those', () => {
+ const f = facts({
+ competitors: 4,
+ records: { gsc: 'skipped' },
+ recordedAt: { gsc: '2026-10-20T12:05:00Z' },
+ });
+ expect(step(f, 'gsc').updatedAt).toBe('2026-10-20T12:05:00Z');
+ expect(step(f, 'competitors').updatedAt).toBeNull();
+ });
+
+ it('is inactive for a brand that never started it, or skipped it', () => {
+ expect(buildGettingStarted(facts({ startedAt: null })).active).toBe(false);
+ expect(buildGettingStarted(facts({ dismissedAt: '2026-10-21T00:00:00Z' })).active).toBe(false);
+ });
+});
+
+describe('parseGettingStartedFacts', () => {
+ it('reads the RPC jsonb', () => {
+ expect(
+ parseGettingStartedFacts({
+ started_at: '2026-10-20T10:00:00+00:00',
+ dismissed_at: null,
+ steps: {
+ kpis: { state: 'done', at: '2026-10-20T12:00:00+00:00' },
+ gsc: { state: 'skipped', at: '2026-10-20T12:05:00+00:00' },
+ visibility: { state: 'opened', at: null },
+ odd: { state: 'maybe', at: '2026-10-20T12:10:00+00:00' },
+ },
+ kpi_setup_at: '2026-10-20T11:00:00+00:00',
+ competitors: 4,
+ topic_prompts: [3, '2', null],
+ gsc: true,
+ ga: false,
+ first_answer: true,
+ first_visit: false,
+ data_suggestions: 7,
+ data_tracked: 1,
+ content_suggestions: 3,
+ content_picked: 0,
+ content_created: 0,
+ audits: 1,
+ }),
+ ).toEqual({
+ startedAt: '2026-10-20T10:00:00+00:00',
+ dismissedAt: null,
+ records: { kpis: 'done', gsc: 'skipped', visibility: 'opened' },
+ recordedAt: { kpis: '2026-10-20T12:00:00+00:00', gsc: '2026-10-20T12:05:00+00:00' },
+ kpiSetupAt: '2026-10-20T11:00:00+00:00',
+ competitors: 4,
+ topicPrompts: [3, 2, 0],
+ gsc: true,
+ ga: false,
+ firstAnswer: true,
+ firstVisit: false,
+ dataSuggestions: 7,
+ dataTracked: 1,
+ contentSuggestions: 3,
+ contentPicked: 0,
+ contentCreated: 0,
+ audits: 1,
+ });
+ });
+
+ it('gives null for a brand the caller can’t see', () => {
+ expect(parseGettingStartedFacts(null)).toBeNull();
+ });
+});
+
+describe('pageOpenedStep', () => {
+ it('maps the explore pages, their subpages included', () => {
+ expect(pageOpenedStep('/dashboard/insights')).toBe('visibility');
+ expect(pageOpenedStep('/dashboard/prompts')).toBe('answers');
+ expect(pageOpenedStep('/dashboard/prompts/tracked')).toBe('answers');
+ expect(pageOpenedStep('/dashboard/mentions')).toBe('mentions');
+ expect(pageOpenedStep('/dashboard/citations/domains')).toBe('citations');
+ expect(pageOpenedStep('/dashboard/traffic')).toBe('traffic');
+ });
+
+ it('leaves every other page alone', () => {
+ expect(pageOpenedStep('/dashboard/prompts/insights')).toBeNull();
+ expect(pageOpenedStep('/dashboard/prompts/suggestions')).toBeNull();
+ expect(pageOpenedStep('/dashboard/insightsx')).toBeNull();
+ expect(pageOpenedStep('/dashboard/action-center/actions')).toBeNull();
+ });
+
+ it('accepts only page steps from the client', () => {
+ expect(isPageOpenedStep('mentions')).toBe(true);
+ expect(isPageOpenedStep('kpis')).toBe(false);
+ expect(isPageOpenedStep('mentions; drop table')).toBe(false);
+ });
+});
diff --git a/web/src/lib/getting-started/steps.ts b/web/src/lib/getting-started/steps.ts
new file mode 100644
index 000000000..405ce9cfb
--- /dev/null
+++ b/web/src/lib/getting-started/steps.ts
@@ -0,0 +1,283 @@
+/**
+ * Getting started (New Ansvisor, AC-ALT2 §4): the fixed steps a brand walks
+ * through in the Actions page, and how each step's state follows from the
+ * brand's data (getting_started_facts, 00196). They sit beside the generated
+ * actions and never go through the signal engine or get a Priority Score.
+ *
+ * Steps unlock when their data is ready, not on a schedule:
+ * - Set up: now.
+ * - Explore: when the first AI answers are in. The high-value prompts step
+ * waits for prompt suggestions built from Search Console or Analytics.
+ * - Act: when the first content suggestions are in.
+ * - Ready: after every step above is done or skipped.
+ */
+
+export type GettingStartedStage = 'setup' | 'explore' | 'act' | 'ready';
+
+export type GettingStartedStepKey =
+ | 'kpis'
+ | 'competitors'
+ | 'topics'
+ | 'prompts'
+ | 'gsc'
+ | 'ga'
+ | 'snippet'
+ | 'visibility'
+ | 'answers'
+ | 'data_prompts'
+ | 'mentions'
+ | 'citations'
+ | 'traffic'
+ | 'pick_content'
+ | 'create_content'
+ | 'optimize_page'
+ | 'ready';
+
+/** waiting: locked until its data is ready ("Waiting for data"). */
+export type GettingStartedState = 'new' | 'done' | 'waiting' | 'skipped';
+
+export interface GettingStartedStepDef {
+ key: GettingStartedStepKey;
+ stage: GettingStartedStage;
+ /** The page the step opens, in a new tab. */
+ href: string;
+ /** Optional steps can be skipped; a skipped step counts as complete. */
+ optional?: boolean;
+}
+
+const INTEGRATIONS_HREF = '/dashboard/settings?tab=integrations';
+
+export const GETTING_STARTED_STEPS: readonly GettingStartedStepDef[] = [
+ { key: 'kpis', stage: 'setup', href: '/dashboard/action-center/kpis' },
+ { key: 'competitors', stage: 'setup', href: '/dashboard/competitors' },
+ { key: 'topics', stage: 'setup', href: '/dashboard/prompts/topics' },
+ { key: 'prompts', stage: 'setup', href: '/dashboard/prompts/suggestions' },
+ { key: 'gsc', stage: 'setup', href: INTEGRATIONS_HREF, optional: true },
+ { key: 'ga', stage: 'setup', href: INTEGRATIONS_HREF, optional: true },
+ { key: 'snippet', stage: 'setup', href: '/dashboard/traffic' },
+ { key: 'visibility', stage: 'explore', href: '/dashboard/insights' },
+ { key: 'answers', stage: 'explore', href: '/dashboard/prompts/tracked' },
+ { key: 'data_prompts', stage: 'explore', href: '/dashboard/prompts/suggestions' },
+ { key: 'mentions', stage: 'explore', href: '/dashboard/mentions' },
+ { key: 'citations', stage: 'explore', href: '/dashboard/citations' },
+ { key: 'traffic', stage: 'explore', href: '/dashboard/traffic' },
+ { key: 'pick_content', stage: 'act', href: '/dashboard/content' },
+ { key: 'create_content', stage: 'act', href: '/dashboard/content' },
+ { key: 'optimize_page', stage: 'act', href: '/dashboard/audit' },
+ { key: 'ready', stage: 'ready', href: '/dashboard/action-center/actions' },
+];
+
+export const MIN_COMPETITORS = 3;
+export const MIN_TOPICS = 3;
+export const PROMPTS_PER_TOPIC = 3;
+/** Search Console / Analytics prompt suggestions to track. */
+export const DATA_PROMPTS_TARGET = 5;
+
+/** The explore steps that are done once their page is opened. */
+const PAGE_STEPS: readonly { path: string; step: GettingStartedStepKey }[] = [
+ { path: '/dashboard/insights', step: 'visibility' },
+ { path: '/dashboard/prompts/tracked', step: 'answers' },
+ { path: '/dashboard/mentions', step: 'mentions' },
+ { path: '/dashboard/citations', step: 'citations' },
+ { path: '/dashboard/traffic', step: 'traffic' },
+];
+
+/** The explore step a dashboard path opens, if any (no locale prefix). */
+export function pageOpenedStep(pathname: string): GettingStartedStepKey | null {
+ // /dashboard/prompts shows the tracked prompts too.
+ const path = pathname === '/dashboard/prompts' ? '/dashboard/prompts/tracked' : pathname;
+ const hit = PAGE_STEPS.find((p) => path === p.path || path.startsWith(`${p.path}/`));
+ return hit?.step ?? null;
+}
+
+export function isPageOpenedStep(step: string): step is GettingStartedStepKey {
+ return PAGE_STEPS.some((p) => p.step === step);
+}
+
+export type GettingStartedRecord = 'opened' | 'skipped' | 'done';
+
+export interface GettingStartedFacts {
+ startedAt: string | null;
+ dismissedAt: string | null;
+ /** What a person did that leaves no other trace (getting_started_steps). */
+ records: Partial<Record<string, GettingStartedRecord>>;
+ /** When each record was made. */
+ recordedAt: Partial<Record<string, string>>;
+ kpiSetupAt: string | null;
+ competitors: number;
+ /** Active prompts in each active topic. */
+ topicPrompts: number[];
+ gsc: boolean;
+ ga: boolean;
+ firstAnswer: boolean;
+ firstVisit: boolean;
+ dataSuggestions: number;
+ dataTracked: number;
+ contentSuggestions: number;
+ contentPicked: number;
+ contentCreated: number;
+ audits: number;
+}
+
+export interface GettingStartedProgress {
+ value: number;
+ target: number;
+}
+
+export interface GettingStartedStep extends GettingStartedStepDef {
+ state: GettingStartedState;
+ progress: GettingStartedProgress | null;
+ /** When a person last acted on it here; null for a step its data finished. */
+ updatedAt: string | null;
+}
+
+export interface GettingStartedStatus {
+ /** Started for the brand and not skipped. */
+ active: boolean;
+ steps: GettingStartedStep[];
+ /** Steps done or skipped. */
+ done: number;
+ total: number;
+}
+
+const num = (v: unknown) => {
+ const n = Number(v);
+ return Number.isFinite(n) && n > 0 ? n : 0;
+};
+const str = (v: unknown) => (typeof v === 'string' && v ? v : null);
+const RECORDS = new Set<string>(['opened', 'skipped', 'done']);
+
+/** getting_started_facts' jsonb, or null for a brand the caller can't see. */
+export function parseGettingStartedFacts(raw: unknown): GettingStartedFacts | null {
+ if (!raw || typeof raw !== 'object') return null;
+ const r = raw as Record<string, unknown>;
+ const records: Partial<Record<string, GettingStartedRecord>> = {};
+ const recordedAt: Partial<Record<string, string>> = {};
+ if (r.steps && typeof r.steps === 'object') {
+ for (const [step, value] of Object.entries(r.steps as Record<string, unknown>)) {
+ const { state, at } = (value ?? {}) as { state?: unknown; at?: unknown };
+ if (typeof state === 'string' && RECORDS.has(state)) {
+ records[step] = state as GettingStartedRecord;
+ const time = str(at);
+ if (time) recordedAt[step] = time;
+ }
+ }
+ }
+ return {
+ startedAt: str(r.started_at),
+ dismissedAt: str(r.dismissed_at),
+ records,
+ recordedAt,
+ kpiSetupAt: str(r.kpi_setup_at),
+ competitors: num(r.competitors),
+ topicPrompts: Array.isArray(r.topic_prompts) ? r.topic_prompts.map(num) : [],
+ gsc: r.gsc === true,
+ ga: r.ga === true,
+ firstAnswer: r.first_answer === true,
+ firstVisit: r.first_visit === true,
+ dataSuggestions: num(r.data_suggestions),
+ dataTracked: num(r.data_tracked),
+ contentSuggestions: num(r.content_suggestions),
+ contentPicked: num(r.content_picked),
+ contentCreated: num(r.content_created),
+ audits: num(r.audits),
+ };
+}
+
+const progress = (value: number, target: number): GettingStartedProgress => ({
+ value: Math.min(value, target),
+ target,
+});
+
+/** done when finished, else waiting until its data is ready, else new. */
+const stateOf = (finished: boolean, ready: boolean): GettingStartedState =>
+ finished ? 'done' : ready ? 'new' : 'waiting';
+
+/** An optional step: done when connected, skipped when a person skipped it. */
+const optionalState = (finished: boolean, record: GettingStartedRecord | undefined) =>
+ finished ? 'done' : record === 'skipped' ? 'skipped' : 'new';
+
+function kpisSet(f: GettingStartedFacts): boolean {
+ if (f.records.kpis === 'done') return true;
+ // KPIs a brand had before it started count: an existing customer set them
+ // up already. After the start, the ready-made set appears on a visit to
+ // the KPI tab, so only saving from the KPI screen counts.
+ if (!f.kpiSetupAt) return false;
+ return !f.startedAt || Date.parse(f.kpiSetupAt) < Date.parse(f.startedAt);
+}
+
+function stepState(
+ key: GettingStartedStepKey,
+ f: GettingStartedFacts,
+): Pick<GettingStartedStep, 'state' | 'progress'> {
+ const topics = f.topicPrompts.length;
+ switch (key) {
+ case 'kpis':
+ return { state: stateOf(kpisSet(f), true), progress: null };
+ case 'competitors':
+ return {
+ state: stateOf(f.competitors >= MIN_COMPETITORS, true),
+ progress: progress(f.competitors, MIN_COMPETITORS),
+ };
+ case 'topics':
+ return {
+ state: stateOf(topics >= MIN_TOPICS, true),
+ progress: progress(topics, MIN_TOPICS),
+ };
+ case 'prompts': {
+ // Three in every topic, and at least three topics' worth.
+ const target = PROMPTS_PER_TOPIC * Math.max(topics, MIN_TOPICS);
+ const value = f.topicPrompts.reduce((sum, n) => sum + Math.min(n, PROMPTS_PER_TOPIC), 0);
+ return { state: stateOf(value >= target, true), progress: progress(value, target) };
+ }
+ case 'gsc':
+ return { state: optionalState(f.gsc, f.records.gsc), progress: null };
+ case 'ga':
+ return { state: optionalState(f.ga, f.records.ga), progress: null };
+ case 'snippet':
+ return { state: stateOf(f.firstVisit, true), progress: null };
+ case 'visibility':
+ case 'answers':
+ case 'mentions':
+ case 'citations':
+ case 'traffic':
+ return { state: stateOf(Boolean(f.records[key]), f.firstAnswer), progress: null };
+ case 'data_prompts': {
+ const finished = f.dataTracked >= DATA_PROMPTS_TARGET;
+ // With both sources skipped and neither connected, no such suggestion
+ // can come: the step goes with them.
+ const noSource = !f.gsc && !f.ga && f.records.gsc === 'skipped' && f.records.ga === 'skipped';
+ return {
+ state: !finished && noSource ? 'skipped' : stateOf(finished, f.dataSuggestions > 0),
+ progress: progress(f.dataTracked, DATA_PROMPTS_TARGET),
+ };
+ }
+ case 'pick_content':
+ return { state: stateOf(f.contentPicked > 0, f.contentSuggestions > 0), progress: null };
+ case 'create_content':
+ return { state: stateOf(f.contentCreated > 0, f.contentSuggestions > 0), progress: null };
+ case 'optimize_page':
+ return { state: stateOf(f.audits > 0, f.contentSuggestions > 0), progress: null };
+ case 'ready':
+ // Filled in once the others are known.
+ return { state: 'waiting', progress: null };
+ }
+}
+
+const complete = (s: GettingStartedStep) => s.state === 'done' || s.state === 'skipped';
+
+export function buildGettingStarted(f: GettingStartedFacts): GettingStartedStatus {
+ const steps = GETTING_STARTED_STEPS.map((def) => ({
+ ...def,
+ ...stepState(def.key, f),
+ updatedAt: f.recordedAt[def.key] ?? null,
+ }));
+ const ready = steps.find((s) => s.key === 'ready')!;
+ ready.state = steps.every((s) => s === ready || complete(s)) ? 'done' : 'waiting';
+ return {
+ active: Boolean(f.startedAt) && !f.dismissedAt,
+ steps,
+ done: steps.filter(complete).length,
+ total: steps.length,
+ };
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index b999e7b1a..0c536e521 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -1098,6 +1098,61 @@ export type Database = {
},
]
}
+ getting_started: {
+ Row: {
+ brand_id: string
+ dismissed_at: string | null
+ started_at: string
+ }
+ Insert: {
+ brand_id: string
+ dismissed_at?: string | null
+ started_at?: string
+ }
+ Update: {
+ brand_id?: string
+ dismissed_at?: string | null
+ started_at?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "getting_started_brand_id_fkey"
+ columns: ["brand_id"]
+ isOneToOne: true
+ referencedRelation: "brands"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
+ getting_started_steps: {
+ Row: {
+ brand_id: string
+ state: string
+ step: string
+ updated_at: string
+ }
+ Insert: {
+ brand_id: string
+ state: string
+ step: string
+ updated_at?: string
+ }
+ Update: {
+ brand_id?: string
+ state?: string
+ step?: string
+ updated_at?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "getting_started_steps_brand_id_fkey"
+ columns: ["brand_id"]
+ isOneToOne: false
+ referencedRelation: "brands"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
gsc_page_stats: {
Row: {
brand_id: string
@@ -3322,6 +3377,14 @@ export type Database = {
isSetofReturn: true
}
}
+ getting_started_facts: {
+ Args: { p_brand_id: string }
+ Returns: Json
+ }
+ getting_started_page_opened: {
+ Args: { p_brand_id: string; p_step: string }
+ Returns: boolean
+ }
gsc_candidate_queries: {
Args: { p_brand_id: string; p_min_impressions: number; p_since: string }
Returns: {