Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(action-center): open a brand without KPIs on a ready-made set (#1129)
Cihana3c9e1bbd68e
diff --git a/supabase/migrations/00163_kpi_presets.sql b/supabase/migrations/00163_kpi_presets.sqlnew file mode 100644index 000000000..1b9f4abf3--- /dev/null+++ b/supabase/migrations/00163_kpi_presets.sql@@ -0,0 +1,105 @@+-- ============================================================================+-- 00163: ready-made KPIs on a brand's first visit (Action Center)+-- ============================================================================+-- A brand with no KPIs used to open on an empty KPI tab. It now opens with a+-- ready-made set (Visibility, Mentions, Citations, Share of Voice, Positive+-- Sentiment, and AI Referral Traffic when Google Analytics is mapped), each+-- aiming 20% above its last 30 days. The web computes the targets; this adds+-- what it can't do safely on its own:+--+-- * brands.kpi_setup_at: when the brand first had a KPI, from the presets+-- or set by hand. The presets are offered only before it, so a person who+-- removes every KPI doesn't get them back on their next visit. Set by a+-- trigger on kpi_definitions, and filled here for the brands that already+-- have KPIs;+-- * seed_kpi_presets: adds the set once, for an admin or manager of the+-- brand's organization (as kpi_definitions' write policies), with the+-- brand row locked so two people opening the tab at once add it once.++alter table public.brands+ add column if not exists kpi_setup_at timestamptz;++comment on column public.brands.kpi_setup_at is+ 'When the brand first had a KPI (ready-made or set by hand); the ready-made set is offered only before it.';++update public.brands b+ set kpi_setup_at = d.first_at+ from (+ select brand_id, min(created_at) as first_at+ from public.kpi_definitions+ group by brand_id+ ) d+ where d.brand_id = b.id+ and b.kpi_setup_at is null;++-- The first KPI a brand gets, by any path, marks it set up.+create or replace function public.mark_brand_kpi_setup()+returns trigger+language plpgsql+security definer+set search_path to 'public'+as $$+begin+ update public.brands+ set kpi_setup_at = now()+ where id = new.brand_id+ and kpi_setup_at is null;+ return new;+end;+$$;++drop trigger if exists trg_kpi_definitions_mark_setup on public.kpi_definitions;+create trigger trg_kpi_definitions_mark_setup+ after insert on public.kpi_definitions+ for each row execute function public.mark_brand_kpi_setup();++-- Adds the ready-made KPIs, p_kpis = [{ "key": "mentions", "target": 129 }, …],+-- monthly. True when it added them; false when the brand was already set up+-- (or isn't there). Raises 42501 for a caller who isn't an admin or manager+-- of the brand's organization.+create or replace function public.seed_kpi_presets(p_brand_id uuid, p_kpis jsonb)+returns boolean+language plpgsql+security definer+set search_path to 'public'+as $$+declare+ v_org uuid;+ v_setup timestamptz;+begin+ select b.organization_id, b.kpi_setup_at+ into v_org, v_setup+ from public.brands b+ where b.id = p_brand_id+ for update;+ if not found then+ return false;+ end if;++ if not exists (+ select 1 from public.profiles p+ where p.id = auth.uid()+ and p.organization_id = v_org+ and p.role = any (array['admin', 'manager']::public.user_role[])+ ) then+ raise exception 'Only admins and managers can set up KPIs' using errcode = '42501';+ end if;++ if v_setup is not null+ or exists (select 1 from public.kpi_definitions d where d.brand_id = p_brand_id) then+ return false;+ end if;++ insert into public.kpi_definitions (brand_id, kpi_key, target, timeframe, is_active)+ select p_brand_id, k.value->>'key', (k.value->>'target')::numeric, 'monthly', true+ from jsonb_array_elements(coalesce(p_kpis, '[]'::jsonb)) k+ where coalesce(k.value->>'key', '') <> ''+ and (k.value->>'target')::numeric > 0+ on conflict (brand_id, kpi_key) do nothing;++ return found;+end;+$$;++revoke execute on function public.seed_kpi_presets(uuid, jsonb) from public, anon;+grant execute on function public.seed_kpi_presets(uuid, jsonb) to authenticated;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 36303fe9f..074866ca2 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -20551,3 +20551,112 @@ $$;revoke execute on function public.refresh_insights_daily(uuid, date, date)from public, anon, authenticated;+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00163_kpi_presets.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00163: ready-made KPIs on a brand's first visit (Action Center)+-- ============================================================================+-- A brand with no KPIs used to open on an empty KPI tab. It now opens with a+-- ready-made set (Visibility, Mentions, Citations, Share of Voice, Positive+-- Sentiment, and AI Referral Traffic when Google Analytics is mapped), each+-- aiming 20% above its last 30 days. The web computes the targets; this adds+-- what it can't do safely on its own:+--+-- * brands.kpi_setup_at: when the brand first had a KPI, from the presets+-- or set by hand. The presets are offered only before it, so a person who+-- removes every KPI doesn't get them back on their next visit. Set by a+-- trigger on kpi_definitions, and filled here for the brands that already+-- have KPIs;+-- * seed_kpi_presets: adds the set once, for an admin or manager of the+-- brand's organization (as kpi_definitions' write policies), with the+-- brand row locked so two people opening the tab at once add it once.++alter table public.brands+ add column if not exists kpi_setup_at timestamptz;++comment on column public.brands.kpi_setup_at is+ 'When the brand first had a KPI (ready-made or set by hand); the ready-made set is offered only before it.';++update public.brands b+ set kpi_setup_at = d.first_at+ from (+ select brand_id, min(created_at) as first_at+ from public.kpi_definitions+ group by brand_id+ ) d+ where d.brand_id = b.id+ and b.kpi_setup_at is null;++-- The first KPI a brand gets, by any path, marks it set up.+create or replace function public.mark_brand_kpi_setup()+returns trigger+language plpgsql+security definer+set search_path to 'public'+as $$+begin+ update public.brands+ set kpi_setup_at = now()+ where id = new.brand_id+ and kpi_setup_at is null;+ return new;+end;+$$;++drop trigger if exists trg_kpi_definitions_mark_setup on public.kpi_definitions;+create trigger trg_kpi_definitions_mark_setup+ after insert on public.kpi_definitions+ for each row execute function public.mark_brand_kpi_setup();++-- Adds the ready-made KPIs, p_kpis = [{ "key": "mentions", "target": 129 }, …],+-- monthly. True when it added them; false when the brand was already set up+-- (or isn't there). Raises 42501 for a caller who isn't an admin or manager+-- of the brand's organization.+create or replace function public.seed_kpi_presets(p_brand_id uuid, p_kpis jsonb)+returns boolean+language plpgsql+security definer+set search_path to 'public'+as $$+declare+ v_org uuid;+ v_setup timestamptz;+begin+ select b.organization_id, b.kpi_setup_at+ into v_org, v_setup+ from public.brands b+ where b.id = p_brand_id+ for update;+ if not found then+ return false;+ end if;++ if not exists (+ select 1 from public.profiles p+ where p.id = auth.uid()+ and p.organization_id = v_org+ and p.role = any (array['admin', 'manager']::public.user_role[])+ ) then+ raise exception 'Only admins and managers can set up KPIs' using errcode = '42501';+ end if;++ if v_setup is not null+ or exists (select 1 from public.kpi_definitions d where d.brand_id = p_brand_id) then+ return false;+ end if;++ insert into public.kpi_definitions (brand_id, kpi_key, target, timeframe, is_active)+ select p_brand_id, k.value->>'key', (k.value->>'target')::numeric, 'monthly', true+ from jsonb_array_elements(coalesce(p_kpis, '[]'::jsonb)) k+ where coalesce(k.value->>'key', '') <> ''+ and (k.value->>'target')::numeric > 0+ on conflict (brand_id, kpi_key) do nothing;++ return found;+end;+$$;++revoke execute on function public.seed_kpi_presets(uuid, jsonb) from public, anon;+grant execute on function public.seed_kpi_presets(uuid, jsonb) to authenticated;+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 925ef758a..2d4d1e912 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -139,6 +139,11 @@"noBrand": {"title": "No brand selected","description": "Select a brand to view its KPIs."+ },+ "presets": {+ "setUp": "We set up these KPIs for you. Each aims 20% above its last 30 days, or starts from a default where there's no data yet. Change or remove them any time.",+ "preview": "Suggested KPIs. Each aims 20% above its last 30 days, or starts from a default where there's no data yet. They're saved the first time an admin or manager opens this tab.",+ "dismiss": "Dismiss"}},"drawer": {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/kpis/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/kpis/page.test.tsxindex a1960321c..d61c6ec1b 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/action-center/kpis/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/kpis/page.test.tsx@@ -1,6 +1,6 @@-import { act } from 'react';+import { act, StrictMode } from 'react';import { createRoot } from 'react-dom/client';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { Brand } from '@/types';(@@ -32,11 +32,23 @@ vi.mock('@/stores/use-brand-store', () => ({selector({ getActiveBrand: () => brand }),}));+const { getKpiSnapshots, seedKpiPresets, getKpiPresetPreview } = vi.hoisted(() => ({+ getKpiSnapshots: vi.fn(),+ seedKpiPresets: vi.fn(),+ getKpiPresetPreview: vi.fn(),+}));vi.mock('@/lib/actions/kpis', () => ({- getKpiSnapshots: vi.fn().mockResolvedValue({ configured: true, kpis: [] }),+ getKpiSnapshots,+ seedKpiPresets,+ getKpiPresetPreview,removeKpi: vi.fn(),}));+let canManage = true;+vi.mock('@/hooks/use-user-role', () => ({+ useUserRole: () => ({ role: canManage ? 'admin' : 'analyst', canManage, canAdmin: canManage }),+}));+vi.mock('@/components/action-center/action-center-tabs', () => ({ActionCenterTabs: () => null,}));@@ -45,9 +57,8 @@ vi.mock('@/components/action-center/kpi-framework-drawer', () => ({KpiFrameworkDrawer: () => null,}));-vi.mock('@/components/action-center/kpi-table', () => ({- KpiTable: () => null,-}));+const { KpiTable } = vi.hoisted(() => ({ KpiTable: vi.fn<(props: unknown) => null>(() => null) }));+vi.mock('@/components/action-center/kpi-table', () => ({ KpiTable }));vi.mock('sonner', () => ({toast: {@@ -57,8 +68,136 @@ vi.mock('sonner', () => ({import ActionCenterKpisPage from './page';+beforeEach(() => {+ getKpiSnapshots.mockResolvedValue({ configured: true, kpis: [] });+});+afterEach(() => {document.body.replaceChildren();+ getKpiSnapshots.mockReset();+ seedKpiPresets.mockReset();+ getKpiPresetPreview.mockReset();+ KpiTable.mockClear();+ canManage = true;+});++const snapshot = (key: string) => ({+ key,+ category: 'mentions',+ unit: 'percent',+ direction: 'higher_is_better',+ timeframe: 'monthly',+ value: 40,+ change: null,+ changeKind: 'points',+ trend: [],+ target: 48,+ progress: 83,+ status: 'on_track',+});++async function renderPage() {+ const container = document.createElement('div');+ document.body.append(container);+ const root = createRoot(container);+ await act(async () => {+ root.render(<ActionCenterKpisPage />);+ });+ return { container, root };+}++describe('the ready-made KPIs', () => {+ it('sets them up once for an admin or manager, and says so', async () => {+ getKpiSnapshots+ .mockResolvedValueOnce({ configured: false, kpis: [], everSetUp: false })+ .mockResolvedValueOnce({ configured: true, kpis: [snapshot('positive_sentiment')] });+ seedKpiPresets.mockResolvedValue(true);+ const { container, root } = await renderPage();++ expect(seedKpiPresets).toHaveBeenCalledWith('brand-id');+ expect(getKpiSnapshots).toHaveBeenCalledTimes(2);+ expect(getKpiPresetPreview).not.toHaveBeenCalled();+ expect(container.textContent).toContain('presets.setUp');+ const props = KpiTable.mock.calls.at(-1)?.[0] as { onEdit?: unknown; kpis: unknown[] };+ expect(props.kpis).toHaveLength(1);+ expect(props.onEdit).toBeTypeOf('function');++ const dismiss = container.querySelector('button[aria-label="presets.dismiss"]') as HTMLElement;+ await act(async () => dismiss.click());+ expect(container.textContent).not.toContain('presets.setUp');+ await act(async () => root.unmount());+ });++ it('shows them unsaved, without editing, to a member who cannot set KPIs', async () => {+ canManage = false;+ getKpiSnapshots.mockResolvedValue({ configured: false, kpis: [], everSetUp: false });+ getKpiPresetPreview.mockResolvedValue([snapshot('mentions'), snapshot('positive_sentiment')]);+ const { container, root } = await renderPage();++ expect(seedKpiPresets).not.toHaveBeenCalled();+ expect(container.textContent).toContain('presets.preview');+ expect(container.textContent).not.toContain('editKpis');+ expect(container.textContent).not.toContain('addKpi');+ const props = KpiTable.mock.calls.at(-1)?.[0] as { onEdit?: unknown; kpis: unknown[] };+ expect(props.kpis).toHaveLength(2);+ expect(props.onEdit).toBeUndefined();+ await act(async () => root.unmount());+ });++ it('leaves the empty state to a brand whose KPIs were all removed', async () => {+ getKpiSnapshots.mockResolvedValue({ configured: false, kpis: [], everSetUp: true });+ const { container, root } = await renderPage();++ expect(seedKpiPresets).not.toHaveBeenCalled();+ expect(container.textContent).toContain('empty.title');+ await act(async () => root.unmount());+ });++ it("keeps the note when a second read races the setup, as React's development double run does", async () => {+ getKpiSnapshots+ .mockResolvedValueOnce({ configured: false, kpis: [], everSetUp: false })+ .mockResolvedValueOnce({ configured: false, kpis: [], everSetUp: false })+ .mockResolvedValue({ configured: true, kpis: [snapshot('mentions')] });+ seedKpiPresets.mockResolvedValueOnce(true).mockResolvedValueOnce(false);+ const container = document.createElement('div');+ document.body.append(container);+ const root = createRoot(container);+ await act(async () => {+ root.render(+ <StrictMode>+ <ActionCenterKpisPage />+ </StrictMode>,+ );+ });++ expect(seedKpiPresets).toHaveBeenCalledTimes(2);+ expect(container.textContent).toContain('presets.setUp');+ await act(async () => root.unmount());+ });++ it('shows the KPIs a colleague set up meanwhile', async () => {+ getKpiSnapshots+ .mockResolvedValueOnce({ configured: false, kpis: [], everSetUp: false })+ .mockResolvedValueOnce({ configured: true, kpis: [snapshot('mentions')] });+ seedKpiPresets.mockResolvedValue(false);+ const { container, root } = await renderPage();++ expect(getKpiSnapshots).toHaveBeenCalledTimes(2);+ expect(container.textContent).not.toContain('presets.setUp');+ expect((KpiTable.mock.calls.at(-1)?.[0] as { kpis: unknown[] }).kpis).toHaveLength(1);+ await act(async () => root.unmount());+ });++ it('keeps the empty state when the setup is refused', async () => {+ getKpiSnapshots.mockResolvedValue({ configured: false, kpis: [], everSetUp: false });+ seedKpiPresets.mockRejectedValue(new Error('Only admins and managers can set up KPIs'));+ // Read again after the attempt: still nothing.+ const { container, root } = await renderPage();++ expect(container.textContent).toContain('empty.title');+ expect(container.textContent).not.toContain('error.title');+ await act(async () => root.unmount());+ });});describe('KPIs status filter', () => {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/kpis/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/kpis/page.tsxindex 4f5bfb378..16d02a505 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/action-center/kpis/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/kpis/page.tsx@@ -3,12 +3,16 @@import { useCallback, useEffect, useMemo, useState } from 'react';import { useTranslations } from 'next-intl';import { toast } from 'sonner';-import { AlertCircle, ListFilter, Plus, Settings2, Target } from 'lucide-react';+import { AlertCircle, ListFilter, Plus, Settings2, Sparkles, Target, X } from 'lucide-react';+import { useUserRole } from '@/hooks/use-user-role';import { useBrandStore } from '@/stores/use-brand-store';import type { Brand } from '@/types';import {+ getKpiPresetPreview,getKpiSnapshots,removeKpi,+ seedKpiPresets,+ type KpiSnapshot,type KpiSnapshotsResult,type KpiWindow,} from '@/lib/actions/kpis';@@ -67,7 +71,12 @@ function KpisContent({ brand }: { brand: Brand }) {const t = useTranslations('actionCenter.kpis');const tCategories = useTranslations('actionCenter.categories');+ const { canManage } = useUserRole();const [result, setResult] = useState<KpiSnapshotsResult | null>(null);+ // A brand that never had a KPI opens on the ready-made set: saved for an+ // admin or manager (and said so once), shown unsaved to everyone else.+ const [preview, setPreview] = useState<KpiSnapshot[] | null>(null);+ const [justSetUp, setJustSetUp] = useState(false);const [isLoading, setIsLoading] = useState(true);const [loadFailed, setLoadFailed] = useState(false);const [category, setCategory] = useState<KpiCategory | 'all'>('all');@@ -91,19 +100,39 @@ function KpisContent({ brand }: { brand: Brand }) {setIsLoading(true);setLoadFailed(false);try {- setResult(await getKpiSnapshots(brand.id, window));+ let next = await getKpiSnapshots(brand.id, window);+ let unsaved: KpiSnapshot[] | null = null;+ if (!next.configured && next.everSetUp === false) {+ if (canManage) {+ // Once per brand (00163): a failed setup leaves the empty state.+ // Read again either way: a colleague may have set it up meanwhile.+ // Only a setup that happened says so: a second read racing it (as+ // React's development double run does) must not hide the note.+ const seeded = await seedKpiPresets(brand.id).catch(() => false);+ if (seeded) setJustSetUp(true);+ next = await getKpiSnapshots(brand.id, window);+ } else {+ unsaved = await getKpiPresetPreview(brand.id, window).catch(() => null);+ }+ }+ setPreview(unsaved);+ setResult(next);} catch {setLoadFailed(true);} finally {setIsLoading(false);}- }, [brand.id, window]);+ }, [brand.id, window, canManage]);useEffect(() => {void load();}, [load]);- const kpis = useMemo(() => result?.kpis ?? [], [result]);+ const previewing = !result?.configured && (preview?.length ?? 0) > 0;+ const kpis = useMemo(+ () => (result?.configured ? result.kpis : (preview ?? [])),+ [result, preview],+ );const categories = useMemo(() => {const counts = new Map<KpiCategory, number>();for (const kpi of kpis) counts.set(kpi.category, (counts.get(kpi.category) ?? 0) + 1);@@ -175,7 +204,7 @@ function KpisContent({ brand }: { brand: Brand }) {/>);- if (!result?.configured) {+ if (!result?.configured && !previewing) {return (<><div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-20 text-center">@@ -194,6 +223,22 @@ function KpisContent({ brand }: { brand: Brand }) {return (<div className="space-y-4">+ {(justSetUp || previewing) && (+ <div className="flex items-start gap-3 rounded-lg border bg-muted/40 px-4 py-3 text-sm">+ <Sparkles className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />+ <p className="flex-1">{previewing ? t('presets.preview') : t('presets.setUp')}</p>+ {justSetUp && (+ <button+ type="button"+ onClick={() => setJustSetUp(false)}+ aria-label={t('presets.dismiss')}+ className="rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground"+ >+ <X className="h-4 w-4" />+ </button>+ )}+ </div>+ )}<div className="flex flex-wrap items-center justify-between gap-3"><div className="flex flex-wrap items-center gap-2"><CategoryPill@@ -264,22 +309,26 @@ function KpisContent({ brand }: { brand: Brand }) {</button>))}</div>- <Button variant="outline" size="sm" className="text-xs" onClick={() => openDrawer()}>- <Settings2 className="h-3.5 w-3.5" />- {t('editKpis')}- </Button>- <Button size="sm" className="text-xs" onClick={() => openDrawer()}>- <Plus className="h-3.5 w-3.5" />- {t('addKpi')}- </Button>+ {!previewing && (+ <>+ <Button variant="outline" size="sm" className="text-xs" onClick={() => openDrawer()}>+ <Settings2 className="h-3.5 w-3.5" />+ {t('editKpis')}+ </Button>+ <Button size="sm" className="text-xs" onClick={() => openDrawer()}>+ <Plus className="h-3.5 w-3.5" />+ {t('addKpi')}+ </Button>+ </>+ )}</div></div>{visible.length > 0 ? (<KpiTablekpis={visible}- onEdit={(key) => openDrawer(key)}- onRemove={(key) => void handleRemove(key)}+ onEdit={previewing ? undefined : (key) => openDrawer(key)}+ onRemove={previewing ? undefined : (key) => void handleRemove(key)}busyKey={busyKey}/>) : kpis.length > 0 ? (diff --git a/web/src/components/action-center/kpi-table.tsx b/web/src/components/action-center/kpi-table.tsxindex 5b0490963..403ba1e30 100644--- a/web/src/components/action-center/kpi-table.tsx+++ b/web/src/components/action-center/kpi-table.tsx@@ -135,10 +135,12 @@ export function KpiTable({busyKey,}: {kpis: KpiSnapshot[];- onEdit: (key: KpiKey) => void;- onRemove: (key: KpiKey) => void;+ /** Without them (the unsaved ready-made set) the rows have no menu. */+ onEdit?: (key: KpiKey) => void;+ onRemove?: (key: KpiKey) => void;busyKey: KpiKey | null;}) {+ const editable = Boolean(onEdit && onRemove);const t = useTranslations('actionCenter.kpis');const tRegistry = useTranslations('actionCenter.registry');@@ -154,9 +156,11 @@ export function KpiTable({<TableHead className="text-xs">{t('table.status')}</TableHead><TableHead className="text-xs">{t('table.goal')}</TableHead><TableHead className="text-xs">{t('table.vsGoal')}</TableHead>- <TableHead className="w-10">- <span className="sr-only">{t('table.actions')}</span>- </TableHead>+ {editable && (+ <TableHead className="w-10">+ <span className="sr-only">{t('table.actions')}</span>+ </TableHead>+ )}</TableRow></TableHeader><TableBody>@@ -203,27 +207,29 @@ export function KpiTable({<TableCell><GoalProgress snapshot={kpi} /></TableCell>- <TableCell>- <DropdownMenu>- <DropdownMenuTrigger- className="rounded p-1 text-muted-foreground hover:bg-muted disabled:pointer-events-none disabled:opacity-50"- disabled={busyKey === kpi.key}- aria-label={t('menu.label', { name: tRegistry(`${kpi.key}.name`) })}- >- <MoreHorizontal className="h-4 w-4" />- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem onClick={() => onEdit(kpi.key)}>- <Pencil className="h-4 w-4" />- {t('menu.edit')}- </DropdownMenuItem>- <DropdownMenuItem variant="destructive" onClick={() => onRemove(kpi.key)}>- <Trash2 className="h-4 w-4" />- {t('menu.remove')}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </TableCell>+ {editable && (+ <TableCell>+ <DropdownMenu>+ <DropdownMenuTrigger+ className="rounded p-1 text-muted-foreground hover:bg-muted disabled:pointer-events-none disabled:opacity-50"+ disabled={busyKey === kpi.key}+ aria-label={t('menu.label', { name: tRegistry(`${kpi.key}.name`) })}+ >+ <MoreHorizontal className="h-4 w-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={() => onEdit?.(kpi.key)}>+ <Pencil className="h-4 w-4" />+ {t('menu.edit')}+ </DropdownMenuItem>+ <DropdownMenuItem variant="destructive" onClick={() => onRemove?.(kpi.key)}>+ <Trash2 className="h-4 w-4" />+ {t('menu.remove')}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </TableCell>+ )}</TableRow>);})}diff --git a/web/src/lib/actions/kpis.test.ts b/web/src/lib/actions/kpis.test.tsindex 784b09747..b6b2ae245 100644--- a/web/src/lib/actions/kpis.test.ts+++ b/web/src/lib/actions/kpis.test.ts@@ -9,21 +9,35 @@ import { DEFAULT_KPI_SET, KPI_KEYS, KPI_REGISTRY, KPI_TEMPLATES } from '@/lib/kp*/let definitions: unknown[] = [];+let brandRow: Record<string, unknown> | null = null;+let brandError: { message: string } | null = null;// One insights_aggregates_daily row per day, by p_day_from.let dailyRows: Record<string, Record<string, number>> = {};const rpcCalls: Record<string, unknown>[] = [];+let seedResult: { data: unknown; error: { code?: string; message: string } | null } = {+ data: true,+ error: null,+};+const seedCalls: Record<string, unknown>[] = [];vi.mock('@/lib/supabase/server', () => ({createClient: vi.fn(async () => ({from: () => {const q = {select: () => q,- eq: async () => ({ data: definitions, error: null }),+ eq: () => q,+ maybeSingle: async () => ({ data: brandRow, error: brandError }),+ then: (resolve: (v: { data: unknown[]; error: null }) => void) =>+ resolve({ data: definitions, error: null }),};return q;},rpc: async (...call: [string, Record<string, unknown>]) => {- const args = call[1];+ const [fn, args] = call;+ if (fn === 'seed_kpi_presets') {+ seedCalls.push(args);+ return seedResult;+ }rpcCalls.push(args);return { data: dailyRows[String(args.p_day_from)] ?? {}, error: null };},@@ -31,23 +45,42 @@ vi.mock('@/lib/supabase/server', () => ({}));const getInsightsSummary = vi.fn();+const getShareOfVoiceData = vi.fn();+const getVisibilityRateTrend = vi.fn();vi.mock('./tracking', () => ({getInsightsSummary: (...args: unknown[]) => getInsightsSummary(...args),- getShareOfVoiceData: vi.fn(),- getVisibilityRateTrend: vi.fn(),+ getShareOfVoiceData: (...args: unknown[]) => getShareOfVoiceData(...args),+ getVisibilityRateTrend: (...args: unknown[]) => getVisibilityRateTrend(...args),+}));+const getTrafficSummary = vi.fn();+const getTrafficTrend = vi.fn();+vi.mock('./traffic', () => ({+ getTrafficSummary: (...args: unknown[]) => getTrafficSummary(...args),+ getTrafficTrend: (...args: unknown[]) => getTrafficTrend(...args),}));-vi.mock('./traffic', () => ({ getTrafficSummary: vi.fn(), getTrafficTrend: vi.fn() }));-const { getKpiSnapshots } = await import('./kpis');+const { getKpiPresetPreview, getKpiSnapshots, seedKpiPresets } = await import('./kpis');const DAY_MS = 86_400_000;const daysAgo = (n: number) => new Date(Date.now() - n * DAY_MS).toISOString().slice(0, 10);beforeEach(() => {definitions = [];+ brandRow = null;+ brandError = null;dailyRows = {};rpcCalls.length = 0;- getInsightsSummary.mockReset();+ seedCalls.length = 0;+ seedResult = { data: true, error: null };+ for (const fn of [+ getInsightsSummary,+ getShareOfVoiceData,+ getVisibilityRateTrend,+ getTrafficSummary,+ getTrafficTrend,+ ]) {+ fn.mockReset();+ }});describe('the Positive Sentiment KPI', () => {@@ -119,3 +152,99 @@ describe('the Positive Sentiment KPI', () => {expect(kpis[1].change).toBeNull();});});++describe('the ready-made KPIs', () => {+ // The last 30 days of a brand: 33.3% visible, 107 mentions, no citations,+ // 90% share of voice, 40% positive, 10 AI visits.+ function lastThirtyDays() {+ getVisibilityRateTrend.mockResolvedValue({ summary: { rate: 33.3, change: 1 }, points: [] });+ getInsightsSummary.mockResolvedValue({+ totalMentions: 107,+ mentionsChange: null,+ totalCitations: 0,+ citationsChange: null,+ positiveSentimentPct: 40,+ sentimentChange: null,+ });+ getShareOfVoiceData.mockResolvedValue({ overallSov: 90, overallSovChange: 0, trend: [] });+ getTrafficSummary.mockResolvedValue({ totalVisits: 10, totalVisitsPrev: 5 });+ getTrafficTrend.mockResolvedValue([]);+ }++ it('says whether a brand without KPIs was ever set up', async () => {+ brandRow = { kpi_setup_at: null };+ await expect(getKpiSnapshots('b1')).resolves.toEqual({+ configured: false,+ kpis: [],+ everSetUp: false,+ });+ brandRow = { kpi_setup_at: '2026-10-01T00:00:00Z' };+ await expect(getKpiSnapshots('b1')).resolves.toMatchObject({ everSetUp: true });+ // A database before 00163: nothing is offered.+ brandRow = null;+ brandError = { message: 'column brands.kpi_setup_at does not exist' };+ await expect(getKpiSnapshots('b1')).resolves.toMatchObject({ everSetUp: true });+ });++ it('sets up each KPI 20% above its last 30 days, with traffic when GA is mapped', async () => {+ lastThirtyDays();+ brandRow = { ga_property_id: 'properties/123' };+ await expect(seedKpiPresets('b1')).resolves.toBe(true);+ expect(seedCalls).toEqual([+ {+ p_brand_id: 'b1',+ p_kpis: [+ { key: 'ai_visibility', target: 40 },+ { key: 'mentions', target: 129 },+ // No citations yet: the registry's default.+ { key: 'citations', target: 100 },+ { key: 'share_of_voice', target: 100 },+ { key: 'positive_sentiment', target: 48 },+ { key: 'ai_referral_traffic', target: 12 },+ ],+ },+ ]);+ // The last 30 days, for every KPI at once.+ expect(getInsightsSummary).toHaveBeenCalledTimes(1);+ });++ it('leaves traffic out without GA, and reports a brand set up meanwhile', async () => {+ lastThirtyDays();+ brandRow = { ga_property_id: null };+ seedResult = { data: false, error: null };+ await expect(seedKpiPresets('b1')).resolves.toBe(false);+ const kpis = seedCalls[0].p_kpis as { key: string }[];+ expect(kpis.map((k) => k.key)).not.toContain('ai_referral_traffic');+ expect(getTrafficSummary).not.toHaveBeenCalled();+ });++ it('is a no-op before the migration, and throws on a refusal', async () => {+ lastThirtyDays();+ seedResult = { data: null, error: { code: 'PGRST202', message: 'not found' } };+ await expect(seedKpiPresets('b1')).resolves.toBe(false);+ seedResult = {+ data: null,+ error: { code: '42501', message: 'Only admins and managers can set up KPIs' },+ };+ await expect(seedKpiPresets('b1')).rejects.toThrow('Only admins and managers');+ });++ it('previews them unsaved, in table order, reading the 30 days once', async () => {+ lastThirtyDays();+ const today = new Date().toISOString().slice(0, 10);+ const preview = await getKpiPresetPreview('b1', { dayFrom: daysAgo(29), dayTo: today });+ expect(preview.map((k) => [k.key, k.target])).toEqual([+ ['ai_visibility', 40],+ ['citations', 100],+ ['mentions', 129],+ ['share_of_voice', 100],+ ['positive_sentiment', 48],+ ]);+ expect(seedCalls).toHaveLength(0);+ expect(getInsightsSummary).toHaveBeenCalledTimes(1);++ // Another window reads its own figures; the targets stay the 30 days'.+ await getKpiPresetPreview('b1', { dayFrom: daysAgo(6), dayTo: today });+ expect(getInsightsSummary).toHaveBeenCalledTimes(3);+ });+});diff --git a/web/src/lib/actions/kpis.ts b/web/src/lib/actions/kpis.tsindex 0f9296054..dbaa349b9 100644--- a/web/src/lib/actions/kpis.ts+++ b/web/src/lib/actions/kpis.ts@@ -34,6 +34,7 @@ import {scaleTargetToWindow,type KpiStatus,} from '@/lib/kpis/status';+import { presetKpiKeys, presetTarget } from '@/lib/kpis/presets';import { getInsightsSummary, getShareOfVoiceData, getVisibilityRateTrend } from './tracking';import { getTrafficSummary, getTrafficTrend } from './traffic';@@ -71,6 +72,12 @@ export interface KpiSnapshotsResult {/** False only when the brand has no definitions at all → empty state. */configured: boolean;kpis: KpiSnapshot[];+ /**+ * With no definitions: whether the brand ever had a KPI (00163's+ * kpi_setup_at). Before that, the page offers the ready-made set; after+ * it, a brand whose KPIs were all removed shows the empty state.+ */+ everSetUp?: boolean;}interface KpiDefinitionRow {@@ -305,7 +312,16 @@ export async function getKpiSnapshots(if (error) throw new Error(error.message);const rows = (data ?? []) as KpiDefinitionRow[];- if (rows.length === 0) return { configured: false, kpis: [] };+ if (rows.length === 0) {+ const { data: brand, error: brandError } = await supabase+ .from('brands')+ .select('kpi_setup_at')+ .eq('id', brandId)+ .maybeSingle();+ // Without the column (a database before 00163) nothing is offered.+ const everSetUp = brandError ? true : Boolean(brand?.kpi_setup_at);+ return { configured: false, kpis: [], everSetUp };+ }// Only registry-known keys are computable. An unknown key (a KPI removed// from the registry, or a future source not shipped yet) is skipped, not@@ -445,3 +461,76 @@ export async function removeKpi(brandId: string, kpiKey: KpiKey): Promise<void>.eq('kpi_key', kpiKey);if (error) throw new Error(error.message);}++/**+ * The ready-made KPIs and their first targets: each KPI's last 30 days, 20%+ * up (lib/kpis/presets.ts), with AI Referral Traffic only when the brand has+ * a Google Analytics property mapped. The metrics are returned too, so a+ * preview over the same 30 days needn't read them twice.+ */+async function readPresets(brandId: string) {+ const supabase = await createClient();+ const { data: brand } = await supabase+ .from('brands')+ .select('ga_property_id')+ .eq('id', brandId)+ .maybeSingle();+ const keys = presetKpiKeys(Boolean(brand?.ga_property_id));+ const metrics = await fetchWindowMetrics(brandId, 'monthly', new Set(keys));+ const entries = keys.map((key) => {+ const now = buildSnapshot(+ { kpiKey: key, target: KPI_REGISTRY[key].defaultTarget, timeframe: 'monthly' },+ metrics,+ );+ return { key, target: presetTarget(key, now?.value ?? null) };+ });+ return { entries, metrics };+}++/**+ * Sets up the ready-made KPIs once, for an admin or manager opening the KPI+ * tab of a brand that never had one (seed_kpi_presets, 00163). True when it+ * added them; false when the brand was set up meanwhile, or on a database+ * without the function.+ */+export async function seedKpiPresets(brandId: string): Promise<boolean> {+ const { entries } = await readPresets(brandId);+ const supabase = await createClient();+ const { data, error } = await supabase.rpc('seed_kpi_presets', {+ p_brand_id: brandId,+ p_kpis: entries,+ });+ if (error?.code === 'PGRST202') return false;+ if (error) throw new Error(error.message);+ return data === true;+}++/**+ * The ready-made KPIs as rows, unsaved: what a member who can't set up KPIs+ * sees on a brand that has none, so the tab isn't empty for them either.+ */+export async function getKpiPresetPreview(+ brandId: string,+ window?: KpiWindow,+): Promise<KpiSnapshot[]> {+ const { entries, metrics } = await readPresets(brandId);+ const windowDays = window+ ? Math.round((Date.parse(window.dayTo) - Date.parse(window.dayFrom)) / DAY_MS) + 1+ : undefined;+ // The presets read the last 30 days; another window needs its own read.+ const sameDays = !window || (windowDays === 30 && window.dayTo === utcToday());+ const shown = sameDays+ ? metrics+ : await fetchWindowMetrics(brandId, 'monthly', new Set(entries.map((e) => e.key)), window);+ const order = new Map(DEFAULT_KPI_SET.map((k, i) => [k, i]));+ return entries+ .map((entry) =>+ buildSnapshot(+ { kpiKey: entry.key, target: entry.target, timeframe: 'monthly' },+ shown,+ windowDays,+ ),+ )+ .filter((snapshot): snapshot is KpiSnapshot => snapshot !== null)+ .sort((a, b) => (order.get(a.key) ?? 99) - (order.get(b.key) ?? 99));+}diff --git a/web/src/lib/kpis/presets.test.ts b/web/src/lib/kpis/presets.test.tsnew file mode 100644index 000000000..ad88ff19a--- /dev/null+++ b/web/src/lib/kpis/presets.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest';+import { isValidKpiTarget } from './registry';+import { PRESET_KPIS, presetKpiKeys, presetTarget } from './presets';++describe('presetKpiKeys', () => {+ it('adds AI Referral Traffic only when Google Analytics is mapped', () => {+ expect(presetKpiKeys(false)).toEqual([+ 'ai_visibility',+ 'mentions',+ 'citations',+ 'share_of_voice',+ 'positive_sentiment',+ ]);+ expect(presetKpiKeys(true)).toEqual([...PRESET_KPIS, 'ai_referral_traffic']);+ });+});++describe('presetTarget', () => {+ it('aims 20% above the last 30 days', () => {+ expect(presetTarget('positive_sentiment', 40)).toBe(48);+ expect(presetTarget('ai_visibility', 33.3)).toBe(40);+ expect(presetTarget('mentions', 107)).toBe(129);+ expect(presetTarget('ai_referral_traffic', 10)).toBe(12);+ });++ it('keeps a percent target at most 100', () => {+ expect(presetTarget('share_of_voice', 90)).toBe(100);+ });++ it("starts from the registry's default without a value", () => {+ expect(presetTarget('mentions', 0)).toBe(100);+ expect(presetTarget('positive_sentiment', null)).toBe(50);+ expect(presetTarget('ai_visibility', Number.NaN)).toBe(50);+ });++ it('always gives a target the framework accepts', () => {+ for (const key of presetKpiKeys(true)) {+ for (const value of [null, 0, 0.01, 1, 55.5, 99.9, 100, 12_345]) {+ expect(isValidKpiTarget(key, presetTarget(key, value))).toBe(true);+ }+ }+ });+});diff --git a/web/src/lib/kpis/presets.ts b/web/src/lib/kpis/presets.tsnew file mode 100644index 000000000..48c748c2a--- /dev/null+++ b/web/src/lib/kpis/presets.ts@@ -0,0 +1,37 @@+import { KPI_REGISTRY, type KpiKey } from './registry';++/**+ * The ready-made KPIs a brand opens with when it has none: the answer-engine+ * set plus Positive Sentiment, and AI Referral Traffic only when Google+ * Analytics is mapped (without it the KPI would read 0 forever). Each aims+ * 20% above its last 30 days, the user's chosen first step; a KPI without a+ * value yet starts from the registry's default target.+ */++export const PRESET_KPIS: readonly KpiKey[] = [+ 'ai_visibility',+ 'mentions',+ 'citations',+ 'share_of_voice',+ 'positive_sentiment',+];++/** The first target is this much above the last 30 days. */+export const PRESET_GROWTH = 1.2;++export function presetKpiKeys(gaConnected: boolean): KpiKey[] {+ return gaConnected ? [...PRESET_KPIS, 'ai_referral_traffic'] : [...PRESET_KPIS];+}++/**+ * The first target for a KPI from its last 30 days: 20% more, rounded up to a+ * whole number for counts, to one decimal (between 0.1 and 100) for percents.+ */+export function presetTarget(key: KpiKey, value: number | null): number {+ const meta = KPI_REGISTRY[key];+ if (value === null || !Number.isFinite(value) || value <= 0) return meta.defaultTarget;+ const raised = value * PRESET_GROWTH;+ // At least 0.1: a sliver of a percent would otherwise round to a 0 target.+ if (meta.unit === 'percent') return Math.min(100, Math.max(0.1, Math.round(raised * 10) / 10));+ return Math.ceil(raised);+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex e7a9cc3d6..0aa416112 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -605,6 +605,7 @@ export type Database = {industry: string | nullinsights_pinned_competitors: string[]is_active: boolean+ kpi_setup_at: string | nulllanguage: string | nulllogo_url: string | nullname: string@@ -625,6 +626,7 @@ export type Database = {industry?: string | nullinsights_pinned_competitors?: string[]is_active?: boolean+ kpi_setup_at?: string | nulllanguage?: string | nulllogo_url?: string | nullname: string@@ -645,6 +647,7 @@ export type Database = {industry?: string | nullinsights_pinned_competitors?: string[]is_active?: boolean+ kpi_setup_at?: string | nulllanguage?: string | nulllogo_url?: string | nullname?: string@@ -3513,6 +3516,10 @@ export type Database = {visible_runs: number}[]}+ seed_kpi_presets: {+ Args: { p_brand_id: string; p_kpis: Json }+ Returns: boolean+ }share_of_voice_aggregates: {Args: {p_brand_id: string