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(insights): pin competitors and mark prompt and action days on the trend (#1043)
Cihanb786f67b8d4c
diff --git a/supabase/migrations/00136_insights_trend.sql b/supabase/migrations/00136_insights_trend.sqlnew file mode 100644index 000000000..40ee3802d--- /dev/null+++ b/supabase/migrations/00136_insights_trend.sql@@ -0,0 +1,75 @@+-- Insights visibility trend (VIS-007).+--+-- The v2 mockup's trend keeps the competitors you pin (up to five) on the+-- chart whatever the range, and marks the days that explain a step in the+-- line: prompts added ("+509 prompts added · Sep 29") and Action Center+-- actions sent ("AC-61 sent · Oct 4").+--+-- Pins are saved on the brand, so the whole team sees the same lines; like+-- every brand setting they're written by admins and managers (the brands+-- update policy). Ids of competitors deleted since are ignored on read.++alter table public.brands+ add column if not exists insights_pinned_competitors uuid[] not null default '{}'+ constraint brands_insights_pinned_competitors_max+ check (cardinality(insights_pinned_competitors) <= 5);++comment on column public.brands.insights_pinned_competitors is+ 'Competitors pinned on the Insights visibility trend (VIS-007, 00136), in pin order; at most five.';++-- Per UTC day (the trend's days), the prompts created for the brand (in the+-- topic, when the trend is filtered to one) and the actions a person sent+-- from it. Actions the nightly generator created have no actor on their+-- "created" event and aren't markers.+create or replace function public.insights_trend_markers(+ p_brand_id uuid,+ p_from timestamptz default null,+ p_to timestamptz default null,+ p_topic_id uuid default null+)+returns jsonb+language sql+stable+security invoker+set search_path to 'public'+as $$+ select jsonb_build_object(+ 'prompts_added', coalesce(+ (select jsonb_agg(jsonb_build_object('day', d.day, 'count', d.n) order by d.day)+ from (+ select (p.created_at at time zone 'utc')::date as day, count(*) as n+ from public.prompts p+ join public.prompt_sets ps on ps.id = p.prompt_set_id+ where ps.brand_id = p_brand_id+ and (p_topic_id is null or p.topic_id = p_topic_id)+ and (p_from is null or p.created_at >= p_from)+ and (p_to is null or p.created_at <= p_to)+ group by 1+ ) d),+ '[]'::jsonb),+ 'actions_sent', coalesce(+ (select jsonb_agg(jsonb_build_object('day', d.day, 'action_nos', d.nos) order by d.day)+ from (+ select (a.created_at at time zone 'utc')::date as day,+ array_agg(a.action_no order by a.action_no) as nos+ from public.actions a+ where a.brand_id = p_brand_id+ and (p_from is null or a.created_at >= p_from)+ and (p_to is null or a.created_at <= p_to)+ and exists (+ select 1 from public.action_events e+ where e.action_id = a.id+ and e.event = 'created'+ and e.actor_id is not null)+ group by 1+ ) d),+ '[]'::jsonb)+ );+$$;++revoke all on function public.insights_trend_markers(uuid, timestamptz, timestamptz, uuid) from public;+grant execute on function public.insights_trend_markers(uuid, timestamptz, timestamptz, uuid)+ to authenticated, service_role;++comment on function public.insights_trend_markers(uuid, timestamptz, timestamptz, uuid) is+ 'Insights trend markers (VIS-007, 00136): per UTC day, the prompts created for the brand (optionally in one topic) and the Action Center actions a person sent, between two optional bounds. Security invoker.';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 6476a816c..64ba63b13 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -16798,6 +16798,85 @@ comment on function public.insights_change_drivers() is'Insights "Why it changed" (VIS-009, 00135) for timestamp windows (24h, topic views), from prompt_results. Same output as insights_change_drivers_daily.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00136_insights_trend.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Insights visibility trend (VIS-007).+--+-- The v2 mockup's trend keeps the competitors you pin (up to five) on the+-- chart whatever the range, and marks the days that explain a step in the+-- line: prompts added ("+509 prompts added · Sep 29") and Action Center+-- actions sent ("AC-61 sent · Oct 4").+--+-- Pins are saved on the brand, so the whole team sees the same lines; like+-- every brand setting they're written by admins and managers (the brands+-- update policy). Ids of competitors deleted since are ignored on read.++alter table public.brands+ add column if not exists insights_pinned_competitors uuid[] not null default '{}'+ constraint brands_insights_pinned_competitors_max+ check (cardinality(insights_pinned_competitors) <= 5);++comment on column public.brands.insights_pinned_competitors is+ 'Competitors pinned on the Insights visibility trend (VIS-007, 00136), in pin order; at most five.';++-- Per UTC day (the trend's days), the prompts created for the brand (in the+-- topic, when the trend is filtered to one) and the actions a person sent+-- from it. Actions the nightly generator created have no actor on their+-- "created" event and aren't markers.+create or replace function public.insights_trend_markers(+ p_brand_id uuid,+ p_from timestamptz default null,+ p_to timestamptz default null,+ p_topic_id uuid default null+)+returns jsonb+language sql+stable+security invoker+set search_path to 'public'+as $$+ select jsonb_build_object(+ 'prompts_added', coalesce(+ (select jsonb_agg(jsonb_build_object('day', d.day, 'count', d.n) order by d.day)+ from (+ select (p.created_at at time zone 'utc')::date as day, count(*) as n+ from public.prompts p+ join public.prompt_sets ps on ps.id = p.prompt_set_id+ where ps.brand_id = p_brand_id+ and (p_topic_id is null or p.topic_id = p_topic_id)+ and (p_from is null or p.created_at >= p_from)+ and (p_to is null or p.created_at <= p_to)+ group by 1+ ) d),+ '[]'::jsonb),+ 'actions_sent', coalesce(+ (select jsonb_agg(jsonb_build_object('day', d.day, 'action_nos', d.nos) order by d.day)+ from (+ select (a.created_at at time zone 'utc')::date as day,+ array_agg(a.action_no order by a.action_no) as nos+ from public.actions a+ where a.brand_id = p_brand_id+ and (p_from is null or a.created_at >= p_from)+ and (p_to is null or a.created_at <= p_to)+ and exists (+ select 1 from public.action_events e+ where e.action_id = a.id+ and e.event = 'created'+ and e.actor_id is not null)+ group by 1+ ) d),+ '[]'::jsonb)+ );+$$;++revoke all on function public.insights_trend_markers(uuid, timestamptz, timestamptz, uuid) from public;+grant execute on function public.insights_trend_markers(uuid, timestamptz, timestamptz, uuid)+ to authenticated, service_role;++comment on function public.insights_trend_markers(uuid, timestamptz, timestamptz, uuid) is+ 'Insights trend markers (VIS-007, 00136): per UTC day, the prompts created for the brand (optionally in one topic) and the Action Center actions a person sent, between two optional bounds. Security invoker.';+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00147_insights_same_prompts_definer.sql-- ─────────────────────────────────────────────────────────────────────────diff --git a/web/messages/en.json b/web/messages/en.jsonindex 0a9964fa7..5ce2e42fd 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1785,6 +1785,28 @@"steady": "Nothing moved the score by 0.1 pts or more.","newExcluded": "{count, plural, one {# new prompt} other {# new prompts}}{hasDate, select, yes { · {date}} other {}} · own baseline, not counted","newIncluded": "{count, plural, one {# new prompt} other {# new prompts}}{hasDate, select, yes { · {date}} other {}} · counted in the change"+ },+ "trend": {+ "subtitle": "Visibility · {range}",+ "range": {+ "24h": "last 24 hours",+ "7d": "last 7 days",+ "30d": "last 30 days",+ "90d": "last 90 days",+ "all": "all time",+ "custom": "{from} – {to}"+ },+ "noData": "No visibility data for this period yet",+ "pin": "Pin",+ "pinTitle": "Pin up to 5 competitors",+ "pinMenu": "Competitors on the chart",+ "pinLimit": "Up to 5 competitors",+ "pinFailed": "Couldn't save the pinned competitors.",+ "promptsAdded": "{count, plural, one {# prompt} other {# prompts}} added · {date}",+ "actionsSent": "{actions} sent · {date}",+ "moreActions": "{actions} +{count}",+ "goal": "Goal {value}",+ "goalLegend": "Action Center goal"}},"topics": {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsxindex bd4d3449b..32a6711dd 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx@@ -17,14 +17,17 @@ import {Bar,LineChart,Line,+ ReferenceLine,} from 'recharts';import type {ProviderComparisonRow,VisibilityTrendPoint,VisibilityRateTrendData,+ VisibilityRateTrendEntity,SoVByPlatform,} from '@/lib/actions/tracking';import { getFaviconUrl } from '@/lib/favicon';+import { trendAxisTop, type TrendLine, type TrendMarker } from '@/lib/insights-trend';// ─── Adaptive Y-axis ─────────────────────────────────────────────────────────// Visibility scores are theoretically 0–100 but realistic values for most@@ -191,13 +194,6 @@ export function TrendChart({ data }: { data: VisibilityTrendPoint[] }) {// ─── Visibility Rate trend (one line per brand, logo at the line's end) ──────-// 5 lines total, matching the leaderboard: the own brand + top 4 competitors.-// Fixed color order across the five lines: green (own brand), then navy,-// purple, orange, red for the competitors by rate.-const RATE_TREND_PALETTE = ['#1e3a8a', '#a855f7', '#f97316', '#ef4444'];-const RATE_TREND_MAX_COMPETITORS = 4;-const OWN_BRAND_COLOR = '#22c55e';-/** Circle-clipped logo rendered on a line's last data point. */function LogoDot(props: {cx?: number;@@ -234,177 +230,210 @@ function LogoDot(props: {);}-export function VisibilityRateTrendChart({ data }: { data: VisibilityRateTrendData }) {- const { entities, points } = data;- // Hovering a line (or its legend entry) brings it forward and dims the rest.- const [hoveredKey, setHoveredKey] = useState<string | null>(null);+/** A marker's badge at the foot of its dashed line: "+" prompts added, "A" action sent. */+function MarkerBadge({+ viewBox,+ glyph,+ title,+ stack,+}: {+ viewBox?: { x?: number; y?: number; height?: number };+ glyph: string;+ title: string;+ /** Badges on the same day stack upwards. */+ stack: number;+}) {+ if (viewBox?.x == null || viewBox.y == null || viewBox.height == null) return <g />;+ const cx = viewBox.x;+ const cy = viewBox.y + viewBox.height - 9 - stack * 20;+ return (+ <g>+ <title>{title}</title>+ <circle cx={cx} cy={cy} r={8} className="fill-background stroke-muted-foreground/50" />+ <text+ x={cx}+ y={cy + 3.5}+ textAnchor="middle"+ fontSize={10}+ fontWeight={600}+ className="fill-muted-foreground"+ >+ {glyph}+ </text>+ </g>+ );+}- if (points.length === 0) {- return (- <div className="flex items-center justify-center h-[280px] text-sm text-muted-foreground">- No visibility data for this period yet- </div>- );- }+/** The goal line's label, left-aligned above it: the right end is where the lines' logos sit. */+function GoalLabel({ viewBox, text }: { viewBox?: { x?: number; y?: number }; text: string }) {+ if (viewBox?.x == null || viewBox.y == null) return <g />;+ return (+ <text+ x={viewBox.x + 4}+ y={viewBox.y - 4}+ fontSize={10}+ className="fill-green-600 dark:fill-green-500"+ >+ {text}+ </text>+ );+}- // Own brand always plots; competitors capped so a long roster doesn't turn- // the chart into spaghetti. Ranked by the LAST point's value — the rolling- // window makes that equal each entity's score over the charted window, i.e.- // the exact number the leaderboard sorts by — so the chart always plots the- // same brands the leaderboard's top rows show. (Period-averaging the points- // here used to pick a different set on short ranges.)- const lastRate = (key: string) => points[points.length - 1]?.values[key] ?? 0;- const avgRate = (key: string) =>- points.reduce((sum, p) => sum + (p.values[key] ?? 0), 0) / points.length;- const shown = [- ...entities.filter((e) => e.isOwnBrand),- ...entities- .filter((e) => !e.isOwnBrand)- .sort((a, b) => lastRate(b.key) - lastRate(a.key) || avgRate(b.key) - avgRate(a.key))- .slice(0, RATE_TREND_MAX_COMPETITORS),- ].map((entity, i) => ({- ...entity,- // Own brand is index 0, so competitor #1 (highest rate) starts the- // palette at navy.- color: entity.isOwnBrand- ? OWN_BRAND_COLOR- : RATE_TREND_PALETTE[(i - 1) % RATE_TREND_PALETTE.length],- logoUrl: entity.logoUrl ?? (entity.domain ? getFaviconUrl(entity.domain, 64) : ''),+/**+ * The visibility trend (VIS-007): the given lines (yours and the pinned or+ * strongest competitors, colored by the caller), the Action Center goal as a+ * dashed line, and a dashed marker per day prompts were added or actions+ * sent. Hover state lives with the caller, so its chips highlight lines too.+ */+export function VisibilityRateTrendChart({+ data,+ lines,+ markers,+ goal,+ hoveredKey,+ onHover,+}: {+ data: VisibilityRateTrendData;+ lines: TrendLine<VisibilityRateTrendEntity>[];+ /** Markers placed on a point (`date` set). */+ markers: (TrendMarker & { date: string; glyph: string; title: string })[];+ goal: { value: number; label: string } | null;+ hoveredKey: string | null;+ onHover: (key: string | null) => void;+}) {+ const { points } = data;+ const shown = lines.map((line) => ({+ ...line,+ logoUrl: line.logoUrl ?? (line.domain ? getFaviconUrl(line.domain, 64) : ''),}));const chartData = points.map((p) => ({ date: p.date, ...p.values }));const lastIndex = points.length - 1;// Y axis ticks run 5, 15, 25, … and the top one sits just above the- // highest score in view (a 60 peak → axis ends at 65), so the lines use- // the full canvas instead of being squashed under an always-100 scale.- const dataMax = Math.max(0, ...shown.flatMap((e) => points.map((p) => p.values[e.key] ?? 0)));- let yTop = 5;- while (yTop <= dataMax) yTop += 10;+ // highest score in view, the goal included (a 60 peak → axis ends at 65),+ // so the lines use the full canvas instead of being squashed under an+ // always-100 scale.+ const yTop = trendAxisTop(+ shown.flatMap((e) => points.map((p) => p.values[e.key] ?? 0)),+ goal?.value ?? null,+ );const yTicks: number[] = [];for (let tick = 5; tick <= yTop; tick += 10) yTicks.push(tick);- return (- <div className="flex flex-col gap-3">- <ChartContainer height={320}>- {(width) => (- <LineChart- width={width}- height={320}- data={chartData}- margin={{ top: 8, right: 26, left: -24, bottom: 0 }}- >- <XAxis- dataKey="date"- tick={{ fontSize: 11 }}- tickLine={false}- axisLine={false}- className="fill-muted-foreground"- />- <YAxis- domain={[0, yTop]}- ticks={yTicks}- tick={{ fontSize: 11 }}- tickLine={false}- axisLine={false}- className="fill-muted-foreground"- />- <Tooltip- isAnimationActive={false}- content={({ active, payload, label }) => {- if (!active || !payload?.length) return null;- const ordered = [...payload].sort(- (a, b) => ((b.value as number) ?? 0) - ((a.value as number) ?? 0),- );- return (- <div className="rounded-lg border bg-background px-3 py-2 shadow-md text-xs">- <p className="font-medium text-foreground mb-1">{label}</p>- {ordered.map((entry) => {- const entity = shown.find((e) => e.key === entry.dataKey);- if (!entity) return null;- return (- <div key={entity.key} className="flex items-center gap-2">- <span- className="inline-block h-2 w-2 rounded-full shrink-0"- style={{ backgroundColor: entity.color }}- />- <span className="text-muted-foreground">{entity.name}:</span>- <span className="font-medium text-foreground">{entry.value}</span>- </div>- );- })}- </div>- );- }}- />- {/* Render order = z-order: lines are drawn lowest-rate first so- when end-of-line logos overlap, the higher rate sits on top.- A hovered line always wins. */}- {[...shown]- .sort((a, b) => {- if (a.key === hoveredKey) return 1;- if (b.key === hoveredKey) return -1;- return (- (points[lastIndex]?.values[a.key] ?? 0) - (points[lastIndex]?.values[b.key] ?? 0)- );- })- .map((entity) => {- const dimmed = hoveredKey !== null && hoveredKey !== entity.key;- return (- <Line- key={entity.key}- type="monotone"- dataKey={entity.key}- stroke={entity.color}- strokeOpacity={dimmed ? 0.15 : 1}- strokeWidth={entity.key === hoveredKey ? 3 : entity.isOwnBrand ? 2.5 : 1.5}- isAnimationActive={false}- onMouseEnter={() => setHoveredKey(entity.key)}- onMouseLeave={() => setHoveredKey(null)}- dot={- <LogoDot- lastIndex={lastIndex}- color={entity.color}- logoUrl={entity.logoUrl}- entityKey={entity.key}- dimmed={dimmed}- />- }- activeDot={{ r: 3 }}- />- );- })}- </LineChart>- )}- </ChartContainer>+ // Badges on the same day stack, so a prompt and an action marker don't overlap.+ const stackOf = (i: number) =>+ markers.slice(0, i).filter((m) => m.date === markers[i].date).length;- <ul className="flex flex-wrap justify-center gap-x-4 gap-y-1.5">- {shown.map((entity) => (- <li- key={entity.key}- tabIndex={0}- aria-label={entity.name}- className="flex cursor-default items-center gap-1.5 rounded-sm text-xs transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- style={{- opacity: hoveredKey !== null && hoveredKey !== entity.key ? 0.35 : 1,+ return (+ <ChartContainer height={320}>+ {(width) => (+ <LineChart+ width={width}+ height={320}+ data={chartData}+ margin={{ top: 8, right: 26, left: -24, bottom: 0 }}+ >+ <XAxis+ dataKey="date"+ tick={{ fontSize: 11 }}+ tickLine={false}+ axisLine={false}+ className="fill-muted-foreground"+ />+ <YAxis+ domain={[0, yTop]}+ ticks={yTicks}+ tick={{ fontSize: 11 }}+ tickLine={false}+ axisLine={false}+ className="fill-muted-foreground"+ />+ <Tooltip+ isAnimationActive={false}+ content={({ active, payload, label }) => {+ if (!active || !payload?.length) return null;+ const ordered = [...payload].sort(+ (a, b) => ((b.value as number) ?? 0) - ((a.value as number) ?? 0),+ );+ return (+ <div className="rounded-lg border bg-background px-3 py-2 shadow-md text-xs">+ <p className="font-medium text-foreground mb-1">{label}</p>+ {ordered.map((entry) => {+ const entity = shown.find((e) => e.key === entry.dataKey);+ if (!entity) return null;+ return (+ <div key={entity.key} className="flex items-center gap-2">+ <span+ className="inline-block h-2 w-2 rounded-full shrink-0"+ style={{ backgroundColor: entity.color }}+ />+ <span className="text-muted-foreground">{entity.name}:</span>+ <span className="font-medium text-foreground">{entry.value}</span>+ </div>+ );+ })}+ </div>+ );}}- onMouseEnter={() => setHoveredKey(entity.key)}- onMouseLeave={() => setHoveredKey(null)}- onFocus={() => setHoveredKey(entity.key)}- onBlur={() => setHoveredKey(null)}- >- <span- className="h-2.5 w-2.5 shrink-0 rounded-sm"- style={{ background: entity.color }}- aria-hidden+ />+ {goal && (+ <ReferenceLine+ y={goal.value}+ className="stroke-green-600 dark:stroke-green-500"+ strokeDasharray="4 4"+ label={<GoalLabel text={goal.label} />}/>- <span className={entity.isOwnBrand ? 'font-medium' : 'text-muted-foreground'}>- {entity.name}- </span>- </li>- ))}- </ul>- </div>+ )}+ {markers.map((m, i) => (+ <ReferenceLine+ key={`${m.kind}-${m.day}`}+ x={m.date}+ className="stroke-muted-foreground/40"+ strokeDasharray="2 3"+ label={<MarkerBadge glyph={m.glyph} title={m.title} stack={stackOf(i)} />}+ />+ ))}+ {/* Render order = z-order: lines are drawn lowest-rate first so+ when end-of-line logos overlap, the higher rate sits on top.+ A hovered line always wins. */}+ {[...shown]+ .sort((a, b) => {+ if (a.key === hoveredKey) return 1;+ if (b.key === hoveredKey) return -1;+ return (+ (points[lastIndex]?.values[a.key] ?? 0) - (points[lastIndex]?.values[b.key] ?? 0)+ );+ })+ .map((entity) => {+ const dimmed = hoveredKey !== null && hoveredKey !== entity.key;+ return (+ <Line+ key={entity.key}+ type="monotone"+ dataKey={entity.key}+ stroke={entity.color}+ strokeOpacity={dimmed ? 0.15 : 1}+ strokeWidth={entity.key === hoveredKey ? 3 : entity.isOwnBrand ? 2.5 : 1.5}+ isAnimationActive={false}+ onMouseEnter={() => onHover(entity.key)}+ onMouseLeave={() => onHover(null)}+ dot={+ <LogoDot+ lastIndex={lastIndex}+ color={entity.color}+ logoUrl={entity.logoUrl}+ entityKey={entity.key}+ dimmed={dimmed}+ />+ }+ activeDot={{ r: 3 }}+ />+ );+ })}+ </LineChart>+ )}+ </ChartContainer>);}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_trend-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_trend-card.tsxnew file mode 100644index 000000000..fdf5a370e--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_trend-card.tsx@@ -0,0 +1,243 @@+'use client';++import { useState } from 'react';+import dynamic from 'next/dynamic';+import { useTranslations } from 'next-intl';+import { Plus } from 'lucide-react';+import { toast } from 'sonner';+import { Card, CardContent, CardHeader } from '@/components/ui/card';+import { Skeleton } from '@/components/ui/skeleton';+import {+ DropdownMenu,+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import { cn } from '@/lib/utils';+import { useUserRole } from '@/hooks/use-user-role';+import { setPinnedCompetitors } from '@/lib/actions/brand';+import type { VisibilityRateTrendData } from '@/lib/actions/tracking';+import {+ MAX_PINNED_COMPETITORS,+ trendLines,+ trendMarkers,+ type TrendMarker,+ type TrendMarkerData,+} from '@/lib/insights-trend';++const VisibilityRateTrendChart = dynamic(+ () => import('./_charts').then((m) => m.VisibilityRateTrendChart),+ { ssr: false, loading: () => <Skeleton className="h-[320px] w-full" /> },+);++/** A 'YYYY-MM-DD' UTC day as "Sep 29". */+const dayLabel = (day: string) =>+ new Date(`${day}T00:00:00Z`).toLocaleDateString('en-US', {+ month: 'short',+ day: 'numeric',+ timeZone: 'UTC',+ });++/** Action numbers as the Action Center writes them: "AC-61", "AC-3, AC-4", "AC-3, AC-4, AC-5 +2". */+const actionIds = (nos: number[]) =>+ nos+ .slice(0, 3)+ .map((n) => `AC-${n}`)+ .join(', ');++/**+ * The visibility trend card (VIS-007), as in the v2 mockup: the score over+ * the range, your line and the pinned competitors (chips to highlight them,+ * "Pin" to choose up to five, saved on the brand), the Action Center goal,+ * and markers for the days prompts were added and actions sent.+ */+export function TrendCard({+ brandId,+ data,+ markers,+ rangeLabel,+ onPinnedChange,+ className,+}: {+ brandId: string;+ data: VisibilityRateTrendData | null;+ /** Null on the 24h view and when the read failed: no markers, no goal. */+ markers: TrendMarkerData | null;+ /** "last 30 days", "all time", … */+ rangeLabel: string;+ onPinnedChange: (pinned: string[]) => void;+ className?: string;+}) {+ const t = useTranslations('insights.trend');+ const { canManage } = useUserRole();+ const [hoveredKey, setHoveredKey] = useState<string | null>(null);+ const [saving, setSaving] = useState(false);++ if (!data || data.points.length === 0) {+ return (+ <Card className={className}>+ <CardContent className="flex h-[360px] items-center justify-center text-sm text-muted-foreground">+ {t('noData')}+ </CardContent>+ </Card>+ );+ }++ const lines = trendLines(data.entities, data.points, data.pinned);+ const competitors = data.entities.filter((e) => !e.isOwnBrand);+ // The menu edits the lines in view: without pins, the strongest four count+ // as checked, so pinning starts from what the chart shows.+ const onChart = lines.filter((l) => !l.isOwnBrand).map((l) => l.key);++ const togglePin = async (key: string) => {+ const next = onChart.includes(key) ? onChart.filter((k) => k !== key) : [...onChart, key];+ if (saving || next.length === 0 || next.length > MAX_PINNED_COMPETITORS) return;+ const previous = data.pinned;+ onPinnedChange(next);+ setSaving(true);+ try {+ onPinnedChange(await setPinnedCompetitors(brandId, next));+ } catch {+ onPinnedChange(previous);+ toast.error(t('pinFailed'));+ } finally {+ setSaving(false);+ }+ };++ const describe = (m: TrendMarker) =>+ m.kind === 'prompts'+ ? t('promptsAdded', { count: m.count, date: dayLabel(m.day) })+ : t('actionsSent', {+ actions:+ m.actionNos.length > 3+ ? t('moreActions', { actions: actionIds(m.actionNos), count: m.actionNos.length - 3 })+ : actionIds(m.actionNos),+ date: dayLabel(m.day),+ });+ // Every marker is listed below the chart; only those with a point are drawn on it.+ const placed = markers+ ? trendMarkers(markers, data.points).map((m) => ({+ ...m,+ glyph: m.kind === 'prompts' ? '+' : 'A',+ title: describe(m),+ }))+ : [];+ const goal =+ markers?.goal != null+ ? { value: markers.goal, label: t('goal', { value: markers.goal }) }+ : null;++ return (+ <Card className={className}>+ <CardHeader className="pb-2">+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <div className="text-3xl font-bold tabular-nums">{data.summary.rate}</div>+ <div className="text-xs text-muted-foreground">+ {t('subtitle', { range: rangeLabel })}+ </div>+ </div>+ <ul className="flex flex-wrap items-center gap-1.5">+ {lines.map((line) => (+ <li+ key={line.key}+ tabIndex={0}+ className="inline-flex h-[26px] cursor-default items-center gap-1.5 rounded-full border px-2.5 text-xs transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ style={{ opacity: hoveredKey !== null && hoveredKey !== line.key ? 0.4 : 1 }}+ onMouseEnter={() => setHoveredKey(line.key)}+ onMouseLeave={() => setHoveredKey(null)}+ onFocus={() => setHoveredKey(line.key)}+ onBlur={() => setHoveredKey(null)}+ >+ <span+ className="h-2 w-2 shrink-0 rounded-full"+ style={{ background: line.color }}+ aria-hidden+ />+ <span className={cn(line.isOwnBrand && 'font-medium')}>{line.name}</span>+ </li>+ ))}+ {canManage && competitors.length > 0 && (+ <li>+ <DropdownMenu>+ <DropdownMenuTrigger+ disabled={saving}+ title={t('pinTitle')}+ className="inline-flex h-[26px] items-center gap-1 rounded-full border border-dashed px-2.5 text-xs text-muted-foreground transition-colors hover:text-foreground disabled:opacity-50"+ >+ <Plus className="h-3 w-3" aria-hidden />+ {t('pin')}+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="max-h-80 min-w-52 overflow-y-auto">+ <DropdownMenuGroup>+ <DropdownMenuLabel>{t('pinMenu')}</DropdownMenuLabel>+ <DropdownMenuSeparator />+ {competitors.map((c) => {+ const checked = onChart.includes(c.key);+ return (+ <DropdownMenuCheckboxItem+ key={c.key}+ checked={checked}+ disabled={+ saving ||+ // At most five, and at least one: an empty list+ // would bring back the automatic four.+ (checked+ ? onChart.length === 1+ : onChart.length >= MAX_PINNED_COMPETITORS)+ }+ onCheckedChange={() => togglePin(c.key)}+ >+ {c.name}+ </DropdownMenuCheckboxItem>+ );+ })}+ </DropdownMenuGroup>+ <DropdownMenuSeparator />+ <div className="px-2 py-1 text-xs text-muted-foreground">{t('pinLimit')}</div>+ </DropdownMenuContent>+ </DropdownMenu>+ </li>+ )}+ </ul>+ </div>+ </CardHeader>+ <CardContent className="space-y-2">+ <VisibilityRateTrendChart+ data={data}+ lines={lines}+ markers={placed.filter(+ (m): m is (typeof placed)[number] & { date: string } => m.date !== null,+ )}+ goal={goal}+ hoveredKey={hoveredKey}+ onHover={setHoveredKey}+ />+ {(placed.length > 0 || goal) && (+ <ul className="flex flex-wrap gap-x-3.5 gap-y-1 text-[11.5px] text-muted-foreground">+ {placed.map((m) => (+ <li key={`${m.kind}-${m.day}`} className="flex items-center gap-1.5">+ <span className="font-semibold text-foreground/70" aria-hidden>+ {m.glyph}+ </span>+ {m.title}+ </li>+ ))}+ {goal && (+ <li className="flex items-center gap-1.5">+ <span className="tracking-tighter text-green-600 dark:text-green-500" aria-hidden>+ - - -+ </span>+ {t('goalLegend')}+ </li>+ )}+ </ul>+ )}+ </CardContent>+ </Card>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsxindex e8c55ab8a..3d7c5851c 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx@@ -4,16 +4,7 @@ import { useState, useRef, useEffect, useCallback } from 'react';import { Link, useRouter } from '@/i18n/navigation';import { useSearchParams } from 'next/navigation';import { useTranslations } from 'next-intl';-import dynamic from 'next/dynamic';import { Skeleton } from '@/components/ui/skeleton';-const VisibilityRateTrendChart = dynamic(- () => import('./_charts').then((m) => m.VisibilityRateTrendChart),- {- ssr: false,- loading: () => <Skeleton className="h-64 w-full" />,- },-);-import { MetricBreakdownSheet, type BreakdownTab } from './_metric-breakdown-sheet';import { FormulaDialog } from './_formula-dialog';import { useBrandStore } from '@/stores/use-brand-store';@@ -56,7 +47,6 @@ import {CalendarX2,Play,TrendingUp,- TrendingDown,Loader2,FlaskConical,Users,@@ -84,10 +74,13 @@ import { readUrlChoice, readUrlParam, writeUrlParams } from '@/lib/url-state';import type { PromptComparison } from '@/lib/insights-same-prompts';import type { KpiSeriesDay } from '@/lib/insights-kpis';import type { PlatformChange, PlatformTableRow } from '@/lib/insights-summary';+import { formatWindowBound } from './kpi-format';import { KpiRows } from './_kpi-cards';import { SummaryLine } from './_summary-line';import { PlatformTable } from './_platform-table';import { Leaderboard } from './_leaderboard';+import { TrendCard } from './_trend-card';+import type { TrendMarkerData } from '@/lib/insights-trend';import { WhyChanged } from './_why-changed';import type { WhyChanged as WhyChangedData } from '@/lib/insights-drivers';@@ -109,7 +102,8 @@ interface InsightsFilters {}const DEFAULT_FILTERS: InsightsFilters = {- datePreset: '24h',+ // 30 days, as in the v2 mockup (VIS-007); 24h stays one click away.+ datePreset: '30d',dateFrom: '',dateTo: '',region: '',@@ -861,6 +855,7 @@ export default function InsightsPage() {const [platformChanges, setPlatformChanges] = useState<PlatformChange[] | null>(null);const [platforms, setPlatforms] = useState<PlatformTableRow[] | null>(null);const [whyChanged, setWhyChanged] = useState<WhyChangedData | null>(null);+ const [trendMarkers, setTrendMarkers] = useState<TrendMarkerData | null>(null);const [breakdownMetric, setBreakdownMetric] = useState<BreakdownMetric | null>(null);const [breakdownTab, setBreakdownTab] = useState<BreakdownTab | undefined>(undefined);// The window and filters the cards were last loaded with (the 24h view@@ -953,6 +948,7 @@ export default function InsightsPage() {setPlatformChanges(insights.platformChanges);setPlatforms(insights.platforms);setWhyChanged(insights.whyChanged);+ setTrendMarkers(insights.trendMarkers);setHasAnyData(insights.hasAnyData);// Group raw model slugs by their resolved display name so different@@ -1305,6 +1301,15 @@ export default function InsightsPage() {? formatRelative(summary.lastCheckedAt, tCommon): 'Never';+ // The trend's subtitle (VIS-007): "Visibility · last 30 days".+ const trendRangeLabel =+ filters.datePreset === 'custom'+ ? t('trend.range.custom', {+ from: formatWindowBound(filters.dateFrom),+ to: formatWindowBound(filters.dateTo),+ })+ : t(`trend.range.${filters.datePreset}`);+const handleResetFilters = () => {const resetFilters = { ...DEFAULT_FILTERS };setFilters(resetFilters);@@ -1427,51 +1432,16 @@ export default function InsightsPage() {{/* Competitor Comparison */}{competitorData ? (<div className="grid grid-cols-1 gap-4 lg:grid-cols-5">- <Card className="lg:col-span-3">- <CardHeader className="pb-2">- {rateTrend ? (- <div>- <div className="text-3xl font-bold tabular-nums">- {rateTrend.summary.rate}- </div>- <div className="mt-1 flex items-center gap-2 text-xs">- {rateTrend.summary.change !== null && (- <span- className={cn(- 'flex items-center gap-0.5 font-medium',- rateTrend.summary.change >= 0- ? 'text-emerald-600 dark:text-emerald-400'- : 'text-red-600 dark:text-red-400',- )}- >- {rateTrend.summary.change >= 0 ? (- <TrendingUp className="h-3 w-3" />- ) : (- <TrendingDown className="h-3 w-3" />- )}- {rateTrend.summary.change >= 0 ? '+' : ''}- {rateTrend.summary.change} pts- </span>- )}- </div>- </div>- ) : (- <CardTitle className="flex items-center gap-2 text-sm font-medium">- <Users className="h-4 w-4" />- AI Visibility — Brand vs Competitors- </CardTitle>- )}- </CardHeader>- <CardContent>- {rateTrend ? (- <VisibilityRateTrendChart data={rateTrend} />- ) : (- <div className="flex items-center justify-center h-[280px] text-sm text-muted-foreground">- No visibility data for this period yet- </div>- )}- </CardContent>- </Card>+ <TrendCard+ className="lg:col-span-3"+ brandId={brand.id}+ data={rateTrend}+ markers={trendMarkers}+ rangeLabel={trendRangeLabel}+ onPinnedChange={(pinned) =>+ setRateTrend((current) => current && { ...current, pinned })+ }+ /><LeaderboardclassName="lg:col-span-2"diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/summary-format.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/insights/summary-format.test.tsindex 8e662d82b..83133c734 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/summary-format.test.ts+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/summary-format.test.ts@@ -25,6 +25,7 @@ const trend = (rate: number, change: number | null) =>entities: [],points: [],summary: { rate, prevRate: null, change, prevFrom: '2026-08-14', prevTo: '2026-09-12' },+ pinned: [],}) as VisibilityRateTrendData;const leaderboard = (...brands: [string, number, boolean?][]) =>diff --git a/web/src/lib/actions/brand-pins.test.ts b/web/src/lib/actions/brand-pins.test.tsnew file mode 100644index 000000000..e4252b60b--- /dev/null+++ b/web/src/lib/actions/brand-pins.test.ts@@ -0,0 +1,71 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/** setPinnedCompetitors (VIS-007) saves only the brand's own competitors, five at most. */++let owned: string[] = [];+let updated: unknown = null;+let updatedRows = 1;++vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }));++vi.mock('@/lib/supabase/server', () => ({+ createClient: vi.fn(async () => ({+ from: (table: string) =>+ table === 'competitors'+ ? {+ select: () => ({+ eq: () => ({+ in: async (_col: string, ids: string[]) => ({+ data: ids.filter((id) => owned.includes(id)).map((id) => ({ id })),+ error: null,+ }),+ }),+ }),+ }+ : {+ update: (row: unknown) => {+ updated = row;+ return {+ eq: () => ({+ select: async () => ({+ data: Array.from({ length: updatedRows }, () => ({ id: 'b1' })),+ error: null,+ }),+ }),+ };+ },+ },+ })),+}));++const { setPinnedCompetitors } = await import('./brand');++describe('setPinnedCompetitors', () => {+ beforeEach(() => {+ owned = ['a', 'b', 'c', 'd', 'e', 'f'];+ updated = null;+ updatedRows = 1;+ });++ it('keeps pin order, drops duplicates and other brands’ ids, and stops at five', async () => {+ const saved = await setPinnedCompetitors('b1', ['c', 'x', 'a', 'c', 'b', 'd', 'e', 'f']);++ expect(saved).toEqual(['c', 'a', 'b', 'd', 'e']);+ expect(updated).toEqual({ insights_pinned_competitors: ['c', 'a', 'b', 'd', 'e'] });+ });++ it('clears the pins', async () => {+ expect(await setPinnedCompetitors('b1', [])).toEqual([]);+ expect(updated).toEqual({ insights_pinned_competitors: [] });+ });++ it('rejects a payload that is not a list of ids', async () => {+ await expect(setPinnedCompetitors('b1', 'abc' as unknown as string[])).rejects.toThrow(/list/);+ expect(updated).toBeNull();+ });++ it('fails when the write is denied', async () => {+ updatedRows = 0;+ await expect(setPinnedCompetitors('b1', ['a'])).rejects.toThrow(/permission/);+ });+});diff --git a/web/src/lib/actions/brand.ts b/web/src/lib/actions/brand.tsindex ebe1ec721..ce6ad1f82 100644--- a/web/src/lib/actions/brand.ts+++ b/web/src/lib/actions/brand.ts@@ -7,6 +7,7 @@ import { isWithinLimit } from '@/config/plans';import { slugify } from '@/lib/slug';import { API_BASE_URL } from '@/config/api';import type { Brand, BrandDomain } from '@/types';+import { MAX_PINNED_COMPETITORS } from '@/lib/insights-trend';function mapDomainRow(d: Record<string, unknown>): BrandDomain {return {@@ -339,6 +340,45 @@ export async function setBrandActive(brandId: string, isActive: boolean): PromisrevalidatePath('/dashboard/brands');}+/**+ * Pin competitors on the Insights visibility trend (VIS-007): saved on the+ * brand, in pin order, so the whole team sees the same lines whatever the+ * range. At most MAX_PINNED_COMPETITORS; ids that aren't this brand's+ * competitors are dropped. Returns what was saved.+ *+ * RLS gates the write like every brand setting: admins and managers only.+ */+export async function setPinnedCompetitors(+ brandId: string,+ competitorIds: string[],+): Promise<string[]> {+ if (!Array.isArray(competitorIds) || competitorIds.some((id) => typeof id !== 'string')) {+ throw new Error('Pinned competitors must be a list of competitor ids.');+ }+ const supabase = await createClient();+ const wanted = [...new Set(competitorIds)];++ const { data: owned, error: ownedError } = wanted.length+ ? await supabase.from('competitors').select('id').eq('brand_id', brandId).in('id', wanted)+ : { data: [], error: null };+ if (ownedError) throw new Error(ownedError.message);+ const ownedIds = new Set((owned ?? []).map((c) => c.id));+ const pinned = wanted.filter((id) => ownedIds.has(id)).slice(0, MAX_PINNED_COMPETITORS);++ // Return the updated row so RLS silently denying the write surfaces as an+ // error, as in setBrandActive.+ const { data, error } = await supabase+ .from('brands')+ .update({ insights_pinned_competitors: pinned })+ .eq('id', brandId)+ .select('id');+ if (error) throw new Error(error.message);+ if (!data || data.length === 0) {+ throw new Error('Brand not found or you do not have permission to update it.');+ }+ return pinned;+}+export interface BrandCardSummary {brandId: string;visibility7d: number;diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.tsindex f47c9f45e..20afb8442 100644--- a/web/src/lib/actions/tracking.ts+++ b/web/src/lib/actions/tracking.ts@@ -46,6 +46,7 @@ import { getPromptSuggestions } from '@/lib/actions/prompt-suggestions';import { aggregatePromptVolumeClusters } from '@/lib/prompt-volume-clusters';import { percentageChange } from '@/lib/metrics';import { parseChangeDrivers, whyChanged, type WhyChanged } from '@/lib/insights-drivers';+import { parseTrendMarkers, type TrendMarkerData } from '@/lib/insights-trend';import {parsePlatformRows,platformChanges,@@ -742,6 +743,12 @@ export interface InsightsData {* period. Null for All time, before the backfill, or when the read failed.*/whyChanged: WhyChanged | null;+ /**+ * The trend's markers and goal (VIS-007): prompts added and actions sent per+ * day, and the AI visibility KPI's target. Null on the 24h view, whose+ * chart has no days to mark, or when the read failed.+ */+ trendMarkers: TrendMarkerData | null;/** The run ledger, when the 24h window was anchored to it (`anchor24h`). */trackingWindow: TrackingWindow | null;}@@ -839,6 +846,7 @@ type WindowedInsights = Pick<| 'platformChanges'| 'platforms'| 'whyChanged'+ | 'trendMarkers'>;type InsightsFilterArgs = {@@ -891,6 +899,7 @@ async function loadWindowedInsights(kpiSeries,platformData,drivers,+ trendMarkers,] = await Promise.all([getInsightsSummary(brandId, filterOpts),lenient(@@ -911,6 +920,7 @@ async function loadWindowedInsights(lenient(getKpiSeries(brandId, filterOpts), null, 'KPI sparklines'),lenient(getPlatformData(brandId, filterOpts), null, 'platforms'),lenient(getChangeDrivers(brandId, filterOpts), null, 'why it changed'),+ lenient(getTrendMarkers(brandId, filterOpts), null, 'trend markers'),]);const windowed = {...(comparisonWindows(filterOpts).prev ? { summary, sov } : withoutChanges(summary, sov)),@@ -931,6 +941,7 @@ async function loadWindowedInsights(whyChanged:drivers &&whyChanged(drivers, resolveProvider, { samePrompts: filterOpts.samePrompts !== false }),+ trendMarkers,};return withPromptComparison(windowed, same, filterOpts.samePrompts !== false);}@@ -1025,6 +1036,42 @@ async function getKpiSeries(return parseKpiSeries(data);}+/**+ * The trend's markers and goal (VIS-007): per UTC day in the charted range,+ * the prompts added and the actions people sent, and the target of the+ * brand's active AI visibility KPI. Null on the 24h view, charted by run+ * rather than by day.+ */+async function getTrendMarkers(+ brandId: string,+ opts?: InsightsFilterArgs,+): Promise<TrendMarkerData | null> {+ if (!opts?.days) return null;+ const supabase = await dbClient();+ const { dayFrom, dayTo } = opts.days;+ const [markers, kpi] = await Promise.all([+ supabase.rpc('insights_trend_markers', {+ p_brand_id: brandId,+ p_from: dayFrom ? `${dayFrom}T00:00:00Z` : undefined,+ p_to: dayTo ? `${dayTo}T23:59:59.999Z` : undefined,+ p_topic_id: opts.topicId ?? undefined,+ }),+ supabase+ .from('kpi_definitions')+ .select('target')+ .eq('brand_id', brandId)+ .eq('kpi_key', 'ai_visibility')+ .eq('is_active', true)+ .maybeSingle(),+ ]);+ if (markers.error) throw new Error(markers.error.message);+ return {+ ...parseTrendMarkers(markers.data),+ // A missing or unreadable KPI only means no goal line.+ goal: kpi.data ? Number(kpi.data.target) : null,+ };+}+/*** The inputs of "Why it changed" (VIS-009): each prompt's and engine's* Visibility components in both comparison windows, over the same prompts as@@ -2906,6 +2953,8 @@ export interface VisibilityRateTrendEntity {export interface VisibilityRateTrendPoint {/** Short label for the X axis, e.g. "Jul 28". */date: string;+ /** The UTC day it covers, 'YYYY-MM-DD' (VIS-007: markers are placed by day). */+ day: string;/** Per-entity rate for the day, keyed by entity key. 0 = tracked but not visible. */values: Record<string, number>;}@@ -2935,6 +2984,8 @@ export interface VisibilityRateTrendData {entities: VisibilityRateTrendEntity[];points: VisibilityRateTrendPoint[];summary: VisibilityRateTrendSummary;+ /** Competitors pinned on the chart (VIS-007), in pin order; ids of deleted ones dropped. */+ pinned: string[];}interface VisibilityRateTrendRow {@@ -3023,6 +3074,7 @@ export async function getVisibilityRateTrend({ data: brand },{ data: brandDomains },{ data: competitors },+ { data: pins },rpcRes,visCurRes,visPrevRes,@@ -3030,6 +3082,9 @@ export async function getVisibilityRateTrend(supabase.from('brands').select('name, logo_url').eq('id', brandId).single(),supabase.from('brand_domains').select('domain, is_primary').eq('brand_id', brandId),supabase.from('competitors').select('id, name, domain').eq('brand_id', brandId),+ // Read on its own: without the pins (00136) the chart falls back to the+ // strongest competitors, and the brand's name and logo still load.+ supabase.from('brands').select('insights_pinned_competitors').eq('id', brandId).single(),// The chart plots a rolling window per day, so the earliest displayed// days need trailing data from before the display range (all-time needs// no warm-up — the window expands from the first row).@@ -3157,6 +3212,7 @@ export async function getVisibilityRateTrend(month: 'short',day: 'numeric',}),+ day: row.day,values,});}@@ -3179,7 +3235,10 @@ export async function getVisibilityRateTrend(prevTo: prevWin ? windowBounds(prevWin).to : '',};- return { entities, points, summary };+ const competitorIds = new Set((competitors ?? []).map((c) => c.id));+ const pinned = (pins?.insights_pinned_competitors ?? []).filter((id) => competitorIds.has(id));++ return { entities, points, summary, pinned };}// ─── Head-to-Head Competitor Comparison ─────────────────────────────────────diff --git a/web/src/lib/insights-trend.test.ts b/web/src/lib/insights-trend.test.tsnew file mode 100644index 000000000..a6dd53c1f--- /dev/null+++ b/web/src/lib/insights-trend.test.ts@@ -0,0 +1,126 @@+import { describe, expect, it } from 'vitest';+import {+ OWN_BRAND_COLOR,+ parseTrendMarkers,+ trendAxisTop,+ trendLines,+ trendMarkers,+} from './insights-trend';++const entity = (key: string, isOwnBrand = false) => ({ key, name: key.toUpperCase(), isOwnBrand });+const entities = [+ entity('you', true),+ entity('a'),+ entity('b'),+ entity('c'),+ entity('d'),+ entity('e'),+];++const point = (day: string, values: Record<string, number> = {}) => ({+ date: day.slice(5),+ day,+ values,+});++describe('trendLines', () => {+ const points = [+ point('2026-10-01', { a: 10, b: 50, c: 30, d: 20, e: 40 }),+ point('2026-10-02', { a: 60, b: 50, c: 30, d: 20, e: 40 }),+ ];++ it('draws you and the pinned competitors in pin order, whatever the scores', () => {+ const lines = trendLines(entities, points, ['d', 'gone', 'a']);++ expect(lines.map((l) => l.key)).toEqual(['you', 'd', 'a']);+ expect(lines[0].color).toBe(OWN_BRAND_COLOR);+ // A pin keeps its color when the range (and so the ranking) changes.+ expect(trendLines(entities, points.slice(0, 1), ['d', 'a'])[1].color).toBe(lines[1].color);+ });++ it('draws the strongest four at the end of the range without pins', () => {+ expect(trendLines(entities, points, []).map((l) => l.key)).toEqual(['you', 'a', 'b', 'e', 'c']);+ });+});++describe('trendMarkers', () => {+ const points = [point('2026-09-29'), point('2026-10-01'), point('2026-10-04')];++ it('puts each marker on the point of its day, or the next one with a point', () => {+ const markers = trendMarkers(+ {+ promptsAdded: [{ day: '2026-09-29', count: 509 }],+ actionsSent: [{ day: '2026-10-03', actionNos: [61] }],+ goal: null,+ },+ points,+ );++ expect(markers).toEqual([+ { kind: 'prompts', day: '2026-09-29', date: '09-29', count: 509 },+ { kind: 'actions', day: '2026-10-03', date: '10-04', actionNos: [61] },+ ]);+ });++ it('keeps the three biggest prompt days and the three latest action days', () => {+ const markers = trendMarkers(+ {+ promptsAdded: [+ { day: '2026-09-29', count: 5 },+ { day: '2026-09-30', count: 50 },+ { day: '2026-10-01', count: 2 },+ { day: '2026-10-02', count: 40 },+ ],+ actionsSent: ['2026-09-28', '2026-09-29', '2026-10-01', '2026-10-02'].map((day, i) => ({+ day,+ actionNos: [i + 1],+ })),+ goal: null,+ },+ points,+ );++ expect(markers.filter((m) => m.kind === 'prompts').map((m) => m.day)).toEqual([+ '2026-09-29',+ '2026-09-30',+ '2026-10-02',+ ]);+ expect(markers.filter((m) => m.kind === 'actions').map((m) => m.day)).toEqual([+ '2026-09-29',+ '2026-10-01',+ '2026-10-02',+ ]);+ });++ it('lists a day after the last point without placing it on the chart', () => {+ expect(+ trendMarkers(+ { promptsAdded: [{ day: '2026-10-05', count: 3 }], actionsSent: [], goal: null },+ points,+ ),+ ).toEqual([{ kind: 'prompts', day: '2026-10-05', date: null, count: 3 }]);+ });+});++describe('parseTrendMarkers', () => {+ it('reads the RPC payload', () => {+ expect(+ parseTrendMarkers({+ prompts_added: [{ day: '2026-10-12', count: '7' }],+ actions_sent: [{ day: '2026-10-13', action_nos: ['3', 4] }],+ }),+ ).toEqual({+ promptsAdded: [{ day: '2026-10-12', count: 7 }],+ actionsSent: [{ day: '2026-10-13', actionNos: [3, 4] }],+ });+ expect(parseTrendMarkers(null)).toEqual({ promptsAdded: [], actionsSent: [] });+ });+});++describe('trendAxisTop', () => {+ it('keeps the goal on the chart', () => {+ expect(trendAxisTop([12, 17.4], null)).toBe(25);+ expect(trendAxisTop([12, 17.4], 50)).toBe(55);+ expect(trendAxisTop([], null)).toBe(5);+ });+});diff --git a/web/src/lib/insights-trend.ts b/web/src/lib/insights-trend.tsnew file mode 100644index 000000000..59c6fb433--- /dev/null+++ b/web/src/lib/insights-trend.ts@@ -0,0 +1,131 @@+/**+ * The Insights visibility trend (VIS-007), as in the v2 mockup: your line+ * and the competitors you pin (they stay the same whatever the range),+ * markers for the days prompts were added and Action Center actions were+ * sent, and the Action Center goal. Kept apart from the chart so the rules+ * are tested on their own.+ */++/** At most this many competitors can be pinned (also a check on brands, 00136). */+export const MAX_PINNED_COMPETITORS = 5;+/** Without pins, the chart shows this many: the strongest at the end of the range. */+const AUTO_COMPETITORS = 4;+/** Markers of each kind shown at once, so the chart stays readable. */+const MARKERS_PER_KIND = 3;++export const OWN_BRAND_COLOR = '#22c55e';+/** Competitor colors in line order: pin order, or rank without pins. */+const COMPETITOR_PALETTE = ['#1e3a8a', '#a855f7', '#f97316', '#ef4444', '#0d9488'];++interface Entity {+ key: string;+ name: string;+ isOwnBrand: boolean;+}++interface Point {+ date: string;+ day: string;+ values: Record<string, number>;+}++export type TrendLine<E extends Entity = Entity> = E & { color: string };++/**+ * The lines to draw: yours, then the pinned competitors in pin order, or,+ * with nothing pinned, the strongest four at the end of the range (ties+ * broken by the range average), as before pins.+ */+export function trendLines<E extends Entity>(+ entities: E[],+ points: Point[],+ pinned: string[],+): TrendLine<E>[] {+ const own = entities.filter((e) => e.isOwnBrand);+ const competitors = entities.filter((e) => !e.isOwnBrand);+ const byKey = new Map(competitors.map((e) => [e.key, e]));+ const pins = pinned.map((key) => byKey.get(key)).filter((e): e is E => e !== undefined);++ const last = (key: string) => points[points.length - 1]?.values[key] ?? 0;+ const avg = (key: string) =>+ points.reduce((sum, p) => sum + (p.values[key] ?? 0), 0) / Math.max(points.length, 1);+ const shown =+ pins.length > 0+ ? pins.slice(0, MAX_PINNED_COMPETITORS)+ : [...competitors]+ .sort((a, b) => last(b.key) - last(a.key) || avg(b.key) - avg(a.key))+ .slice(0, AUTO_COMPETITORS);++ return [+ ...own.map((e) => ({ ...e, color: OWN_BRAND_COLOR })),+ ...shown.map((e, i) => ({ ...e, color: COMPETITOR_PALETTE[i % COMPETITOR_PALETTE.length] })),+ ];+}++export interface TrendMarkerData {+ promptsAdded: { day: string; count: number }[];+ actionsSent: { day: string; actionNos: number[] }[];+ /** The active "AI visibility" Action Center KPI's target; null without one. */+ goal: number | null;+}++/** The insights_trend_markers payload (00136). */+export function parseTrendMarkers(raw: unknown): Omit<TrendMarkerData, 'goal'> {+ const r = (raw ?? {}) as Record<string, unknown>;+ const rows = (v: unknown) => (Array.isArray(v) ? (v as Record<string, unknown>[]) : []);+ return {+ promptsAdded: rows(r.prompts_added).map((d) => ({+ day: String(d.day),+ count: Number(d.count ?? 0),+ })),+ actionsSent: rows(r.actions_sent).map((d) => ({+ day: String(d.day),+ actionNos: Array.isArray(d.action_nos) ? d.action_nos.map(Number) : [],+ })),+ };+}++export type TrendMarker =+ | { kind: 'prompts'; day: string; date: string | null; count: number }+ | { kind: 'actions'; day: string; date: string | null; actionNos: number[] };++/**+ * The markers, each on the chart point of its day (or the next day with a+ * point): the days the most prompts were added and the latest days actions+ * were sent, three of each at most, in day order. A day after the last point+ * (the latest run hasn't landed yet) gets no `date`: it is listed under the+ * chart but not drawn on a day it didn't happen.+ */+export function trendMarkers(data: TrendMarkerData, points: Point[]): TrendMarker[] {+ const dateOf = (day: string) => points.find((p) => p.day >= day)?.date ?? null;++ const prompts = [...data.promptsAdded]+ .sort((a, b) => b.count - a.count || b.day.localeCompare(a.day))+ .slice(0, MARKERS_PER_KIND)+ .map((d) => ({ kind: 'prompts' as const, day: d.day, date: dateOf(d.day), count: d.count }));+ const actions = [...data.actionsSent]+ .sort((a, b) => b.day.localeCompare(a.day))+ .slice(0, MARKERS_PER_KIND)+ .map((d) => ({+ kind: 'actions' as const,+ day: d.day,+ date: dateOf(d.day),+ actionNos: d.actionNos,+ }));++ return [...prompts, ...actions].sort(+ (a, b) => a.day.localeCompare(b.day) || a.kind.localeCompare(b.kind),+ );+}++/**+ * The Y axis top: ticks run 5, 15, 25, … and the top one sits just above+ * the highest value in view, the goal included, so the goal line is never+ * cut off.+ */+export function trendAxisTop(values: number[], goal: number | null): number {+ const max = Math.max(0, ...values, goal ?? 0);+ let top = 5;+ while (top <= max) top += 10;+ return top;+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex da9a6efb8..4afb50713 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -552,6 +552,7 @@ export type Database = {gsc_property: string | nullid: stringindustry: string | null+ insights_pinned_competitors: string[]is_active: booleanlanguage: string | nulllogo_url: string | null@@ -571,6 +572,7 @@ export type Database = {gsc_property?: string | nullid?: stringindustry?: string | null+ insights_pinned_competitors?: string[]is_active?: booleanlanguage?: string | nulllogo_url?: string | null@@ -590,6 +592,7 @@ export type Database = {gsc_property?: string | nullid?: stringindustry?: string | null+ insights_pinned_competitors?: string[]is_active?: booleanlanguage?: string | nulllogo_url?: string | null@@ -3187,6 +3190,15 @@ export type Database = {}Returns: Json}+ insights_trend_markers: {+ Args: {+ p_brand_id: string+ p_from?: string+ p_to?: string+ p_topic_id?: string+ }+ Returns: Json+ }normalize_page_path: { Args: { p_url: string }; Returns: string }import_prompts: {Args: {