Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(prompts): add a Positions column with a per-platform positions panel (#1003)

Gökhan Geyikef04aa87558d
diff --git a/web/public/perplexity.svg b/web/public/perplexity.svg
index 41e8ddd35..7503bab40 100644
--- a/web/public/perplexity.svg
+++ b/web/public/perplexity.svg
@@ -1 +1 @@
-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" class="w-full h-full"> <path d="M23.566,1.398l-9.495,9.504h9.495V1.398v2.602V1.398Zm-9.496,9.504L4.574,1.398v9.504h9.496Zm-.021-10.902v36m9.517-15.596l-9.495-9.504v13.625l9.495,9.504v-13.625Zm-18.991,0l9.496-9.504v13.625l-9.496,9.504v-13.625ZM.5,10.9v13.57h4.074v-4.066l9.496-9.504H.5Zm13.57,0l9.495,9.504v4.066h4.075v-13.57h-13.57Z" fill="none" stroke="#20808d" stroke-miterlimit="10"></path> </svg>
\ No newline at end of file
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="-5.93 -2 40 40" class="w-full h-full"> <path d="M23.566,1.398l-9.495,9.504h9.495V1.398v2.602V1.398Zm-9.496,9.504L4.574,1.398v9.504h9.496Zm-.021-10.902v36m9.517-15.596l-9.495-9.504v13.625l9.495,9.504v-13.625Zm-18.991,0l9.496-9.504v13.625l-9.496,9.504v-13.625ZM.5,10.9v13.57h4.074v-4.066l9.496-9.504H.5Zm13.57,0l9.495,9.504v4.066h4.075v-13.57h-13.57Z" fill="none" stroke="#20808d" stroke-miterlimit="10"></path> </svg>
\ No newline at end of file
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/citations/url/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/citations/url/page.tsx
index d3f446468..da41a4d31 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/citations/url/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/citations/url/page.tsx
@@ -28,6 +28,7 @@ import {
} from '@/components/citations/filter-bar';
import { AddCompetitorButton } from '@/components/citations/add-competitor-button';
import { CategoryBadge, DomainFavicon, PlatformsCell } from '@/components/citations/source-cells';
+import { PositionLabel } from '@/components/position-label';
import { TablePager, usePagination } from '@/components/table-pager';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
@@ -103,29 +104,6 @@ function SentimentBadge({ sentiment }: { sentiment: string | null }) {
);
}
-/** "Early · #2 of 7" — where in the answer the URL's first citation sits. */
-function PositionCell({ rank, totalSources }: { rank: number; totalSources: number }) {
- const ratio = totalSources > 1 ? (rank - 1) / (totalSources - 1) : 0;
- const tone = ratio <= 1 / 3 ? 'Early' : ratio >= 2 / 3 ? 'Late' : 'Mid';
- return (
- <span className="text-xs tabular-nums whitespace-nowrap">
- <span
- className={cn(
- 'font-medium',
- tone === 'Early' && 'text-emerald-600 dark:text-emerald-400',
- tone === 'Late' && 'text-amber-600 dark:text-amber-400',
- )}
- >
- {tone}
- </span>
- <span className="text-muted-foreground">
- {' '}
- · #{rank} of {totalSources}
- </span>
- </span>
- );
-}
-
export default function CitationUrlDetailPage() {
const { getActiveBrand } = useBrandStore();
const brand = getActiveBrand();
@@ -471,7 +449,8 @@ export default function CitationUrlDetailPage() {
)}
</TableCell>
<TableCell className="pr-6">
- <PositionCell rank={o.rank} totalSources={o.totalSources} />
+ {/* Where in the answer the URL's first citation sits. */}
+ <PositionLabel rank={o.rank} total={o.totalSources} />
</TableCell>
</TableRow>
))}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
index 41b8fa362..e069593ea 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
@@ -111,6 +111,10 @@ import { formatRelative } from '@/lib/format-relative';
import { compareNullsLast, type SortDir } from './prompt-sort';
import { formatCompactNumber } from '@/lib/format';
import { usePagination, TablePager } from '@/components/table-pager';
+import {
+ PromptPositionsSheet,
+ type PositionsPrompt,
+} from '@/components/prompts/prompt-positions-sheet';
// ─── Info Tooltip ─────────────────────────────────────────────────────────────
@@ -1015,6 +1019,10 @@ export default function PromptsPage() {
[rangePreset, customFrom, customTo],
);
const rangeLabel = promptRangeLabel(rangePreset);
+ // The Positions panel reads the window the table's columns were computed
+ // over. An empty custom range loads the table's 30-day default, so the
+ // panel follows it there too.
+ const positionsWindow = useMemo(() => range ?? resolvePromptRange('30d'), [range]);
// Keep the URL in sync with the active tab so deep links / refreshes land
// back on the same view. Shallow history update on purpose: the tab is pure
@@ -1620,6 +1628,9 @@ export default function PromptsPage() {
volumeByPromptId={volumeByPromptId}
visibility={visibility}
rangeLabel={rangeLabel}
+ positionsWindow={positionsWindow}
+ positionsPreset={range ? rangePreset : '30d'}
+ regionFilter={regionFilter}
onAddPrompt={canManage ? () => setAddPromptOpen(true) : undefined}
onEditPrompt={canManage ? setEditingPrompt : undefined}
/>
@@ -2023,6 +2034,9 @@ function AllPromptsTab({
volumeByPromptId,
visibility,
rangeLabel,
+ positionsWindow,
+ positionsPreset,
+ regionFilter,
onAddPrompt,
onEditPrompt,
}: {
@@ -2033,6 +2047,11 @@ function AllPromptsTab({
visibility: Record<string, PromptVisibilitySummary>;
/** Selected window, so the column tooltips describe the data on screen. */
rangeLabel: string;
+ /** Bounds the table's columns were computed over, for the Positions panel. */
+ positionsWindow: { from: string; to?: string };
+ positionsPreset: PromptRangePreset;
+ /** Selected location; empty means every location. */
+ regionFilter: string;
/** Opens the Add Prompt dialog; undefined when the user can't write (member role). */
onAddPrompt?: () => void;
/** Opens the Edit Prompt dialog for a row; undefined hides the pencil (member role). */
@@ -2048,6 +2067,12 @@ function AllPromptsTab({
new Map(),
);
const searchParams = useSearchParams();
+ // The row whose Positions panel is open. It lives here, beside the table,
+ // so closing the panel leaves search, sort, page and scroll as they were.
+ const [positionsFor, setPositionsFor] = useState<PositionsPrompt | null>(null);
+ // A brand switch or reload that drops the prompt must not leave its panel up.
+ const openPositions =
+ positionsFor && prompts.some((p) => p.id === positionsFor.id) ? positionsFor : null;
const statusOf = useCallback(
(p: Prompt) => (statusOverrides.has(p.id) ? statusOverrides.get(p.id)! : p.workStatus),
@@ -2255,6 +2280,12 @@ function AllPromptsTab({
>
Citations
</SortableHead>
+ <ColHead
+ className="text-center"
+ tooltip={`Where the brand was mentioned and cited, per AI platform, over the ${rangeLabel}. Available when the prompt has a mention or citation in that window.`}
+ >
+ Positions
+ </ColHead>
<SortableHead
className="text-right"
tooltip="Estimated monthly AI prompt volume, from keyword analysis. Empty until analysed."
@@ -2395,6 +2426,22 @@ function AllPromptsTab({
<span className="text-xs text-muted-foreground">—</span>
)}
</TableCell>
+ <TableCell className="text-center">
+ {vis && (vis.mentionAnswers > 0 || vis.citationAnswers > 0) ? (
+ <Button
+ type="button"
+ size="xs"
+ variant="outline"
+ aria-label={`View positions for ${p.text}`}
+ onClick={() => setPositionsFor({ id: p.id, text: p.text })}
+ >
+ <BarChart3 />
+ See
+ </Button>
+ ) : (
+ <span className="text-xs text-muted-foreground">—</span>
+ )}
+ </TableCell>
<TableCell className="text-right">
{vol ? (
<VolumePill value={vol.estAiVolume} />
@@ -2452,6 +2499,13 @@ function AllPromptsTab({
</div>
)}
</CardContent>
+ <PromptPositionsSheet
+ prompt={openPositions}
+ window={positionsWindow}
+ preset={positionsPreset}
+ region={regionFilter}
+ onClose={() => setPositionsFor(null)}
+ />
</Card>
);
}
diff --git a/web/src/components/ai-provider-avatar.tsx b/web/src/components/ai-provider-avatar.tsx
index 950b8e40f..f14382cad 100644
--- a/web/src/components/ai-provider-avatar.tsx
+++ b/web/src/components/ai-provider-avatar.tsx
@@ -133,12 +133,40 @@ export function getAIProviderDisplayName(provider: AIProviderKey): string {
export function AIProviderAvatar({
provider,
className,
+ plain = false,
}: {
provider: AIProviderKey;
className?: string;
+ /**
+ * Just the logo, without the round badge, for rows where it stands beside
+ * the platform's name. The ChatGPT mark is drawn white for the dark badge,
+ * so it is inverted to black on a light background.
+ */
+ plain?: boolean;
}) {
const meta = AI_PROVIDER_META[provider];
+ if (plain && meta.icon) {
+ return (
+ <span
+ title={meta.label}
+ aria-label={meta.label}
+ className={cn('flex h-5 w-5 shrink-0 items-center justify-center', className)}
+ >
+ {/* eslint-disable-next-line @next/next/no-img-element -- same static logo files as the badge below */}
+ <img
+ src={meta.icon}
+ alt=""
+ aria-hidden="true"
+ className={cn(
+ 'h-full w-full object-contain',
+ provider === 'openai' && 'invert dark:invert-0',
+ )}
+ />
+ </span>
+ );
+ }
+
if (!meta.icon) {
return (
<span
diff --git a/web/src/components/position-label.tsx b/web/src/components/position-label.tsx
new file mode 100644
index 000000000..c0303c05d
--- /dev/null
+++ b/web/src/components/position-label.tsx
@@ -0,0 +1,28 @@
+import { cn } from '@/lib/utils';
+import { positionTone } from '@/lib/position-tone';
+
+/**
+ * "Early · #2 of 7": where an entry sits in its list. Without a known total
+ * there is no third to place it in, so it reads just "#2".
+ */
+export function PositionLabel({ rank, total }: { rank: number; total: number | null }) {
+ if (!total) return <span className="text-xs tabular-nums whitespace-nowrap">#{rank}</span>;
+ const tone = positionTone(rank, total);
+ return (
+ <span className="text-xs tabular-nums whitespace-nowrap">
+ <span
+ className={cn(
+ 'font-medium',
+ tone === 'Early' && 'text-emerald-600 dark:text-emerald-400',
+ tone === 'Late' && 'text-amber-600 dark:text-amber-400',
+ )}
+ >
+ {tone}
+ </span>
+ <span className="text-muted-foreground">
+ {' '}
+ · #{rank} of {total}
+ </span>
+ </span>
+ );
+}
diff --git a/web/src/components/prompts/prompt-positions-sheet.tsx b/web/src/components/prompts/prompt-positions-sheet.tsx
new file mode 100644
index 000000000..13640125d
--- /dev/null
+++ b/web/src/components/prompts/prompt-positions-sheet.tsx
@@ -0,0 +1,814 @@
+'use client';
+
+/**
+ * Positions panel for one tracked prompt: per-platform mention and citation
+ * results over the Prompts table's window and location.
+ *
+ * The 24h window shows each platform's latest answer; longer windows show
+ * days — how many were tracked, mentioned and cited, with a block per day and
+ * every answer's positions behind it. A day with no answer is "not tracked",
+ * never "not mentioned".
+ */
+
+import { useEffect, useMemo, useState } from 'react';
+import {
+ AlertTriangle,
+ CalendarDays,
+ ChevronDown,
+ ExternalLink,
+ MessageSquareText,
+ RefreshCw,
+} from 'lucide-react';
+import { Link } from '@/i18n/navigation';
+import {
+ Sheet,
+ SheetClose,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from '@/components/ui/sheet';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { buttonVariants } from '@/components/ui/button-variants';
+import { Skeleton } from '@/components/ui/skeleton';
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
+import { AIProviderAvatar, resolveAIProvider } from '@/components/ai-provider-avatar';
+import { PositionLabel } from '@/components/position-label';
+import { cn } from '@/lib/utils';
+import { formatRegionDisplay } from '@/lib/region';
+import { positionTone } from '@/lib/position-tone';
+import { CONTACT_SALES_URL, type PlanId } from '@/config/plans';
+import type { PromptRangePreset } from '@/config/prompt-options';
+import { getPromptPositions, type PromptPositionsData } from '@/lib/actions/prompt-positions';
+import type {
+ AnswerView,
+ PlatformDay,
+ PlatformPositions,
+ PositionStats,
+} from '@/lib/prompt-positions';
+import type { Sentiment } from '@/types';
+
+export interface PositionsPrompt {
+ id: string;
+ text: string;
+}
+
+interface Props {
+ /** The prompt to show; null keeps the panel closed. */
+ prompt: PositionsPrompt | null;
+ /** The table's window: the same bounds its Mentions / Citations columns read. */
+ window: { from: string; to?: string };
+ preset: PromptRangePreset;
+ /** The table's location; empty means every location. */
+ region: string;
+ onClose: () => void;
+}
+
+const DAYS_PAGE = 10;
+const HISTORY_PAGE = 7;
+
+const DATE_FMT = new Intl.DateTimeFormat('en-US', {
+ timeZone: 'UTC',
+ month: 'short',
+ day: 'numeric',
+ year: 'numeric',
+});
+const SHORT_DATE_FMT = new Intl.DateTimeFormat('en-US', {
+ timeZone: 'UTC',
+ month: 'short',
+ day: 'numeric',
+});
+const TIME_FMT = new Intl.DateTimeFormat('en-US', {
+ timeZone: 'UTC',
+ hour: '2-digit',
+ minute: '2-digit',
+ hourCycle: 'h23',
+});
+
+const formatDay = (day: string) => DATE_FMT.format(new Date(`${day}T00:00:00Z`));
+const formatTime = (iso: string) => `${TIME_FMT.format(new Date(iso))} UTC`;
+const formatDateTime = (iso: string) =>
+ `${DATE_FMT.format(new Date(iso))}, ${TIME_FMT.format(new Date(iso))} UTC`;
+const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`;
+const pct = (n: number, of: number) => (of > 0 ? `${Math.round((n / of) * 100)}%` : '—');
+
+function windowTitle(preset: PromptRangePreset, window: { from: string; to?: string }): string {
+ if (preset !== 'custom') return `Last ${preset}`;
+ const to = window.to ?? new Date().toISOString();
+ return `Custom: ${SHORT_DATE_FMT.format(new Date(window.from))} – ${DATE_FMT.format(new Date(to))}`;
+}
+
+export function PromptPositionsSheet({ prompt, window, preset, region, onClose }: Props) {
+ // Everything the data depends on. A response is shown only while its key
+ // still matches, so another prompt's (or window's) numbers never linger.
+ const key = prompt ? `${prompt.id}|${window.from}|${window.to ?? ''}|${region}` : '';
+ const [loaded, setLoaded] = useState<{
+ key: string;
+ data: PromptPositionsData | null;
+ error: string | null;
+ } | null>(null);
+ const [attempt, setAttempt] = useState(0);
+
+ useEffect(() => {
+ if (!prompt) return;
+ let cancelled = false;
+ getPromptPositions(prompt.id, { from: window.from, to: window.to, region: region || undefined })
+ .then((data) => {
+ if (cancelled) return;
+ setLoaded({ key, data, error: data ? null : 'This prompt is no longer available.' });
+ })
+ .catch((err: unknown) => {
+ if (cancelled) return;
+ setLoaded({
+ key,
+ data: null,
+ error: err instanceof Error ? err.message : 'Failed to load positions.',
+ });
+ });
+ return () => {
+ cancelled = true;
+ };
+ // `key` covers prompt, window and region; `attempt` re-runs a failed load.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [key, attempt]);
+
+ const current = loaded?.key === key && key !== '' ? loaded : null;
+ const data = current?.data ?? null;
+ const latestMode = preset === '24h';
+
+ const retry = () => {
+ setLoaded(null);
+ setAttempt((n) => n + 1);
+ };
+
+ return (
+ <Sheet open={prompt !== null} onOpenChange={(open) => !open && onClose()}>
+ <SheetContent className="flex flex-col gap-0 p-0 data-[side=right]:w-full data-[side=right]:sm:max-w-2xl">
+ <SheetHeader className="gap-2 border-b px-5 py-4 pr-12">
+ <SheetTitle className="text-base leading-snug break-words">{prompt?.text}</SheetTitle>
+ {data && (
+ <div className="flex flex-wrap items-center gap-1.5">
+ <Badge variant="outline" className="text-[11px]">
+ {data.prompt.isActive ? 'Tracked prompt' : 'Paused'}
+ </Badge>
+ {data.prompt.topicName && (
+ <Badge variant="outline" className="text-[11px] text-muted-foreground">
+ {data.prompt.topicName}
+ </Badge>
+ )}
+ </div>
+ )}
+ <SheetDescription className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs">
+ <CalendarDays className="h-3.5 w-3.5" />
+ <span className="font-medium text-foreground">{windowTitle(preset, window)}</span>
+ {data && latestMode && (
+ <span>
+ Last run:{' '}
+ {data.summary.lastAnswerAt ? formatDateTime(data.summary.lastAnswerAt) : '—'}
+ </span>
+ )}
+ {data && !latestMode && data.summary.days.length > 0 && (
+ <span>
+ {SHORT_DATE_FMT.format(new Date(`${data.summary.days[0]}T00:00:00Z`))} –{' '}
+ {formatDay(data.summary.days[data.summary.days.length - 1])} (UTC)
+ </span>
+ )}
+ {region && <span>· {formatRegionDisplay(region)}</span>}
+ {data && !latestMode && (
+ <Badge variant="secondary" className="text-[11px]">
+ {plural(data.summary.runs, 'run')}
+ </Badge>
+ )}
+ </SheetDescription>
+ </SheetHeader>
+
+ <div className="flex-1 overflow-y-auto px-5 py-4">
+ {prompt && !current && <PositionsSkeleton />}
+ {current?.error && <LoadError message={current.error} onRetry={retry} />}
+ {data && (latestMode ? <LatestView data={data} /> : <PeriodView data={data} />)}
+ </div>
+
+ <div className="flex items-center justify-between gap-2 border-t px-5 py-3">
+ {prompt ? (
+ <Link
+ href={`/dashboard/prompts/${prompt.id}`}
+ className={buttonVariants({ variant: 'ghost', size: 'sm' })}
+ >
+ <MessageSquareText />
+ AI answers
+ </Link>
+ ) : (
+ <span />
+ )}
+ <SheetClose render={<Button variant="outline" size="sm" />}>Back to prompts</SheetClose>
+ </div>
+ </SheetContent>
+ </Sheet>
+ );
+}
+
+// ─── States ───────────────────────────────────────────────────────────────────
+
+function PositionsSkeleton() {
+ return (
+ <div className="space-y-3" aria-busy="true" aria-label="Loading positions">
+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <Skeleton key={i} className="h-[72px] w-full" />
+ ))}
+ </div>
+ <Skeleton className="h-8 w-60" />
+ {Array.from({ length: 6 }).map((_, i) => (
+ <Skeleton key={i} className="h-16 w-full" />
+ ))}
+ </div>
+ );
+}
+
+function LoadError({ message, onRetry }: { message: string; onRetry: () => void }) {
+ return (
+ <div
+ role="alert"
+ className="flex flex-col items-start gap-3 rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive"
+ >
+ <div className="flex items-start gap-2">
+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
+ <span>Couldn&apos;t load positions: {message}</span>
+ </div>
+ <Button type="button" variant="outline" size="sm" onClick={onRetry}>
+ <RefreshCw />
+ Retry
+ </Button>
+ </div>
+ );
+}
+
+// ─── Shared pieces ────────────────────────────────────────────────────────────
+
+function Stat({ label, value, sub }: { label: string; value: string; sub?: string }) {
+ return (
+ <div className="rounded-lg border p-3">
+ <p className="text-[11px] font-medium text-muted-foreground">{label}</p>
+ <p className="mt-1 text-lg font-semibold leading-tight tabular-nums">{value}</p>
+ {sub && <p className="mt-0.5 text-[11px] text-muted-foreground">{sub}</p>}
+ </div>
+ );
+}
+
+function PlatformName({ platform }: { platform: { id: string; label: string } }) {
+ return (
+ <span className="flex min-w-0 items-center gap-2 sm:w-44">
+ <AIProviderAvatar plain provider={resolveAIProvider('', platform.id)} className="h-6 w-6" />
+ <span className="truncate text-sm font-medium">{platform.label}</span>
+ </span>
+ );
+}
+
+const SENTIMENT_CLASS: Record<Sentiment, string> = {
+ positive: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300',
+ neutral: '',
+ negative: 'border-rose-500/30 bg-rose-500/10 text-rose-700 dark:text-rose-300',
+};
+
+function SentimentTag({ sentiment }: { sentiment: Sentiment | null }) {
+ if (!sentiment) return <span className="text-muted-foreground">Sentiment unavailable</span>;
+ return (
+ <Badge
+ variant="outline"
+ className={cn('h-4 px-1.5 text-[10px] font-medium capitalize', SENTIMENT_CLASS[sentiment])}
+ >
+ {sentiment}
+ </Badge>
+ );
+}
+
+function MentionStatus({ answer }: { answer: AnswerView }) {
+ if (!answer.mentioned) return <span className="text-muted-foreground">Not mentioned</span>;
+ return (
+ <span className="inline-flex flex-wrap items-center gap-x-1.5 gap-y-0.5">
+ <span className="font-medium">Mentioned</span>
+ {answer.mention ? (
+ <PositionLabel rank={answer.mention.position} total={answer.mention.total} />
+ ) : (
+ <span className="text-muted-foreground">Position unavailable</span>
+ )}
+ <SentimentTag sentiment={answer.sentiment} />
+ </span>
+ );
+}
+
+function CitationStatus({ answer }: { answer: AnswerView }) {
+ if (!answer.cited) return <span className="text-muted-foreground">Not cited</span>;
+ return (
+ <span className="inline-flex flex-wrap items-center gap-x-1.5 gap-y-0.5">
+ <span className="font-medium">Cited</span>
+ {answer.citation ? (
+ <PositionLabel rank={answer.citation.rank} total={answer.citation.total} />
+ ) : (
+ <span className="text-muted-foreground">Position unavailable</span>
+ )}
+ </span>
+ );
+}
+
+/** One answer: its mention and its citation side by side. */
+function AnswerLine({ answer, showTime }: { answer: AnswerView; showTime: boolean }) {
+ return (
+ <div className="grid grid-cols-1 gap-1 text-xs sm:grid-cols-[5.5rem_1fr_1fr] sm:gap-3">
+ {showTime ? (
+ <span className="tabular-nums text-muted-foreground">
+ {formatTime(answer.at)}
+ {answer.region ? ` · ${formatRegionDisplay(answer.region)}` : ''}
+ </span>
+ ) : (
+ <span className="hidden sm:block" />
+ )}
+ <MentionStatus answer={answer} />
+ <CitationStatus answer={answer} />
+ </div>
+ );
+}
+
+function LockedRow({ platform, planId }: { platform: PlatformPositions; planId: PlanId }) {
+ if (platform.access.state !== 'locked') return null;
+ const growth = platform.access.requiredPlan === 'growth';
+ const note = growth
+ ? 'Available on Growth'
+ : planId === 'enterprise'
+ ? 'Not enabled for this workspace'
+ : 'Available on Enterprise';
+ return (
+ <div className="flex flex-wrap items-center justify-between gap-3 px-3 py-3">
+ <div className="flex min-w-0 items-center gap-3">
+ <AIProviderAvatar plain provider={resolveAIProvider('', platform.id)} className="h-6 w-6" />
+ <div className="min-w-0">
+ <p className="text-sm font-medium">{platform.label}</p>
+ <p className="text-xs text-muted-foreground">
+ {note} · {growth ? 'Upgrade' : 'Contact us'} to track {platform.label} results and
+ positions.
+ </p>
+ </div>
+ </div>
+ {growth ? (
+ <Link
+ href="/dashboard/settings?tab=billing"
+ className={buttonVariants({ variant: 'outline', size: 'sm' })}
+ >
+ Upgrade
+ </Link>
+ ) : (
+ <a
+ href={CONTACT_SALES_URL}
+ target="_blank"
+ rel="noopener noreferrer"
+ className={buttonVariants({ variant: 'outline', size: 'sm' })}
+ >
+ Contact us
+ <ExternalLink />
+ </a>
+ )}
+ </div>
+ );
+}
+
+function avgLabel(stats: PositionStats | null): string {
+ return stats ? `#${stats.avg}` : '—';
+}
+
+// ─── 24h: each platform's latest answer ───────────────────────────────────────
+
+function LatestView({ data }: { data: PromptPositionsData }) {
+ const included = data.platforms.filter((p) => p.access.state === 'included');
+ const answered = included.filter((p) => p.latest);
+ const mentioned = answered.filter((p) => p.latest!.mentioned).length;
+ const cited = answered.filter((p) => p.latest!.cited).length;
+ const latestPositions = answered.flatMap((p) =>
+ p.latest!.mention ? [p.latest!.mention.position] : [],
+ );
+ const avg =
+ latestPositions.length > 0
+ ? `#${Math.round((latestPositions.reduce((a, b) => a + b, 0) / latestPositions.length) * 10) / 10}`
+ : '—';
+
+ return (
+ <div className="space-y-4">
+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
+ <Stat
+ label="Platforms answered"
+ value={`${answered.length} / ${included.length}`}
+ sub="in their latest run"
+ />
+ <Stat label="Mentioned on" value={`${mentioned} / ${answered.length}`} sub="platforms" />
+ <Stat label="Cited on" value={`${cited} / ${answered.length}`} sub="platforms" />
+ <Stat label="Avg. position" value={avg} sub="when mentioned" />
+ </div>
+
+ <div className="divide-y rounded-lg border">
+ {data.platforms.map((p) =>
+ p.access.state === 'locked' ? (
+ <LockedRow key={p.id} platform={p} planId={data.planId} />
+ ) : (
+ <LatestRow key={p.id} platform={p} />
+ ),
+ )}
+ </div>
+ </div>
+ );
+}
+
+function LatestRow({ platform: p }: { platform: PlatformPositions }) {
+ return (
+ <div className="px-3 py-3">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <PlatformName platform={p} />
+ {p.latest && (
+ <span className="text-xs text-muted-foreground">
+ Run at {formatDateTime(p.latest.at)}
+ </span>
+ )}
+ </div>
+ {!p.latest ? (
+ <p className="mt-2 text-xs text-muted-foreground">
+ No completed tracking runs in this period
+ </p>
+ ) : (
+ <dl className="mt-2 grid gap-3 text-xs sm:grid-cols-2">
+ <div>
+ <dt className="text-[11px] font-medium uppercase tracking-wide text-muted-foreground">
+ Mention
+ </dt>
+ <dd className="mt-1 space-y-1">
+ <MentionStatus answer={p.latest} />
+ {p.mentionedEarlier && (
+ <p className="text-muted-foreground">Detected earlier in this period</p>
+ )}
+ </dd>
+ </div>
+ <div>
+ <dt className="text-[11px] font-medium uppercase tracking-wide text-muted-foreground">
+ Citation
+ </dt>
+ <dd className="mt-1 space-y-1">
+ <CitationStatus answer={p.latest} />
+ {p.citedEarlier && (
+ <p className="text-muted-foreground">Detected earlier in this period</p>
+ )}
+ </dd>
+ </div>
+ </dl>
+ )}
+ </div>
+ );
+}
+
+// ─── 7d / 30d / 90d / custom: days ────────────────────────────────────────────
+
+function PeriodView({ data }: { data: PromptPositionsData }) {
+ const s = data.summary;
+ return (
+ <div className="space-y-4">
+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
+ <Stat
+ label="Runs"
+ value={String(s.runs)}
+ sub={`${s.trackedDays} of ${plural(s.days.length, 'day')} tracked`}
+ />
+ <Stat
+ label="Mentioned"
+ value={`${s.mentionedDays} / ${plural(s.trackedDays, 'day')}`}
+ sub={`${s.trackedDays - s.mentionedDays} not mentioned`}
+ />
+ <Stat
+ label="Cited"
+ value={`${s.citedDays} / ${plural(s.trackedDays, 'day')}`}
+ sub={`${s.trackedDays - s.citedDays} not cited`}
+ />
+ <Stat
+ label="Avg. position"
+ value={avgLabel(s.mentionPosition)}
+ sub={
+ s.citationPosition
+ ? `when mentioned · ${avgLabel(s.citationPosition)} in sources`
+ : 'when mentioned'
+ }
+ />
+ </div>
+ {s.untrackedDays > 0 && (
+ <p className="text-xs text-muted-foreground">
+ {plural(s.untrackedDays, 'day')} without a completed run. Untracked days don&apos;t count
+ as not mentioned or not cited.
+ </p>
+ )}
+
+ <Tabs defaultValue="platforms">
+ <TabsList>
+ <TabsTrigger value="platforms">Platform results</TabsTrigger>
+ <TabsTrigger value="history">Daily history ({s.trackedDays})</TabsTrigger>
+ </TabsList>
+ <TabsContent value="platforms" className="mt-3 space-y-3">
+ <HeatmapLegend />
+ <div className="divide-y rounded-lg border">
+ {data.platforms.map((p) =>
+ p.access.state === 'locked' ? (
+ <LockedRow key={p.id} platform={p} planId={data.planId} />
+ ) : (
+ <PlatformPeriodRow key={p.id} platform={p} days={s.days} />
+ ),
+ )}
+ </div>
+ <p className="text-xs text-muted-foreground">
+ Each block is one UTC day in the selected range. Hover a block for that day&apos;s
+ positions; open a platform for every run.
+ </p>
+ </TabsContent>
+ <TabsContent value="history" className="mt-3">
+ <DailyHistory platforms={data.platforms} />
+ </TabsContent>
+ </Tabs>
+ </div>
+ );
+}
+
+type CellTone = 'untracked' | 'none' | 'Early' | 'Mid' | 'Late' | 'mentioned' | 'cited';
+
+const CELL_CLASS: Record<CellTone, string> = {
+ untracked: 'border border-dashed border-muted-foreground/40',
+ none: 'bg-muted-foreground/15',
+ Early: 'bg-emerald-500',
+ Mid: 'bg-emerald-300 dark:bg-emerald-700',
+ Late: 'bg-amber-400',
+ mentioned: 'bg-emerald-400',
+ cited: 'bg-sky-400',
+};
+
+const LEGEND: { tone: CellTone; label: string }[] = [
+ { tone: 'Early', label: 'Mentioned early' },
+ { tone: 'Mid', label: 'Mid' },
+ { tone: 'Late', label: 'Late' },
+ { tone: 'cited', label: 'Cited only' },
+ { tone: 'none', label: 'No result' },
+ { tone: 'untracked', label: 'Not tracked' },
+];
+
+function HeatmapLegend() {
+ return (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-muted-foreground">
+ {LEGEND.map(({ tone, label }) => (
+ <span key={tone} className="inline-flex items-center gap-1.5">
+ <span className={cn('h-2.5 w-2.5 rounded-[3px]', CELL_CLASS[tone])} />
+ {label}
+ </span>
+ ))}
+ </div>
+ );
+}
+
+/** The day's best mention and best citation, by rank. */
+function bestOf(answers: AnswerView[]) {
+ const mention = answers
+ .filter((a) => a.mention)
+ .sort((a, b) => a.mention!.position - b.mention!.position)[0]?.mention;
+ const citation = answers
+ .filter((a) => a.citation)
+ .sort((a, b) => a.citation!.rank - b.citation!.rank)[0]?.citation;
+ return { mention, citation };
+}
+
+function cellTone(entry: PlatformDay | undefined): CellTone {
+ if (!entry) return 'untracked';
+ const { mention } = bestOf(entry.answers);
+ if (mention) return mention.total ? positionTone(mention.position, mention.total) : 'mentioned';
+ if (entry.answers.some((a) => a.mentioned)) return 'mentioned';
+ if (entry.answers.some((a) => a.cited)) return 'cited';
+ return 'none';
+}
+
+function dayTooltip(day: string, entry: PlatformDay | undefined): string {
+ if (!entry) return `${formatDay(day)}\nNot tracked`;
+ const runs = entry.answers.length;
+ const mentioned = entry.answers.filter((a) => a.mentioned).length;
+ const cited = entry.answers.filter((a) => a.cited).length;
+ const { mention, citation } = bestOf(entry.answers);
+ const share = (n: number) => (runs > 1 ? ` in ${n} of ${runs} runs` : '');
+ const mentionLine = mentioned
+ ? `Mentioned${share(mentioned)}${
+ mention
+ ? ` · ${mention.total ? `${positionTone(mention.position, mention.total)} · ` : ''}#${mention.position}${mention.total ? ` of ${mention.total}` : ''}`
+ : ''
+ }`
+ : 'Not mentioned';
+ const citationLine = cited
+ ? `Cited${share(cited)}${
+ citation
+ ? ` · ${positionTone(citation.rank, citation.total)} · #${citation.rank} of ${citation.total}`
+ : ''
+ }`
+ : 'Not cited';
+ return `${formatDay(day)} · ${plural(runs, 'run')}\n${mentionLine}\n${citationLine}`;
+}
+
+function Heatmap({ platform, days }: { platform: PlatformPositions; days: string[] }) {
+ const byDay = useMemo(() => new Map(platform.days.map((d) => [d.day, d])), [platform.days]);
+ return (
+ <div
+ role="img"
+ aria-label={`${platform.label}: mentioned on ${platform.mentionedDays} and cited on ${platform.citedDays} of ${plural(platform.trackedDays, 'tracked day')}`}
+ className="mt-2 flex flex-wrap gap-[3px]"
+ >
+ {days.map((day) => {
+ const entry = byDay.get(day);
+ return (
+ <span
+ key={day}
+ title={dayTooltip(day, entry)}
+ className={cn('h-3 w-3 rounded-[3px]', CELL_CLASS[cellTone(entry)])}
+ />
+ );
+ })}
+ </div>
+ );
+}
+
+function Metric({ label, value, sub }: { label: string; value: string; sub: string }) {
+ return (
+ <span className="flex flex-col">
+ <span className="text-[11px] text-muted-foreground">{label}</span>
+ <span className="text-sm font-semibold tabular-nums">{value}</span>
+ <span className="text-[11px] text-muted-foreground">{sub}</span>
+ </span>
+ );
+}
+
+function PositionTrio({ stats }: { stats: PositionStats | null }) {
+ const cells: [string, string, string][] = stats
+ ? [
+ ['Best', `#${stats.best}`, 'text-emerald-600 dark:text-emerald-400'],
+ ['Worst', `#${stats.worst}`, 'text-amber-600 dark:text-amber-400'],
+ ['Avg.', `#${stats.avg}`, ''],
+ ]
+ : [];
+ if (cells.length === 0) {
+ return <span className="text-[11px] text-muted-foreground">No mention position</span>;
+ }
+ return (
+ <span className="flex gap-3" title="Position when mentioned">
+ {cells.map(([label, value, cls]) => (
+ <span key={label} className="flex flex-col items-center">
+ <span className={cn('text-sm font-semibold tabular-nums', cls)}>{value}</span>
+ <span className="text-[10px] text-muted-foreground">{label}</span>
+ </span>
+ ))}
+ </span>
+ );
+}
+
+function runsNote(d: PlatformDay): string {
+ const runs = d.answers.length;
+ if (runs === 1) return '1 run';
+ const mentioned = d.answers.filter((a) => a.mentioned).length;
+ const cited = d.answers.filter((a) => a.cited).length;
+ return `${runs} runs · mentioned in ${mentioned} · cited in ${cited}`;
+}
+
+function PlatformPeriodRow({ platform: p, days }: { platform: PlatformPositions; days: string[] }) {
+ const [open, setOpen] = useState(false);
+ const [shown, setShown] = useState(DAYS_PAGE);
+
+ if (p.runs === 0) {
+ return (
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 px-3 py-3">
+ <PlatformName platform={p} />
+ <span className="text-xs text-muted-foreground">No tracking data for this period</span>
+ </div>
+ );
+ }
+
+ const s = p.sentiment;
+ return (
+ <div className="px-3 py-3">
+ <button
+ type="button"
+ onClick={() => setOpen((o) => !o)}
+ aria-expanded={open}
+ aria-label={`${open ? 'Hide' : 'Show'} daily ${p.label} results`}
+ className="flex w-full flex-wrap items-center gap-x-5 gap-y-2 rounded-md text-left outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ >
+ <PlatformName platform={p} />
+ <Metric
+ label="Mentioned"
+ value={`${p.mentionedDays} / ${p.trackedDays}`}
+ sub={pct(p.mentionedDays, p.trackedDays)}
+ />
+ <Metric
+ label="Cited"
+ value={`${p.citedDays} / ${p.trackedDays}`}
+ sub={pct(p.citedDays, p.trackedDays)}
+ />
+ <PositionTrio stats={p.mentionPosition} />
+ <ChevronDown
+ className={cn(
+ 'ml-auto h-4 w-4 text-muted-foreground transition-transform',
+ open && 'rotate-180',
+ )}
+ />
+ </button>
+ <Heatmap platform={p} days={days} />
+
+ {open && (
+ <div className="mt-3 space-y-2">
+ <p className="text-xs text-muted-foreground">
+ {plural(p.runs, 'run')} on {plural(p.trackedDays, 'day')}
+ {s.positive + s.neutral + s.negative + s.unavailable > 0 &&
+ ` · sentiment in mentioning answers: ${s.positive} positive, ${s.neutral} neutral, ${s.negative} negative${
+ s.unavailable ? `, ${s.unavailable} unavailable` : ''
+ }`}
+ </p>
+ <ul className="space-y-2">
+ {p.days.slice(0, shown).map((d) => (
+ <li key={d.day} className="rounded-md bg-muted/40 px-3 py-2">
+ <div className="flex flex-wrap items-center justify-between gap-2 text-xs">
+ <span className="font-medium">{formatDay(d.day)}</span>
+ <span className="text-muted-foreground">{runsNote(d)}</span>
+ </div>
+ <div className="mt-1.5 space-y-1.5">
+ {d.answers.map((a, i) => (
+ <AnswerLine key={`${a.at}-${i}`} answer={a} showTime={d.answers.length > 1} />
+ ))}
+ </div>
+ </li>
+ ))}
+ </ul>
+ {p.days.length > shown && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => setShown((n) => n + DAYS_PAGE)}
+ >
+ Show {Math.min(DAYS_PAGE, p.days.length - shown)} more days
+ </Button>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function DailyHistory({ platforms }: { platforms: PlatformPositions[] }) {
+ const [shown, setShown] = useState(HISTORY_PAGE);
+ const days = useMemo(() => {
+ const byDay = new Map<string, { platform: PlatformPositions; answers: AnswerView[] }[]>();
+ for (const p of platforms) {
+ for (const d of p.days) {
+ byDay.set(d.day, [...(byDay.get(d.day) ?? []), { platform: p, answers: d.answers }]);
+ }
+ }
+ return [...byDay.entries()].sort(([a], [b]) => b.localeCompare(a));
+ }, [platforms]);
+
+ if (days.length === 0) {
+ return (
+ <p className="py-6 text-center text-sm text-muted-foreground">
+ No completed tracking runs in this period.
+ </p>
+ );
+ }
+
+ return (
+ <div className="space-y-3">
+ {days.slice(0, shown).map(([day, entries]) => (
+ <div key={day} className="rounded-lg border">
+ <div className="flex items-center justify-between border-b px-3 py-2 text-xs">
+ <span className="font-medium">{formatDay(day)}</span>
+ <span className="text-muted-foreground">
+ {plural(entries.length, 'platform')} answered
+ </span>
+ </div>
+ <div className="divide-y">
+ {entries.map(({ platform, answers }) => (
+ <div key={platform.id} className="flex flex-col gap-1.5 px-3 py-2 sm:flex-row">
+ <PlatformName platform={platform} />
+ <div className="flex-1 space-y-1.5">
+ {answers.map((a, i) => (
+ <AnswerLine key={`${a.at}-${i}`} answer={a} showTime={answers.length > 1} />
+ ))}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ ))}
+ {days.length > shown && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => setShown((n) => n + HISTORY_PAGE)}
+ >
+ Show {Math.min(HISTORY_PAGE, days.length - shown)} more days
+ </Button>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/components/settings/plan-switcher.tsx b/web/src/components/settings/plan-switcher.tsx
index 79613e0f8..25b015c2a 100644
--- a/web/src/components/settings/plan-switcher.tsx
+++ b/web/src/components/settings/plan-switcher.tsx
@@ -16,7 +16,7 @@ import {
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
-import { PLANS, SUBSCRIBABLE_PLANS, type PlanId } from '@/config/plans';
+import { CONTACT_SALES_URL, PLANS, SUBSCRIBABLE_PLANS, type PlanId } from '@/config/plans';
import { ALL_SCRAPERS } from '@/config/prompt-options';
interface SubscriptionData {
@@ -260,7 +260,7 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
<p className="text-xs text-muted-foreground">{t('customPlanDescription')}</p>
</div>
<a
- href="https://www.ansvisor.com/contact-us"
+ href={CONTACT_SALES_URL}
target="_blank"
rel="noopener noreferrer"
className="inline-flex shrink-0 items-center justify-center rounded-md border bg-background px-5 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground"
diff --git a/web/src/config/plans.ts b/web/src/config/plans.ts
index 436e6164b..d68ab9869 100644
--- a/web/src/config/plans.ts
+++ b/web/src/config/plans.ts
@@ -223,6 +223,9 @@ export const PLAN_ORDER: PlanId[] = ['starter', 'growth', 'enterprise'];
export const SUBSCRIBABLE_PLANS: PlanId[] = ['starter', 'growth'];
+/** Where a plan the app can't sell by itself (Enterprise, add-ons) is asked for. */
+export const CONTACT_SALES_URL = 'https://www.ansvisor.com/contact-us';
+
/**
* Self-hosted instances bypass all limits.
* Cloud is determined by NEXT_PUBLIC_IS_CLOUD env var.
diff --git a/web/src/lib/actions/prompt-positions.ts b/web/src/lib/actions/prompt-positions.ts
new file mode 100644
index 000000000..cd299fb64
--- /dev/null
+++ b/web/src/lib/actions/prompt-positions.ts
@@ -0,0 +1,155 @@
+'use server';
+
+import { dbClient } from '@/lib/supabase/scoped';
+import { getOrgPlan } from '@/lib/guards/plan-guard';
+import type { PlanId } from '@/config/plans';
+import {
+ POSITION_PLATFORMS,
+ brandCitationPosition,
+ platformAccess,
+ summarizePositions,
+ type PlatformPositions,
+ type PositionAnswer,
+ type PositionsSummary,
+} from '@/lib/prompt-positions';
+import type { Sentiment } from '@/types';
+
+export interface PromptPositionsData {
+ prompt: { id: string; text: string; topicName: string | null; isActive: boolean };
+ planId: PlanId;
+ window: { from: string; to: string };
+ summary: PositionsSummary;
+ platforms: PlatformPositions[];
+}
+
+/** 90 days × 8 engines × a few locations, with room to spare. */
+const MAX_ANSWERS = 5000;
+const PAGE_SIZE = 1000;
+/** Ids per `in` filter: keeps the request URL well under PostgREST's limit. */
+const ID_CHUNK = 100;
+
+const SENTIMENTS: readonly string[] = ['positive', 'neutral', 'negative'];
+
+/**
+ * One prompt's per-engine positions over the Prompts table's window and
+ * location, for the Positions panel.
+ *
+ * Reads through the caller's RLS-scoped client, so a prompt outside the
+ * caller's organisations comes back as null. Engines the org's plan doesn't
+ * include are never queried: their rows carry only the upgrade state.
+ * Answer text and source lists stay on the server; the panel gets the
+ * folded numbers.
+ */
+export async function getPromptPositions(
+ promptId: string,
+ opts: { from: string; to?: string; region?: string },
+): Promise<PromptPositionsData | null> {
+ if (!Number.isFinite(Date.parse(opts.from))) throw new Error('Invalid date range');
+ if (opts.to && !Number.isFinite(Date.parse(opts.to))) throw new Error('Invalid date range');
+ const to = opts.to ?? new Date().toISOString();
+
+ const supabase = await dbClient();
+
+ const { data: prompt } = await supabase
+ .from('prompts')
+ .select('id, text, topic_id, category, is_active, prompt_set_id')
+ .eq('id', promptId)
+ .maybeSingle();
+ if (!prompt) return null;
+
+ const { data: promptSet } = await supabase
+ .from('prompt_sets')
+ .select('brand_id')
+ .eq('id', prompt.prompt_set_id)
+ .maybeSingle();
+ const brandId = promptSet?.brand_id as string | undefined;
+ if (!brandId) return null;
+
+ const [{ data: brand }, { data: domainRows }, { data: topic }] = await Promise.all([
+ supabase.from('brands').select('organization_id').eq('id', brandId).maybeSingle(),
+ supabase.from('brand_domains').select('domain').eq('brand_id', brandId),
+ prompt.topic_id
+ ? supabase.from('topics').select('name').eq('id', prompt.topic_id).maybeSingle()
+ : Promise.resolve({ data: null }),
+ ]);
+ if (!brand?.organization_id) return null;
+
+ const plan = await getOrgPlan(brand.organization_id as string);
+ const platforms = POSITION_PLATFORMS.map((p) => ({ ...p, access: platformAccess(plan, p.id) }));
+ const includedIds = platforms.filter((p) => p.access.state === 'included').map((p) => p.id);
+ const brandDomains = (domainRows ?? []).map((r) => r.domain as string);
+
+ const rows: Record<string, unknown>[] = [];
+ for (let offset = 0; offset < MAX_ANSWERS; offset += PAGE_SIZE) {
+ let query = supabase
+ .from('prompt_results')
+ .select(
+ 'id, platform, created_at, region, mention_count, mention_position, mentioned_entity_count, sentiment, citation_count',
+ )
+ .eq('prompt_id', promptId)
+ .eq('brand_id', brandId)
+ .in('platform', includedIds)
+ .gte('created_at', opts.from)
+ .lte('created_at', to);
+ if (opts.region) query = query.eq('region', opts.region);
+ const { data, error } = await query
+ .order('created_at', { ascending: false })
+ .range(offset, offset + PAGE_SIZE - 1);
+ if (error) throw new Error(error.message);
+ rows.push(...((data ?? []) as Record<string, unknown>[]));
+ if ((data ?? []).length < PAGE_SIZE) break;
+ }
+
+ // Source lists are the heavy column and only cited answers need theirs, so
+ // they are fetched for those answers alone.
+ const citedIds = rows.filter((r) => Number(r.citation_count ?? 0) > 0).map((r) => r.id as string);
+ const sourcesById = new Map<string, unknown>();
+ const chunks = Array.from({ length: Math.ceil(citedIds.length / ID_CHUNK) }, (_, i) =>
+ citedIds.slice(i * ID_CHUNK, (i + 1) * ID_CHUNK),
+ );
+ await Promise.all(
+ chunks.map(async (ids) => {
+ const { data, error } = await supabase
+ .from('prompt_results')
+ .select('id, citations')
+ .in('id', ids);
+ if (error) throw new Error(error.message);
+ for (const r of data ?? []) sourcesById.set(r.id as string, r.citations);
+ }),
+ );
+
+ const answers: PositionAnswer[] = rows.map((row) => {
+ const mentioned = Number(row.mention_count ?? 0) > 0;
+ const cited = Number(row.citation_count ?? 0) > 0;
+ const sentiment = row.sentiment as string | null;
+ return {
+ platform: row.platform as string,
+ createdAt: row.created_at as string,
+ region: (row.region as string | null) ?? null,
+ mentioned,
+ mentionPosition: (row.mention_position as number | null) ?? null,
+ mentionTotal: (row.mentioned_entity_count as number | null) ?? null,
+ sentiment: sentiment && SENTIMENTS.includes(sentiment) ? (sentiment as Sentiment) : null,
+ cited,
+ citation: cited
+ ? brandCitationPosition(sourcesById.get(row.id as string), brandDomains)
+ : null,
+ };
+ });
+
+ const window = { from: opts.from, to };
+ const { summary, platforms: rowsByPlatform } = summarizePositions(answers, platforms, window);
+
+ return {
+ prompt: {
+ id: prompt.id as string,
+ text: prompt.text as string,
+ topicName: (topic?.name as string | undefined) ?? (prompt.category as string | null) ?? null,
+ isActive: Boolean(prompt.is_active),
+ },
+ planId: plan.id,
+ window,
+ summary,
+ platforms: rowsByPlatform,
+ };
+}
diff --git a/web/src/lib/position-tone.ts b/web/src/lib/position-tone.ts
new file mode 100644
index 000000000..28079cd9b
--- /dev/null
+++ b/web/src/lib/position-tone.ts
@@ -0,0 +1,11 @@
+export type PositionTone = 'Early' | 'Mid' | 'Late';
+
+/**
+ * Where a rank sits in its list: the first third is Early, the last third
+ * Late. The Citation URL page and the Prompts Positions panel share it, so
+ * the same rank never reads differently on the two.
+ */
+export function positionTone(rank: number, total: number): PositionTone {
+ const ratio = total > 1 ? (rank - 1) / (total - 1) : 0;
+ return ratio <= 1 / 3 ? 'Early' : ratio >= 2 / 3 ? 'Late' : 'Mid';
+}
diff --git a/web/src/lib/prompt-positions.test.ts b/web/src/lib/prompt-positions.test.ts
new file mode 100644
index 000000000..0630af303
--- /dev/null
+++ b/web/src/lib/prompt-positions.test.ts
@@ -0,0 +1,277 @@
+import { describe, expect, it } from 'vitest';
+
+import { PLANS, type Plan } from '@/config/plans';
+import {
+ POSITION_PLATFORMS,
+ brandCitationPosition,
+ countRuns,
+ platformAccess,
+ summarizePositions,
+ windowDays,
+ type PositionAnswer,
+} from './prompt-positions';
+import { positionTone } from './position-tone';
+
+const accessFor = (plan: Plan) =>
+ Object.fromEntries(POSITION_PLATFORMS.map((p) => [p.id, platformAccess(plan, p.id)]));
+
+describe('platformAccess', () => {
+ it('locks Starter to ChatGPT and Perplexity, with Grok and Claude behind sales', () => {
+ const access = accessFor(PLANS.starter);
+ expect(access['chatgpt-web']).toEqual({ state: 'included' });
+ expect(access['perplexity-web']).toEqual({ state: 'included' });
+ for (const id of ['google-aio', 'google-aimode', 'gemini-web', 'copilot-web']) {
+ expect(access[id]).toEqual({ state: 'locked', requiredPlan: 'growth' });
+ }
+ expect(access['grok-web']).toEqual({ state: 'locked', requiredPlan: 'enterprise' });
+ expect(access.claude).toEqual({ state: 'locked', requiredPlan: 'enterprise' });
+ });
+
+ it('includes the other scrapers on Growth and leaves Grok and Claude to sales', () => {
+ const access = accessFor(PLANS.growth);
+ for (const p of POSITION_PLATFORMS.filter((p) => p.id !== 'claude' && p.id !== 'grok-web')) {
+ expect(access[p.id]).toEqual({ state: 'included' });
+ }
+ expect(access['grok-web']).toEqual({ state: 'locked', requiredPlan: 'enterprise' });
+ expect(access.claude).toEqual({ state: 'locked', requiredPlan: 'enterprise' });
+ });
+
+ it('leaves Grok to sales on Enterprise too', () => {
+ expect(platformAccess(PLANS.enterprise, 'grok-web')).toEqual({
+ state: 'locked',
+ requiredPlan: 'enterprise',
+ });
+ });
+
+ it('includes Claude on Enterprise only when the customer override enables it', () => {
+ expect(platformAccess(PLANS.enterprise, 'claude')).toEqual({
+ state: 'locked',
+ requiredPlan: 'enterprise',
+ });
+ const overridden: Plan = {
+ ...PLANS.enterprise,
+ limits: { ...PLANS.enterprise.limits, allowedModels: ['claude-sonnet-5'] },
+ };
+ expect(platformAccess(overridden, 'claude')).toEqual({ state: 'included' });
+ });
+
+ it('includes everything when self-hosted', () => {
+ const access = accessFor(PLANS.self_hosted);
+ expect(Object.values(access).every((a) => a.state === 'included')).toBe(true);
+ });
+});
+
+describe('positionTone', () => {
+ it('splits a list into thirds', () => {
+ expect(positionTone(1, 9)).toBe('Early');
+ expect(positionTone(3, 9)).toBe('Early');
+ expect(positionTone(5, 9)).toBe('Mid');
+ expect(positionTone(7, 9)).toBe('Late');
+ expect(positionTone(5, 5)).toBe('Late');
+ });
+
+ it('calls the only entry Early', () => {
+ expect(positionTone(1, 1)).toBe('Early');
+ });
+});
+
+describe('brandCitationPosition', () => {
+ const cites = (...urls: (string | null)[]) => urls.map((url) => ({ url, title: '' }));
+
+ it('ranks the first own-domain source among the sources with a URL', () => {
+ const result = brandCitationPosition(
+ cites('https://a.com', null, 'https://blog.acme.com/x', 'https://www.acme.com/y'),
+ ['acme.com'],
+ );
+ expect(result).toEqual({ rank: 2, total: 3 });
+ });
+
+ it('does not match the domain inside another site', () => {
+ expect(
+ brandCitationPosition(cites('https://notacme.com', 'https://x.com/?u=acme.com'), [
+ 'https://www.acme.com/',
+ ]),
+ ).toBeNull();
+ });
+
+ it('returns null without domains or citations', () => {
+ expect(brandCitationPosition(cites('https://acme.com'), [])).toBeNull();
+ expect(brandCitationPosition(null, ['acme.com'])).toBeNull();
+ });
+});
+
+describe('windowDays', () => {
+ it('drops the partial first date of a rolling window when nothing landed in it', () => {
+ const days = windowDays('2026-10-03T14:00:00.000Z', '2026-10-10T14:00:00.000Z', new Set());
+ expect(days).toEqual([
+ '2026-10-04',
+ '2026-10-05',
+ '2026-10-06',
+ '2026-10-07',
+ '2026-10-08',
+ '2026-10-09',
+ '2026-10-10',
+ ]);
+ });
+
+ it('keeps the partial first date when an answer landed in it', () => {
+ const days = windowDays(
+ '2026-10-03T14:00:00.000Z',
+ '2026-10-10T14:00:00.000Z',
+ new Set(['2026-10-03']),
+ );
+ expect(days[0]).toBe('2026-10-03');
+ expect(days).toHaveLength(8);
+ });
+
+ it('keeps every date of a whole-day custom range', () => {
+ expect(windowDays('2026-10-01T00:00:00.000Z', '2026-10-03T23:59:59.999Z', new Set())).toEqual([
+ '2026-10-01',
+ '2026-10-02',
+ '2026-10-03',
+ ]);
+ });
+});
+
+describe('countRuns', () => {
+ it('counts answers a few hours apart as one run and a day apart as two', () => {
+ expect(
+ countRuns([
+ '2026-10-08T02:01:00Z',
+ '2026-10-08T02:40:00Z',
+ '2026-10-08T04:10:00Z',
+ '2026-10-09T02:05:00Z',
+ ]),
+ ).toBe(2);
+ });
+
+ it('counts nothing for no answers', () => {
+ expect(countRuns([])).toBe(0);
+ });
+});
+
+function answer(over: Partial<PositionAnswer> & { createdAt: string }): PositionAnswer {
+ return {
+ platform: 'chatgpt-web',
+ region: 'us',
+ mentioned: false,
+ mentionPosition: null,
+ mentionTotal: null,
+ sentiment: null,
+ cited: false,
+ citation: null,
+ ...over,
+ };
+}
+
+const included = { state: 'included' } as const;
+const growthOnly = { state: 'locked', requiredPlan: 'growth' } as const;
+const PLATFORMS = [
+ { id: 'chatgpt-web' as const, label: 'ChatGPT', access: included },
+ { id: 'perplexity-web' as const, label: 'Perplexity', access: included },
+ { id: 'google-aio' as const, label: 'Google AI Overviews', access: growthOnly },
+];
+const WEEK = { from: '2026-10-04T00:00:00.000Z', to: '2026-10-10T23:59:59.999Z' };
+
+describe('summarizePositions', () => {
+ it('counts a day once however many answers it has, and keeps every answer', () => {
+ const { platforms } = summarizePositions(
+ [
+ answer({ createdAt: '2026-10-08T02:00:00Z' }),
+ answer({
+ createdAt: '2026-10-08T09:00:00Z',
+ cited: true,
+ citation: { rank: 2, total: 8 },
+ }),
+ answer({ createdAt: '2026-10-08T15:00:00Z' }),
+ ],
+ PLATFORMS,
+ WEEK,
+ );
+ const chatgpt = platforms[0];
+ expect(chatgpt.runs).toBe(3);
+ expect(chatgpt.trackedDays).toBe(1);
+ expect(chatgpt.citedDays).toBe(1);
+ expect(chatgpt.days[0].answers).toHaveLength(3);
+ expect(chatgpt.days[0].answers.filter((a) => a.cited)).toHaveLength(1);
+ });
+
+ it('never counts a day without an answer as not mentioned', () => {
+ const { summary } = summarizePositions(
+ [
+ answer({ createdAt: '2026-10-05T02:00:00Z', mentioned: true, mentionPosition: 1 }),
+ answer({ createdAt: '2026-10-06T02:00:00Z' }),
+ answer({ createdAt: '2026-10-07T02:00:00Z', mentioned: true, mentionPosition: 3 }),
+ answer({ createdAt: '2026-10-08T02:00:00Z' }),
+ answer({ createdAt: '2026-10-09T02:00:00Z', cited: true }),
+ ],
+ PLATFORMS,
+ WEEK,
+ );
+ expect(summary.days).toHaveLength(7);
+ expect(summary.trackedDays).toBe(5);
+ expect(summary.mentionedDays).toBe(2);
+ expect(summary.citedDays).toBe(1);
+ expect(summary.untrackedDays).toBe(2);
+ });
+
+ it('merges engines into one run and one day for the summary, but not per engine', () => {
+ const { summary, platforms } = summarizePositions(
+ [
+ answer({ createdAt: '2026-10-08T02:00:00Z', mentioned: true, mentionPosition: 2 }),
+ answer({
+ createdAt: '2026-10-08T02:30:00Z',
+ platform: 'perplexity-web',
+ mentioned: true,
+ mentionPosition: 4,
+ }),
+ ],
+ PLATFORMS,
+ WEEK,
+ );
+ expect(summary.runs).toBe(1);
+ expect(summary.mentionedDays).toBe(1);
+ expect(summary.mentionPosition).toEqual({ best: 2, worst: 4, avg: 3, count: 2 });
+ expect(platforms[0].runs).toBe(1);
+ expect(platforms[1].runs).toBe(1);
+ });
+
+ it('gives a locked engine no data even when answers exist for it', () => {
+ const { platforms, summary } = summarizePositions(
+ [answer({ createdAt: '2026-10-08T02:00:00Z', platform: 'google-aio', mentioned: true })],
+ PLATFORMS,
+ WEEK,
+ );
+ expect(platforms[2].runs).toBe(0);
+ expect(platforms[2].latest).toBeNull();
+ expect(summary.trackedDays).toBe(0);
+ });
+
+ it('flags a mention seen earlier in the window when the latest answer has none', () => {
+ const { platforms } = summarizePositions(
+ [
+ answer({ createdAt: '2026-10-09T20:00:00Z', mentioned: true, mentionPosition: 1 }),
+ answer({ createdAt: '2026-10-10T02:00:00Z' }),
+ ],
+ PLATFORMS,
+ WEEK,
+ );
+ expect(platforms[0].latest?.mentioned).toBe(false);
+ expect(platforms[0].mentionedEarlier).toBe(true);
+ expect(platforms[0].citedEarlier).toBe(false);
+ });
+
+ it('leaves position and sentiment empty rather than inventing them', () => {
+ const { platforms } = summarizePositions(
+ [answer({ createdAt: '2026-10-08T02:00:00Z', mentioned: true, cited: true })],
+ PLATFORMS,
+ WEEK,
+ );
+ const latest = platforms[0].latest!;
+ expect(latest.mention).toBeNull();
+ expect(latest.citation).toBeNull();
+ expect(latest.sentiment).toBeNull();
+ expect(platforms[0].sentiment.unavailable).toBe(1);
+ expect(platforms[0].mentionPosition).toBeNull();
+ });
+});
diff --git a/web/src/lib/prompt-positions.ts b/web/src/lib/prompt-positions.ts
new file mode 100644
index 000000000..7a98502c7
--- /dev/null
+++ b/web/src/lib/prompt-positions.ts
@@ -0,0 +1,335 @@
+/**
+ * Per-platform positions for one prompt over a date window: what the
+ * Positions panel on the Prompts page shows.
+ *
+ * Pure on purpose: the server action loads the answers and the plan, this
+ * turns them into the panel's numbers, and the tests pin the counting rules
+ * that are easy to get subtly wrong (a day without an answer is untracked,
+ * not "not mentioned"; several answers on one day count that day once).
+ */
+import { PLANS, PLAN_ORDER, type Plan } from '@/config/plans';
+import { extractHostname, normalizeDomain } from '@/lib/citations/classify';
+import type { Sentiment } from '@/types';
+
+/** The engines the panel lists, in the order it lists them. */
+export const POSITION_PLATFORMS = [
+ { id: 'chatgpt-web', label: 'ChatGPT' },
+ { id: 'perplexity-web', label: 'Perplexity' },
+ { id: 'google-aio', label: 'Google AI Overviews' },
+ { id: 'google-aimode', label: 'Google AI Mode' },
+ { id: 'gemini-web', label: 'Gemini' },
+ { id: 'copilot-web', label: 'Microsoft Copilot' },
+ { id: 'grok-web', label: 'Grok' },
+ // API-model tracking stores its answers under this platform.
+ { id: 'claude', label: 'Claude' },
+] as const;
+
+export type PositionPlatformId = (typeof POSITION_PLATFORMS)[number]['id'];
+
+export type PlatformAccess =
+ | { state: 'included' }
+ | { state: 'locked'; requiredPlan: 'growth' | 'enterprise' };
+
+/**
+ * Whether a plan's limits cover an engine. Claude is an API model, gated by
+ * `allowedModels`; every other engine is a scraper, gated by
+ * `allowedScrapers`. An absent list allows everything (plan-engines.ts).
+ */
+function limitsAllow(limits: Plan['limits'], platform: PositionPlatformId): boolean {
+ if (platform === 'claude') {
+ const models = limits.allowedModels;
+ return !models || models.some((m) => m.startsWith('claude'));
+ }
+ const scrapers = limits.allowedScrapers;
+ return !scrapers || scrapers.includes(platform);
+}
+
+/**
+ * Engines the panel offers only through sales on every cloud plan, whatever
+ * the plan's scraper list says. Grok is paused for everyone (Cloro fails
+ * every Grok task; see UNAVAILABLE_PLATFORMS in the tracking worker), so an
+ * included-but-empty card would only look broken. It stays in the plan lists
+ * because removing it there would strip it from stored prompts. Self-hosted
+ * keeps it: there is no sales team behind that plan.
+ */
+const SALES_ONLY_PLATFORMS: readonly PositionPlatformId[] = ['grok-web'];
+
+/**
+ * Whether the org's plan includes an engine, and if not, what unlocks it:
+ * the next subscribable plan that covers it, or a conversation with sales.
+ * `plan` must be the org's effective plan (getOrgPlan), so Enterprise
+ * per-customer overrides are already merged in.
+ */
+export function platformAccess(plan: Plan, platform: PositionPlatformId): PlatformAccess {
+ if (SALES_ONLY_PLATFORMS.includes(platform) && PLAN_ORDER.includes(plan.id)) {
+ return { state: 'locked', requiredPlan: 'enterprise' };
+ }
+ if (limitsAllow(plan.limits, platform)) return { state: 'included' };
+ const above = PLAN_ORDER.slice(PLAN_ORDER.indexOf(plan.id) + 1);
+ const upgrade = above.find(
+ (id) => id !== 'enterprise' && limitsAllow(PLANS[id].limits, platform),
+ );
+ return { state: 'locked', requiredPlan: upgrade === 'growth' ? 'growth' : 'enterprise' };
+}
+
+/**
+ * The brand's first citation in an answer's source list, as a 1-based rank
+ * among the sources that carry a URL. A source counts as the brand's on the
+ * same rule as `citation_count`: its host is one of the brand's domains or a
+ * subdomain of one. Null when none of the sources is the brand's.
+ */
+export function brandCitationPosition(
+ citations: unknown,
+ brandDomains: string[],
+): { rank: number; total: number } | null {
+ if (!Array.isArray(citations)) return null;
+ const domains = brandDomains.map(normalizeDomain).filter(Boolean);
+ if (domains.length === 0) return null;
+
+ let total = 0;
+ let rank: number | null = null;
+ for (const cite of citations) {
+ const url = typeof cite?.url === 'string' ? cite.url.trim() : '';
+ if (!url) continue;
+ total += 1;
+ if (rank !== null) continue;
+ const host = extractHostname(url);
+ if (host && domains.some((d) => host === d || host.endsWith(`.${d}`))) rank = total;
+ }
+ return rank === null ? null : { rank, total };
+}
+
+/** One stored answer, reduced to what the panel needs. */
+export interface PositionAnswer {
+ platform: string;
+ createdAt: string;
+ region: string | null;
+ mentioned: boolean;
+ /** 1-based rank among the tracked brands the answer names; null when not stored. */
+ mentionPosition: number | null;
+ /** How many tracked brands the answer names. */
+ mentionTotal: number | null;
+ sentiment: Sentiment | null;
+ cited: boolean;
+ /** The brand's first source; null when not cited or the source can't be found. */
+ citation: { rank: number; total: number } | null;
+}
+
+export interface PositionStats {
+ best: number;
+ worst: number;
+ avg: number;
+ count: number;
+}
+
+export interface AnswerView {
+ at: string;
+ region: string | null;
+ mentioned: boolean;
+ /** Null when not mentioned, or mentioned with no stored position. */
+ mention: { position: number; total: number | null } | null;
+ sentiment: Sentiment | null;
+ cited: boolean;
+ /** Null when not cited, or cited with no locatable source. */
+ citation: { rank: number; total: number } | null;
+}
+
+export interface PlatformDay {
+ /** UTC date, YYYY-MM-DD. */
+ day: string;
+ /** Newest first. */
+ answers: AnswerView[];
+}
+
+export interface PlatformPositions {
+ id: PositionPlatformId;
+ label: string;
+ access: PlatformAccess;
+ /** Answers collected on this engine in the window: one per completed run. */
+ runs: number;
+ trackedDays: number;
+ mentionedDays: number;
+ citedDays: number;
+ /** Over the answers that mention the brand. */
+ sentiment: { positive: number; neutral: number; negative: number; unavailable: number };
+ mentionPosition: PositionStats | null;
+ citationPosition: PositionStats | null;
+ /** The engine's most recent answer in the window. */
+ latest: AnswerView | null;
+ /** The latest answer misses the brand, but an earlier one in the window had it. */
+ mentionedEarlier: boolean;
+ citedEarlier: boolean;
+ /** Days with at least one answer, newest first. */
+ days: PlatformDay[];
+}
+
+export interface PositionsSummary {
+ /** Every UTC date the window covers, oldest first. */
+ days: string[];
+ /** Tracking runs that produced an answer for this prompt, across engines. */
+ runs: number;
+ trackedDays: number;
+ mentionedDays: number;
+ citedDays: number;
+ untrackedDays: number;
+ lastAnswerAt: string | null;
+ mentionPosition: PositionStats | null;
+ citationPosition: PositionStats | null;
+}
+
+const DAY_MS = 86_400_000;
+
+/**
+ * Answers from one run of a prompt land within a couple of hours of each
+ * other, and runs are a day apart. A gap longer than this between two
+ * consecutive answers starts a new run; answers carry no run id to group by.
+ */
+export const RUN_GAP_MS = 6 * 60 * 60 * 1000;
+
+export function utcDay(iso: string): string {
+ return new Date(iso).toISOString().slice(0, 10);
+}
+
+/**
+ * The UTC dates a window covers, oldest first. A rolling window starts part
+ * way through its first date; that date is left out unless an answer landed
+ * in the part the window covers, so "last 7 days" reads as 7 days rather
+ * than 8 with an empty one in front.
+ */
+export function windowDays(from: string, to: string, answeredDays: Set<string>): string[] {
+ const start = Date.parse(`${utcDay(from)}T00:00:00Z`);
+ const end = Date.parse(`${utcDay(to)}T00:00:00Z`);
+ const days: string[] = [];
+ for (let t = start; t <= end; t += DAY_MS) days.push(new Date(t).toISOString().slice(0, 10));
+
+ const partialStart = Date.parse(from) > start;
+ if (partialStart && days.length > 1 && !answeredDays.has(days[0])) days.shift();
+ return days;
+}
+
+/** Distinct runs among answer timestamps, split on RUN_GAP_MS. */
+export function countRuns(timestamps: string[]): number {
+ const times = timestamps.map((t) => Date.parse(t)).sort((a, b) => a - b);
+ let runs = 0;
+ let last = -Infinity;
+ for (const t of times) {
+ if (t - last > RUN_GAP_MS) runs += 1;
+ last = t;
+ }
+ return runs;
+}
+
+function positionStats(values: number[]): PositionStats | null {
+ if (values.length === 0) return null;
+ const sum = values.reduce((a, b) => a + b, 0);
+ return {
+ best: Math.min(...values),
+ worst: Math.max(...values),
+ avg: Math.round((sum / values.length) * 10) / 10,
+ count: values.length,
+ };
+}
+
+function toView(a: PositionAnswer): AnswerView {
+ return {
+ at: a.createdAt,
+ region: a.region,
+ mentioned: a.mentioned,
+ mention:
+ a.mentioned && a.mentionPosition !== null && a.mentionPosition > 0
+ ? { position: a.mentionPosition, total: a.mentionTotal }
+ : null,
+ sentiment: a.mentioned ? a.sentiment : null,
+ cited: a.cited,
+ citation: a.cited ? a.citation : null,
+ };
+}
+
+function summarizePlatform(
+ platform: { id: PositionPlatformId; label: string; access: PlatformAccess },
+ answers: PositionAnswer[],
+): PlatformPositions {
+ const views = answers.map(toView).sort((a, b) => Date.parse(b.at) - Date.parse(a.at));
+
+ const byDay = new Map<string, AnswerView[]>();
+ for (const v of views) {
+ const day = utcDay(v.at);
+ byDay.set(day, [...(byDay.get(day) ?? []), v]);
+ }
+ const days = [...byDay.entries()]
+ .sort(([a], [b]) => b.localeCompare(a))
+ .map(([day, dayAnswers]) => ({ day, answers: dayAnswers }));
+
+ const sentiment = { positive: 0, neutral: 0, negative: 0, unavailable: 0 };
+ for (const v of views) {
+ if (!v.mentioned) continue;
+ if (v.sentiment) sentiment[v.sentiment] += 1;
+ else sentiment.unavailable += 1;
+ }
+
+ const latest = views[0] ?? null;
+ const earlier = views.slice(1);
+
+ return {
+ ...platform,
+ runs: views.length,
+ trackedDays: days.length,
+ mentionedDays: days.filter((d) => d.answers.some((a) => a.mentioned)).length,
+ citedDays: days.filter((d) => d.answers.some((a) => a.cited)).length,
+ sentiment,
+ mentionPosition: positionStats(views.flatMap((v) => (v.mention ? [v.mention.position] : []))),
+ citationPosition: positionStats(views.flatMap((v) => (v.citation ? [v.citation.rank] : []))),
+ latest,
+ mentionedEarlier: !!latest && !latest.mentioned && earlier.some((v) => v.mentioned),
+ citedEarlier: !!latest && !latest.cited && earlier.some((v) => v.cited),
+ days,
+ };
+}
+
+/**
+ * Fold a window's answers into the panel's summary and per-engine rows.
+ * `answers` must already be limited to the engines the plan includes; a
+ * locked engine gets its row with empty numbers, which the panel replaces
+ * with the upgrade prompt.
+ */
+export function summarizePositions(
+ answers: PositionAnswer[],
+ platforms: { id: PositionPlatformId; label: string; access: PlatformAccess }[],
+ window: { from: string; to: string },
+): { summary: PositionsSummary; platforms: PlatformPositions[] } {
+ const rows = platforms.map((p) =>
+ summarizePlatform(
+ p,
+ p.access.state === 'included' ? answers.filter((a) => a.platform === p.id) : [],
+ ),
+ );
+ const counted = rows.flatMap((r) => r.days.flatMap((d) => d.answers));
+
+ const tracked = new Set(counted.map((a) => utcDay(a.at)));
+ const mentioned = new Set(counted.filter((a) => a.mentioned).map((a) => utcDay(a.at)));
+ const cited = new Set(counted.filter((a) => a.cited).map((a) => utcDay(a.at)));
+ const days = windowDays(window.from, window.to, tracked);
+ const lastAnswerAt = counted.reduce<string | null>(
+ (latest, a) => (latest === null || Date.parse(a.at) > Date.parse(latest) ? a.at : latest),
+ null,
+ );
+
+ return {
+ summary: {
+ days,
+ runs: countRuns(counted.map((a) => a.at)),
+ trackedDays: tracked.size,
+ mentionedDays: mentioned.size,
+ citedDays: cited.size,
+ untrackedDays: days.filter((d) => !tracked.has(d)).length,
+ lastAnswerAt,
+ mentionPosition: positionStats(
+ counted.flatMap((a) => (a.mention ? [a.mention.position] : [])),
+ ),
+ citationPosition: positionStats(
+ counted.flatMap((a) => (a.citation ? [a.citation.rank] : [])),
+ ),
+ },
+ platforms: rows,
+ };
+}