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
fix(insights): show No data, mark low samples and use the UI's locale
Cihan668cae49a44c
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 68e037150..f322d76e4 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1720,7 +1720,14 @@"allPrompts": "all prompts","netSentiment": "Net sentiment","netSentimentTip": "Positive minus negative share of the answers that name or cite your brand.",- "sentimentSplit": "{positive}% pos · {negative}% neg",+ "sentimentSplit": "{positive} pos · {negative} neg",+ "sampleTip": {+ "all": "{count, plural, one {Based on # answer} other {Based on # answers}} in this period.",+ "named": "{count, plural, one {Based on # answer that names you} other {Based on # answers that name you}} in this period.",+ "placed": "{count, plural, one {Based on # answer that places you} other {Based on # answers that place you}} in this period."+ },+ "lowSample": "{count, plural, one {Low sample · # answer} other {Low sample · # answers}}",+ "lowSampleShort": "Low sample","coverage": "Coverage","coverageTip": "Share of answered prompts where you appear at least once.","coverageSub": "{visible} of {active} prompts",@@ -1737,6 +1744,7 @@"summary": {"label": "Summary","visibility": "visibility",+ "lowSample": "{count, plural, one {(low sample · # answer)} other {(low sample · # answers)}}","rank": "#{rank}","ofCount": "of {count}","pts": "{value} pts",@@ -1766,6 +1774,7 @@"leaderboard": {"title": "Leaderboard","headToHead": "Head-to-Head",+ "lowSample": "{count, plural, one {Low sample · # answer} other {Low sample · # answers}}","you": "You","coverageSov": "Coverage {coverage} · SoV {sov}","scoreDetail": "Mentioned in {mentions} answers · cited in {citations} · position factor {factor}",@@ -1779,6 +1788,7 @@},"whyChanged": {"title": "Why it changed",+ "rowLowSample": "Low sample","fullBreakdown": "Full breakdown","gains": "Gains","drops": "Drops",@@ -1798,6 +1808,7 @@},"trend": {"subtitle": "Visibility · {range}",+ "lowSample": "{count, plural, one {low sample · # answer} other {low sample · # answers}}","range": {"24h": "last 24 hours","7d": "last 7 days",@@ -1838,6 +1849,10 @@"openAction": "Open","gapChanged": "The gap changed since the page loaded. Refresh to see the latest."},+ "breakdown": {+ "noData": "No data",+ "lowSample": "Low sample"+ },"header": {"lastRun": "Last run {when}","noRuns": "No runs yet",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsxindex 32a6711dd..bacc08256 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx@@ -1,6 +1,7 @@'use client';import { useRef, useState, useEffect } from 'react';+import { useLocale } from 'next-intl';import { PLATFORM_LABELS } from '@/config/platform-labels';import {AreaChart,@@ -28,6 +29,8 @@ import type {} from '@/lib/actions/tracking';import { getFaviconUrl } from '@/lib/favicon';import { trendAxisTop, type TrendLine, type TrendMarker } from '@/lib/insights-trend';+import { numberFormat } from '@/lib/number-format';+import { dayLabel } from './kpi-format';// ─── Adaptive Y-axis ─────────────────────────────────────────────────────────// Visibility scores are theoretically 0–100 but realistic values for most@@ -302,6 +305,11 @@ export function VisibilityRateTrendChart({onHover: (key: string | null) => void;}) {const { points } = data;+ const locale = useLocale();+ const f = numberFormat(locale);+ // The points' `date` stays the key markers are placed by; what the axis and+ // tooltip print is the day in the UI's locale (VIS-005).+ const labelOf = new Map(points.map((p) => [p.date, dayLabel(p.day, locale)]));const shown = lines.map((line) => ({...line,logoUrl: line.logoUrl ?? (line.domain ? getFaviconUrl(line.domain, 64) : ''),@@ -336,6 +344,7 @@ export function VisibilityRateTrendChart({><XAxisdataKey="date"+ tickFormatter={(date: string) => labelOf.get(date) ?? date}tick={{ fontSize: 11 }}tickLine={false}axisLine={false}@@ -344,6 +353,7 @@ export function VisibilityRateTrendChart({<YAxisdomain={[0, yTop]}ticks={yTicks}+ tickFormatter={(v: number) => f.number(v)}tick={{ fontSize: 11 }}tickLine={false}axisLine={false}@@ -358,7 +368,9 @@ export function VisibilityRateTrendChart({);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>+ <p className="font-medium text-foreground mb-1">+ {labelOf.get(String(label)) ?? label}+ </p>{ordered.map((entry) => {const entity = shown.find((e) => e.key === entry.dataKey);if (!entity) return null;@@ -369,7 +381,9 @@ export function VisibilityRateTrendChart({style={{ backgroundColor: entity.color }}/><span className="text-muted-foreground">{entity.name}:</span>- <span className="font-medium text-foreground">{entry.value}</span>+ <span className="font-medium text-foreground">+ {typeof entry.value === 'number' ? f.number(entry.value) : entry.value}+ </span></div>);})}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsxindex 00f4ce2f7..272afac9b 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx@@ -2,7 +2,7 @@import { useId, useRef, useState } from 'react';import { createPortal } from 'react-dom';-import { useTranslations } from 'next-intl';+import { useLocale, useTranslations } from 'next-intl';import {ArrowUpRight,Eye,@@ -19,7 +19,8 @@ import {} from 'lucide-react';import { Card } from '@/components/ui/card';import { cn } from '@/lib/utils';-import { formatCompactNumber } from '@/lib/format';+import { numberFormat } from '@/lib/number-format';+import { LOW_SAMPLE_ANSWERS } from '@/lib/insights-summary';import type {CompetitorComparisonData,CoverageKpi,@@ -37,6 +38,8 @@ import {TONE_TEXT,upIsGood,type Change,+ rateSamples,+ type RateSample,} from './kpi-format';// ─── Info tooltip ─────────────────────────────────────────────────────────────@@ -239,8 +242,6 @@ function MetricCard({);}-const pct = (n: number | null) => (n === null ? null : `${n}%`);-// ─── The two rows ─────────────────────────────────────────────────────────────interface KpiRowsProps {@@ -274,14 +275,31 @@ export function KpiRows({onNavigate,}: KpiRowsProps) {const t = useTranslations('insights.kpi');+ const locale = useLocale();+ const f = numberFormat(locale);const none = t('noData');+ const pct = (n: number | null) => (n === null ? none : f.percent(n));++ // Every rate comes with its sample size (VIS-005): in the tooltip, and+ // under 20 answers as "Low sample" on the context line, with no change+ // shown for so few answers. A card without a value has nothing to qualify.+ const samples = rateSamples(summary);+ const low = (s: RateSample) => s.count < LOW_SAMPLE_ANSWERS;+ const rateTip = (tip: string, s: RateSample) =>+ `${tip} ${t(`sampleTip.${s.of}`, { count: s.count })}`;+ const rateSub = (s: RateSample, sub: React.ReactNode, hasValue = true) =>+ hasValue && low(s) ? t('lowSample', { count: s.count }) : sub;+ const rateDelta = (s: RateSample, delta: Change | null) => (low(s) ? null : delta);const own = competitors?.brands.findIndex((b) => b.isOwnBrand) ?? -1;const visibilitySub =competitors && own >= 0- ? t('rankOf', { rank: own + 1, count: competitors.brands.length })+ ? t('rankOf', { rank: f.number(own + 1), count: f.number(competitors.brands.length) }): coverage- ? t('appearedIn', { visible: coverage.visiblePrompts, active: coverage.activePrompts })+ ? t('appearedIn', {+ visible: f.number(coverage.visiblePrompts),+ active: f.number(coverage.activePrompts),+ }): null;const basisSub =comparison?.basis === 'same'@@ -308,11 +326,20 @@ export function KpiRows({<div className="grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-5"><MetricCardlabel={t('visibility')}- tooltip={t('visibilityTip')}+ tooltip={rateTip(t('visibilityTip'), samples.visibility)}icon={Eye}- value={String(trend?.summary.rate ?? 0)}- delta={upIsGood(trend?.summary.change ?? null)}- sub={visibilitySub}+ // No trend read: "No data", never a 0 that reads as a score.+ value={trend ? f.number(trend.summary.rate) : none}+ delta={rateDelta(samples.visibility, upIsGood(trend?.summary.change ?? null, { locale }))}+ // The rank stays beside a short mark (the count is in the tooltip):+ // the card is narrow, and the leaderboard is marked too.+ sub={+ trend && low(samples.visibility)+ ? visibilitySub+ ? `${visibilitySub} · ${t('lowSampleShort')}`+ : t('lowSample', { count: samples.visibility.count })+ : visibilitySub+ }spark={trend ? trend.points.map((p) => p.values.you ?? null) : null}onClick={() => onBreakdown('visibility')}clickLabel={t('viewBreakdown', { metric: t('visibility') })}@@ -322,16 +349,16 @@ export function KpiRows({tooltip={quota? t('trackedPromptsTip', {- used: quota.used.toLocaleString('en-US'),- limit: quota.limit.toLocaleString('en-US'),+ used: f.number(quota.used),+ limit: f.number(quota.limit),}): t('trackedPromptsTipUnlimited')}icon={Layers}- value={(trackedPrompts?.activeInPeriod ?? 0).toLocaleString('en-US')}+ value={f.number(trackedPrompts?.activeInPeriod ?? 0)}delta={comparison && comparison.newPrompts > 0- ? { text: signedChange(comparison.newPrompts), tone: 'neutral' }+ ? { text: signedChange(comparison.newPrompts, locale), tone: 'neutral' }: null}sub={trackedSub}@@ -340,8 +367,8 @@ export function KpiRows({? {...quota,label: t('quotaLabel', {- used: quota.used.toLocaleString('en-US'),- limit: quota.limit.toLocaleString('en-US'),+ used: f.number(quota.used),+ limit: f.number(quota.limit),}),}: null@@ -353,8 +380,8 @@ export function KpiRows({label={t('mentions')}tooltip={t('mentionsTip')}icon={MessageCircle}- value={formatCompactNumber(summary.totalMentions)}- delta={upIsGood(summary.mentionsChange, '%')}+ value={f.compact(summary.totalMentions)}+ delta={upIsGood(summary.mentionsChange, { percent: true, locale })}sub={basisSub}spark={daily('mentions')}onClick={() => onBreakdown('mentions')}@@ -364,8 +391,8 @@ export function KpiRows({label={t('citations')}tooltip={t('citationsTip')}icon={Quote}- value={formatCompactNumber(summary.totalCitations)}- delta={upIsGood(summary.citationsChange, '%')}+ value={f.compact(summary.totalCitations)}+ delta={upIsGood(summary.citationsChange, { percent: true, locale })}sub={basisSub}spark={daily('citations')}onClick={() => onNavigate('/dashboard/citations')}@@ -373,18 +400,20 @@ export function KpiRows({/><MetricCardlabel={t('netSentiment')}- tooltip={t('netSentimentTip')}+ tooltip={rateTip(t('netSentimentTip'), samples.netSentiment)}icon={Smile}- value={summary.netSentiment === null ? none : signedValue(summary.netSentiment)}- delta={upIsGood(summary.netSentimentChange)}- sub={+ value={summary.netSentiment === null ? none : signedValue(summary.netSentiment, locale)}+ delta={rateDelta(samples.netSentiment, upIsGood(summary.netSentimentChange, { locale }))}+ sub={rateSub(+ samples.netSentiment,summary.netSentiment === null? null: t('sentimentSplit', {- positive: summary.positiveSentimentPct,- negative: summary.negativeSentimentPct ?? 0,- })- }+ positive: f.percent(summary.positiveSentimentPct),+ negative: f.percent(summary.negativeSentimentPct ?? 0),+ }),+ summary.netSentiment !== null,+ )}spark={daily('netSentiment')}/></div>@@ -394,13 +423,14 @@ export function KpiRows({label={t('coverage')}tooltip={t('coverageTip')}icon={Target}- value={pct(coverage?.value ?? null) ?? none}- delta={upIsGood(coverage?.change ?? null)}+ value={pct(coverage?.value ?? null)}+ delta={upIsGood(coverage?.change ?? null, { locale })}+ // Coverage counts prompts, and its line already gives them.sub={coverage? t('coverageSub', {- visible: coverage.visiblePrompts,- active: coverage.activePrompts,+ visible: f.number(coverage.visiblePrompts),+ active: f.number(coverage.activePrompts),}): null}@@ -408,29 +438,32 @@ export function KpiRows({/><MetricCardlabel={t('shareOfVoice')}- tooltip={t('shareOfVoiceTip')}+ tooltip={rateTip(t('shareOfVoiceTip'), samples.shareOfVoice)}icon={PieChart}- value={pct(sov ? sov.overallSov : null) ?? none}- delta={upIsGood(sov?.overallSovChange ?? null)}- sub={t('shareOfVoiceSub')}+ value={pct(sov ? sov.overallSov : null)}+ delta={rateDelta(+ samples.shareOfVoice,+ upIsGood(sov?.overallSovChange ?? null, { locale }),+ )}+ sub={rateSub(samples.shareOfVoice, t('shareOfVoiceSub'), !!sov)}spark={daily('shareOfVoice')}/><MetricCardlabel={t('avgPosition')}- tooltip={t('avgPositionTip')}+ tooltip={rateTip(t('avgPositionTip'), samples.avgPosition)}icon={ListOrdered}- value={summary.avgPosition === null ? none : `#${summary.avgPosition}`}- delta={lowerIsGood(summary.avgPositionChange)}- sub={t('avgPositionSub')}+ value={summary.avgPosition === null ? none : `#${f.number(summary.avgPosition)}`}+ delta={rateDelta(samples.avgPosition, lowerIsGood(summary.avgPositionChange, locale))}+ sub={rateSub(samples.avgPosition, t('avgPositionSub'), summary.avgPosition !== null)}spark={daily('avgPosition')}/><MetricCardlabel={t('citationRate')}- tooltip={t('citationRateTip')}+ tooltip={rateTip(t('citationRateTip'), samples.citationRate)}icon={Link2}- value={pct(summary.citationRate) ?? none}- delta={upIsGood(summary.citationRateChange)}- sub={t('citationRateSub')}+ value={pct(summary.citationRate)}+ delta={rateDelta(samples.citationRate, upIsGood(summary.citationRateChange, { locale }))}+ sub={rateSub(samples.citationRate, t('citationRateSub'), summary.citationRate !== null)}spark={daily('citationRate')}/></div>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_leaderboard.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_leaderboard.tsxindex b076705db..71fae4c5d 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_leaderboard.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_leaderboard.tsx@@ -1,14 +1,16 @@'use client';import { useState } from 'react';-import { useTranslations } from 'next-intl';+import { useLocale, useTranslations } from 'next-intl';import { ArrowRight, ArrowUp } from 'lucide-react';import { Link } from '@/i18n/navigation';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { cn } from '@/lib/utils';import type { CompetitorComparisonEntry, ProviderComparisonRow } from '@/lib/actions/tracking';import { coverage } from '@/lib/insights-kpis';+import { numberFormat } from '@/lib/number-format';import {+ LOW_SAMPLE_ANSWERS,leaderboardCallout,leaderboardLines,mentionShares,@@ -27,6 +29,7 @@ export function Leaderboard({brands,providerRows,platforms,+ answers,className,}: {/** Brands in rank order, yours included. */@@ -34,9 +37,17 @@ export function Leaderboard({providerRows: ProviderComparisonRow[];/** The By AI platform rows: only a platform with enough answers can be the lever. */platforms: PlatformTableRow[] | null;+ /**+ * Your answers in the period, every score's denominator: under 20 the+ * board is a low sample (VIS-005), and no change is read into it.+ */+ answers?: number;className?: string;}) {const t = useTranslations('insights.leaderboard');+ const locale = useLocale();+ const f = numberFormat(locale);+ const lowSample = answers !== undefined && answers < LOW_SAMPLE_ANSWERS;// Expanded for this board only: another brand or range starts collapsed.const [expandedFor, setExpandedFor] = useState<CompetitorComparisonEntry[] | null>(null);const expanded = expandedFor === brands;@@ -52,7 +63,7 @@ export function Leaderboard({const callout = leaderboardCallout(brands, providerRows, (name) =>(platforms ?? []).some((p) => p.name === name && p.status === 'ok'),);- const percent = (value: number | null) => (value === null ? '—' : `${value}%`);+ const percent = (value: number | null) => (value === null ? '—' : f.percent(value));return (<Card className={className}>@@ -67,6 +78,9 @@ export function Leaderboard({<ArrowRight className="h-3 w-3" /></Link></div>+ {lowSample && (+ <p className="text-xs text-muted-foreground">{t('lowSample', { count: answers! })}</p>+ )}</CardHeader><CardContent><ul className="flex flex-col gap-1.5">@@ -80,14 +94,14 @@ export function Leaderboard({aria-label={t('moreLabel', { count: line.count })}className="w-full py-0.5 text-center text-xs text-muted-foreground transition-colors hover:text-foreground">- {t('more', { count: line.count })}+ {t('more', { count: f.number(line.count) })}</button></li>);}const entry = brands[line.index];- const change = arrowChange(entry.scoreChange);+ const change = lowSample ? null : arrowChange(entry.scoreChange, locale);return (<li key={`${line.index}-${entry.competitorId ?? entry.name}`}><div@@ -97,7 +111,7 @@ export function Leaderboard({)}><span className="w-5 shrink-0 text-center text-xs font-semibold tabular-nums text-muted-foreground">- {line.index + 1}+ {f.number(line.index + 1)}</span><span className="min-w-0 flex-1"><span className="flex items-center gap-1.5">@@ -128,13 +142,13 @@ export function Leaderboard({<spanclassName="block text-sm font-semibold tabular-nums"title={t('scoreDetail', {- mentions: entry.mentionAnswers,- citations: entry.citationAnswers,+ mentions: f.number(entry.mentionAnswers),+ citations: f.number(entry.citationAnswers),factor:- entry.positionFactor === null ? '—' : entry.positionFactor.toFixed(2),+ entry.positionFactor === null ? '—' : f.number(entry.positionFactor, 2),})}>- {entry.score ?? '—'}+ {entry.score === null ? '—' : f.number(entry.score)}</span>{change && (<span@@ -153,8 +167,8 @@ export function Leaderboard({<ArrowUp className="h-3 w-3 shrink-0" aria-hidden /><span>{callout.gap === 0- ? t('tiedWith', { rank: callout.rank })- : t('gapTo', { gap: callout.gap, rank: callout.rank })}+ ? t('tiedWith', { rank: f.number(callout.rank) })+ : t('gapTo', { gap: f.number(callout.gap), rank: f.number(callout.rank) })}{callout.lever && ` · ${t('lever', { platform: callout.lever })}`}</span></p>@@ -169,7 +183,7 @@ export function Leaderboard({onClick={() => setExpandedFor(expanded ? null : brands)}className="mt-1.5 w-full py-1 text-center text-xs font-medium text-muted-foreground transition-colors hover:text-foreground">- {expanded ? t('showLess') : t('showAll', { count: brands.length })}+ {expanded ? t('showLess') : t('showAll', { count: f.number(brands.length) })}</button>)}</CardContent>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_metric-breakdown-sheet.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_metric-breakdown-sheet.tsxindex 6f3d8118a..adfb52fa3 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_metric-breakdown-sheet.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_metric-breakdown-sheet.tsx@@ -1,6 +1,7 @@'use client';import { useEffect, useMemo, useState } from 'react';+import { useLocale, useTranslations } from 'next-intl';import { TrendingDown, TrendingUp, Minus, AlertTriangle } from 'lucide-react';import {Sheet,@@ -14,6 +15,8 @@ import { Badge } from '@/components/ui/badge';import { Skeleton } from '@/components/ui/skeleton';import { Link } from '@/i18n/navigation';import { cn } from '@/lib/utils';+import { numberFormat, type NumberFormat } from '@/lib/number-format';+import { LOW_SAMPLE_ANSWERS } from '@/lib/insights-summary';import { getInsightsBreakdown } from '@/lib/actions/tracking';import {pickDriver,@@ -55,6 +58,7 @@ export function MetricBreakdownSheet({initialTab,}: Props) {const open = Boolean(brandId && metric);+ const locale = useLocale();const [data, setData] = useState<InsightsBreakdown | null>(null);const [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);@@ -74,7 +78,7 @@ export function MetricBreakdownSheet({setLoading(true);setError(null);- getInsightsBreakdown(brandId, metric, filters)+ getInsightsBreakdown(brandId, metric, filters, locale).then((res) => {if (!cancelled) setData(res);})@@ -92,7 +96,7 @@ export function MetricBreakdownSheet({};// filtersKey is the stable dependency; `filters` is intentionally omitted.// eslint-disable-next-line react-hooks/exhaustive-deps- }, [open, brandId, metric, filtersKey]);+ }, [open, brandId, metric, filtersKey, locale]);const title = metric ? METRIC_TITLE[metric] : '';@@ -152,6 +156,7 @@ function BreakdownBody({initialTab?: BreakdownTab;}) {const [tab, setTab] = useState<BreakdownTab>(initialTab ?? 'prompts');+ const f = numberFormat(useLocale());const samePrompts = data.comparison?.basis === 'same';const newCount = data.comparison?.newPrompts ?? 0;@@ -168,7 +173,7 @@ function BreakdownBody({{data.windowDays === null ? 'All time' : `Current ${data.windowDays}d`}</div><div className="text-2xl font-semibold tabular-nums">- {formatValue(data.curTotal, metric)}+ {formatValue(data.curTotal, metric, f)}<span className="text-sm font-normal text-muted-foreground">{METRIC_UNIT[metric]}</span>@@ -182,8 +187,8 @@ function BreakdownBody({Same {data.comparison!.samePrompts}{' '}{data.comparison!.samePrompts === 1 ? 'prompt' : 'prompts'}:{' '}<span className="tabular-nums">- {data.prevTotal === null ? '—' : formatValue(data.prevTotal, metric)} →{' '}- {formatValue(data.comparedCur, metric)}+ {data.prevTotal === null ? '—' : formatValue(data.prevTotal, metric, f)} →{' '}+ {formatValue(data.comparedCur, metric, f)}{METRIC_UNIT[metric]}</span></>@@ -194,7 +199,7 @@ function BreakdownBody({'no data') : (<span className="tabular-nums">- {formatValue(data.prevTotal, metric)}+ {formatValue(data.prevTotal, metric, f)}{METRIC_UNIT[metric]}</span>)}@@ -254,6 +259,7 @@ function BreakdownBody({}function RootCauseSummary({ data, metric }: { data: InsightsBreakdown; metric: BreakdownMetric }) {+ const f = numberFormat(useLocale());const isDrop = (data.delta ?? 0) < 0;const topPrompt = pickDriver(data.byPrompt, data.delta);const topPlatform = pickDriver(data.byPlatform, data.delta);@@ -273,12 +279,12 @@ function RootCauseSummary({ data, metric }: { data: InsightsBreakdown; metric: B>"{truncate(topPrompt.label, 60)}"</Link>{' '}- {formatContribution(topPrompt, metric)}.+ {formatContribution(topPrompt, metric, f)}.{topPlatform && (<>{' '}Top platform {isDrop ? 'drop' : 'gain'}: {topPlatform.label}{' '}- {formatContribution(topPlatform, metric)}.+ {formatContribution(topPlatform, metric, f)}.</>)}</div>@@ -297,6 +303,8 @@ function BreakdownTable({/** False for All time: no previous window, so no Prev or Change column. */comparable: boolean;}) {+ const t = useTranslations('insights.breakdown');+ const f = numberFormat(useLocale());if (rows.length === 0) {return (<div className="py-10 text-center text-sm text-muted-foreground">@@ -334,15 +342,41 @@ function BreakdownTable({<div className="mt-0.5 text-[11px] text-muted-foreground">{r.sublabel}</div>)}</td>+ {/* A window without answers for the row is "No data", never a 0+ to change from; a score on under 20 answers is a low sample (VIS-005). */}{comparable && (<td className="px-2 py-2 text-right tabular-nums text-muted-foreground">- {r.prev === null ? '—' : formatValue(r.prev, metric)}+ {r.prev === null ? (+ '—'+ ) : r.prevRuns === 0 ? (+ <span className="whitespace-nowrap text-xs">{t('noData')}</span>+ ) : (+ formatValue(r.prev, metric, f)+ )}</td>)}- <td className="px-2 py-2 text-right tabular-nums">{formatValue(r.cur, metric)}</td>+ <td+ className={cn(+ 'px-2 py-2 text-right tabular-nums',+ r.curRuns === 0 && 'text-muted-foreground',+ )}+ >+ {r.curRuns === 0 ? (+ <span className="whitespace-nowrap text-xs">{t('noData')}</span>+ ) : (+ formatValue(r.cur, metric, f)+ )}+ </td>{comparable && (<td className="px-2 py-2 text-right">- <DeltaPill delta={r.delta ?? 0} deltaPct={r.deltaPct} metric={metric} />+ {r.prevRuns === 0 || r.curRuns === 0 ? (+ <span className="text-xs text-muted-foreground">—</span>+ ) : metric === 'visibility' &&+ Math.min(r.prevRuns, r.curRuns) < LOW_SAMPLE_ANSWERS ? (+ <span className="text-xs text-muted-foreground">{t('lowSample')}</span>+ ) : (+ <DeltaPill delta={r.delta ?? 0} deltaPct={r.deltaPct} metric={metric} />+ )}</td>)}</tr>@@ -364,6 +398,7 @@ function DeltaPill({metric: BreakdownMetric;big?: boolean;}) {+ const f = numberFormat(useLocale());if (delta === 0) {return (<span@@ -372,7 +407,8 @@ function DeltaPill({big ? 'text-sm' : 'text-xs',)}>- <Minus className={big ? 'h-3.5 w-3.5' : 'h-3 w-3'} />0+ <Minus className={big ? 'h-3.5 w-3.5' : 'h-3 w-3'} />+ {f.number(0)}</span>);}@@ -384,13 +420,13 @@ function DeltaPill({// Prefer percentage display for count metrics when available; fall back to// absolute delta for visibility (pts) or when previous was zero.const showPct = metric !== 'visibility' && deltaPct !== null;- const sign = positive ? '+' : '';+ const sign = positive ? '+' : '−';const primary = showPct- ? `${sign}${deltaPct}%`+ ? `${sign}${f.percent(Math.abs(deltaPct))}`: metric === 'visibility'- ? `${sign}${delta} pts`- : `${sign}${delta}`;- const secondary = showPct ? `${sign}${delta}` : null;+ ? `${sign}${f.number(Math.abs(delta))} pts`+ : `${sign}${f.number(Math.abs(delta))}`;+ const secondary = showPct ? `${sign}${f.number(Math.abs(delta))}` : null;return (<span@@ -411,28 +447,25 @@ function DeltaPill({);}-function formatValue(value: number, metric: BreakdownMetric): string {- if (metric === 'visibility') {- return value.toLocaleString(undefined, { maximumFractionDigits: 1 });- }- return value.toLocaleString();+function formatValue(value: number, metric: BreakdownMetric, f: NumberFormat): string {+ return f.number(metric === 'visibility' ? Math.round(value * 10) / 10 : value);}-function formatContribution(row: BreakdownRow, metric: BreakdownMetric): string {+function formatContribution(row: BreakdownRow, metric: BreakdownMetric, f: NumberFormat): string {const delta = row.delta ?? 0;const isLoss = delta < 0;const abs = Math.abs(delta);if (metric === 'visibility') {const verb = isLoss ? 'dropped' : 'rose';- return `${verb} ${Math.round(abs * 10) / 10} pts`;+ return `${verb} ${f.number(Math.round(abs * 10) / 10)} pts`;}const verb = isLoss ? 'lost' : 'gained';- const core = `${verb} ${abs.toLocaleString()} mention${abs !== 1 ? 's' : ''}`;+ const core = `${verb} ${f.number(abs)} mention${abs !== 1 ? 's' : ''}`;if (row.deltaPct === null) return core;const sign = row.deltaPct < 0 ? '−' : '+';- return `${core} (${sign}${Math.abs(row.deltaPct)}%)`;+ return `${core} (${sign}${f.percent(Math.abs(row.deltaPct))})`;}function truncate(value: string, max: number): string {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsxindex e6cca9421..4e61c2492 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx@@ -1,13 +1,13 @@'use client';import { useMemo, useState } from 'react';-import { useFormatter, useTranslations } from 'next-intl';+import { useFormatter, useLocale, useTranslations } from 'next-intl';import { ArrowRight, Loader2, MessageCircle, Tag } from 'lucide-react';import { toast } from 'sonner';import { Link, useRouter } from '@/i18n/navigation';import { Button } from '@/components/ui/button';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';-import { formatCompactNumber } from '@/lib/format';+import { numberFormat } from '@/lib/number-format';import { trackSuggestions } from '@/lib/actions/prompt-suggestions';import { sendTopicOpportunityToActionCenter } from '@/lib/actions/topic';import { generateOpportunitiesOnDemand, getGenerationJobStatus } from '@/lib/actions/content';@@ -63,6 +63,7 @@ export function Opportunities({}) {const t = useTranslations('insights.opportunities');const format = useFormatter();+ const f = numberFormat(useLocale());const router = useRouter();const [trackedIds, setTrackedIds] = useState<ReadonlySet<string>>(new Set());const [busy, setBusy] = useState<string | null>(null);@@ -242,14 +243,14 @@ export function Opportunities({};const meta = (item: Opportunity): string => {- const volume = t('volume', { volume: formatCompactNumber(item.volume) });- if (item.kind === 'prompt') return [volume, t('notTracked')].join(' · ');+ const volume = item.volume === null ? null : t('volume', { volume: f.compact(item.volume) });+ if (item.kind === 'prompt') return [volume, t('notTracked')].filter(Boolean).join(' · ');const s = item.standing;const standing =s.kind === 'competitor'? s.name? t('competitorLeads', { name: s.name })- : t('leaderScore', { score: s.score.toFixed(1) })+ : t('leaderScore', { score: f.number(s.score, 1) }): s.kind === 'you'? t('youLead'): s.kind === 'notTracked'diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_platform-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_platform-table.tsxindex 3cf15daad..b668c55e8 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_platform-table.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_platform-table.tsx@@ -1,8 +1,9 @@'use client';-import { useTranslations } from 'next-intl';+import { useLocale, useTranslations } from 'next-intl';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { cn } from '@/lib/utils';+import { numberFormat } from '@/lib/number-format';import type { PlatformTableRow } from '@/lib/insights-summary';import { TONE_TEXT, upIsGood } from './kpi-format';@@ -20,6 +21,8 @@ export function PlatformTable({className?: string;}) {const t = useTranslations('insights.platforms');+ const locale = useLocale();+ const f = numberFormat(locale);// Share-of-voice bars are scaled to the largest share in the table.const maxSov = Math.max(0, ...rows.map((r) => r.shareOfVoice ?? 0));@@ -42,7 +45,7 @@ export function PlatformTable({</thead><tbody>{rows.map((row) => {- const change = upIsGood(row.change);+ const change = upIsGood(row.change, { locale });return (<trkey={row.name}@@ -58,7 +61,7 @@ export function PlatformTable({{row.status === 'ok' ? (<><td className="px-2 py-2.5 text-right font-semibold tabular-nums">- {row.visibility}+ {row.visibility === null ? '—' : f.number(row.visibility)}</td><tdclassName={cn(@@ -69,7 +72,7 @@ export function PlatformTable({{change?.text ?? '—'}</td><td className="px-2 py-2.5 text-right tabular-nums">- {row.coverage === null ? '—' : `${row.coverage}%`}+ {row.coverage === null ? '—' : f.percent(row.coverage)}</td><td className="px-2 py-2.5">{row.shareOfVoice === null ? (@@ -85,13 +88,13 @@ export function PlatformTable({/></span><span className="min-w-10 text-right tabular-nums">- {row.shareOfVoice}%+ {f.percent(row.shareOfVoice)}</span></span>)}</td><td className="py-2.5 pl-2 text-right tabular-nums">- {row.avgPosition === null ? '—' : `#${row.avgPosition}`}+ {row.avgPosition === null ? '—' : `#${f.number(row.avgPosition)}`}</td></>) : (diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_run-line.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_run-line.tsxindex eb6620b1c..26743e615 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_run-line.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_run-line.tsx@@ -1,9 +1,10 @@'use client';import { Fragment, useEffect, useState } from 'react';-import { useTranslations } from 'next-intl';+import { useLocale, useTranslations } from 'next-intl';import { formatRelative } from '@/lib/format-relative';import { timeUntil } from '@/lib/tracking-schedule';+import { numberFormat } from '@/lib/number-format';/*** The header's "Acme Coffee · Last run 11h ago · next run in 13h" (VIS-012).@@ -26,6 +27,7 @@ export function RunLine({}) {const t = useTranslations('insights.header');const tCommon = useTranslations('common');+ const f = numberFormat(useLocale());const [, setTick] = useState(0);useEffect(() => {const id = setInterval(() => setTick((n) => n + 1), 60_000);@@ -41,7 +43,7 @@ export function RunLine({: hasData? null: t('noRuns'),- nextIn ? t('nextRun', { when: t(nextIn.unit, { n: nextIn.value }) }) : null,+ nextIn ? t('nextRun', { when: t(nextIn.unit, { n: f.number(nextIn.value) }) }) : null,].filter((part): part is string => part !== null);return (diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_summary-line.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_summary-line.tsxindex 6bf1123c3..a860269c0 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_summary-line.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_summary-line.tsx@@ -1,7 +1,7 @@'use client';import { Fragment } from 'react';-import { useTranslations } from 'next-intl';+import { useLocale, useTranslations } from 'next-intl';import { Copy, Sparkles } from 'lucide-react';import { toast } from 'sonner';import { cn } from '@/lib/utils';@@ -18,9 +18,10 @@ import { summaryContext, summaryFacts, summaryText, type SummaryInput } from './export function SummaryLine(props: SummaryInput) {const t = useTranslations('insights.summary');const tCompare = useTranslations('insights.compare');+ const input = { ...props, locale: useLocale() };- const facts = summaryFacts(props, t);- const context = summaryContext(props, t, tCompare);+ const facts = summaryFacts(input, t);+ const context = summaryContext(input, t, tCompare);if (facts.length === 0 && !context) return null;const copy = async () => {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_topic-heatmap.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_topic-heatmap.tsxindex 38ed686a8..972c18e58 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_topic-heatmap.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_topic-heatmap.tsx@@ -1,7 +1,7 @@'use client';import { useState } from 'react';-import { useTranslations } from 'next-intl';+import { useLocale, useTranslations } from 'next-intl';import { ArrowRight } from 'lucide-react';import { toast } from 'sonner';import { Link, useRouter } from '@/i18n/navigation';@@ -9,15 +9,13 @@ import { Button } from '@/components/ui/button';import { sendTopicGapToActionCenter, type TopicGapWindow } from '@/lib/actions/topic';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { cn } from '@/lib/utils';+import { numberFormat } from '@/lib/number-format';import { biggestGap, heatShade, topicHeatmap, type TopicCompetitors } from '@/lib/insights-topics';import { TONE_TEXT } from './kpi-format';/** Rows shown before "Show all". */const VISIBLE_ROWS = 6;-/** A gap with one decimal, so the column lines up: "−29.0", "−20.3". */-const gapText = (gap: number) => `−${Math.abs(gap).toFixed(1)}`;-/*** Cell shades, light to dark: soft theme-relative tints, so they read in* both themes and a full table doesn't turn into dark blocks. The text keeps@@ -51,6 +49,9 @@ export function TopicHeatmap({className?: string;}) {const t = useTranslations('insights.topicMap');+ const f = numberFormat(useLocale());+ /** A gap with one decimal, so the column lines up: "−29.0", "−20.3". */+ const gapText = (gap: number) => `−${f.number(Math.abs(gap), 1)}`;const router = useRouter();const [sending, setSending] = useState(false);// Expanded for this data only: another brand or range starts folded.@@ -111,7 +112,7 @@ export function TopicHeatmap({? t('sendGapTitle', {topic: target.name,competitor: targetCompetitor ?? '',- gap: Math.abs(target.gap!).toFixed(1),+ gap: f.number(Math.abs(target.gap!), 1),}): t('noGap')}@@ -167,7 +168,7 @@ export function TopicHeatmap({row.status === 'lowSample' && 'opacity-50',)}>- {value.toFixed(1)}+ {f.number(value, 1)}</Link></td>))}@@ -197,7 +198,7 @@ export function TopicHeatmap({onClick={() => setExpandedFor(expanded ? null : topics)}className="mt-1.5 w-full py-1 text-center text-xs font-medium text-muted-foreground transition-colors hover:text-foreground">- {expanded ? t('showLess') : t('showAll', { count: rows.length })}+ {expanded ? t('showLess') : t('showAll', { count: f.number(rows.length) })}</button>)}</CardContent>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_trend-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_trend-card.tsxindex fdf5a370e..61b277415 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_trend-card.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_trend-card.tsx@@ -2,7 +2,7 @@import { useState } from 'react';import dynamic from 'next/dynamic';-import { useTranslations } from 'next-intl';+import { useLocale, useTranslations } from 'next-intl';import { Plus } from 'lucide-react';import { toast } from 'sonner';import { Card, CardContent, CardHeader } from '@/components/ui/card';@@ -17,6 +17,9 @@ import {DropdownMenuTrigger,} from '@/components/ui/dropdown-menu';import { cn } from '@/lib/utils';+import { numberFormat } from '@/lib/number-format';+import { LOW_SAMPLE_ANSWERS } from '@/lib/insights-summary';+import { dayLabel } from './kpi-format';import { useUserRole } from '@/hooks/use-user-role';import { setPinnedCompetitors } from '@/lib/actions/brand';import type { VisibilityRateTrendData } from '@/lib/actions/tracking';@@ -33,14 +36,6 @@ const VisibilityRateTrendChart = dynamic({ 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@@ -59,6 +54,7 @@ export function TrendCard({data,markers,rangeLabel,+ answers,onPinnedChange,className,}: {@@ -68,10 +64,14 @@ export function TrendCard({markers: TrendMarkerData | null;/** "last 30 days", "all time", … */rangeLabel: string;+ /** The period's answers: under 20 the headline is a low sample (VIS-005). */+ answers?: number;onPinnedChange: (pinned: string[]) => void;className?: string;}) {const t = useTranslations('insights.trend');+ const locale = useLocale();+ const f = numberFormat(locale);const { canManage } = useUserRole();const [hoveredKey, setHoveredKey] = useState<string | null>(null);const [saving, setSaving] = useState(false);@@ -110,13 +110,16 @@ export function TrendCard({const describe = (m: TrendMarker) =>m.kind === 'prompts'- ? t('promptsAdded', { count: m.count, date: dayLabel(m.day) })+ ? t('promptsAdded', { count: m.count, date: dayLabel(m.day, locale) }): t('actionsSent', {actions:m.actionNos.length > 3- ? t('moreActions', { actions: actionIds(m.actionNos), count: m.actionNos.length - 3 })+ ? t('moreActions', {+ actions: actionIds(m.actionNos),+ count: f.number(m.actionNos.length - 3),+ }): actionIds(m.actionNos),- date: dayLabel(m.day),+ date: dayLabel(m.day, locale),});// Every marker is listed below the chart; only those with a point are drawn on it.const placed = markers@@ -128,7 +131,7 @@ export function TrendCard({: [];const goal =markers?.goal != null- ? { value: markers.goal, label: t('goal', { value: markers.goal }) }+ ? { value: markers.goal, label: t('goal', { value: f.number(markers.goal) }) }: null;return (@@ -136,9 +139,12 @@ export function TrendCard({<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-3xl font-bold tabular-nums">{f.number(data.summary.rate)}</div><div className="text-xs text-muted-foreground">{t('subtitle', { range: rangeLabel })}+ {answers !== undefined && answers < LOW_SAMPLE_ANSWERS && (+ <> · {t('lowSample', { count: answers })}</>+ )}</div></div><ul className="flex flex-wrap items-center gap-1.5">diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_why-changed.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_why-changed.tsxindex d6bd8ead8..43a374030 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_why-changed.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_why-changed.tsx@@ -1,9 +1,11 @@'use client';-import { useTranslations } from 'next-intl';+import { useLocale, useTranslations } from 'next-intl';import { ArrowRight } from 'lucide-react';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { cn } from '@/lib/utils';+import { numberFormat } from '@/lib/number-format';+import { LOW_SAMPLE_ANSWERS } from '@/lib/insights-summary';import type { Driver, DriverKind, WhyChanged as WhyChangedData } from '@/lib/insights-drivers';import { signedChange, TONE_TEXT } from './kpi-format';import type { BreakdownTab } from './_metric-breakdown-sheet';@@ -15,9 +17,9 @@ const TAB_OF: Record<DriverKind, BreakdownTab> = {};/** "Oct 12", or "Sep 29 – Oct 12" when the prompts were added over several days. */-function addedOn(first: string | null, last: string | null): string | null {+function addedOn(first: string | null, last: string | null, locale: string): string | null {const day = (ts: string) =>- new Date(ts).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });+ new Date(ts).toLocaleDateString(locale, { month: 'short', day: 'numeric' });if (!first || !last) return first ? day(first) : last ? day(last) : null;return day(first) === day(last) ? day(last) : `${day(first)} – ${day(last)}`;}@@ -38,7 +40,9 @@ export function WhyChanged({className?: string;}) {const t = useTranslations('insights.whyChanged');- const date = addedOn(data.newPrompts.firstAdded, data.newPrompts.lastAdded);+ const locale = useLocale();+ const f = numberFormat(locale);+ const date = addedOn(data.newPrompts.firstAdded, data.newPrompts.lastAdded, locale);const nameOf = (d: Driver) =>d.name ?? (d.kind === 'topic' ? t('uncategorized') : t('deletedPrompt'));@@ -66,8 +70,11 @@ export function WhyChanged({<span className="min-w-0 flex-1 truncate text-[13px]" title={name}>{name}</span>+ {/* A slice's own score on a handful of answers says little (VIS-005). */}<span className="shrink-0 text-xs tabular-nums text-muted-foreground">- {t('range', { prev: d.prev.toFixed(1), cur: d.cur.toFixed(1) })}+ {Math.min(d.answers.prev, d.answers.cur) < LOW_SAMPLE_ANSWERS+ ? t('rowLowSample')+ : t('range', { prev: f.number(d.prev, 1), cur: f.number(d.cur, 1) })}</span><spanclassName={cn(@@ -75,7 +82,7 @@ export function WhyChanged({TONE_TEXT[d.impact > 0 ? 'good' : 'bad'],)}>- {signedChange(d.impact)}+ {signedChange(d.impact, locale)}</span></button></li>@@ -103,7 +110,10 @@ export function WhyChanged({<CardContent className="flex flex-1 flex-col gap-3">{data.status === 'lowSample' ? (<p className="text-sm text-muted-foreground">- {t('lowSample', { cur: data.answers.cur, prev: data.answers.prev })}+ {t('lowSample', {+ cur: f.number(data.answers.cur),+ prev: f.number(data.answers.prev),+ })}</p>) : data.gains.length === 0 && data.drops.length === 0 ? (<p className="text-sm text-muted-foreground">{t('steady')}</p>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.test.tsindex afa319a43..0ab93bd34 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.test.ts+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest';import {+ rateSamples,arrowChange,formatWindowBound,lowerIsGood,@@ -22,12 +23,20 @@ describe('KPI card formatting', () => {});it('colours a rise good and a fall bad on most cards', () => {- expect(upIsGood(18, '%')).toEqual({ text: '+18%', tone: 'good' });+ expect(upIsGood(18, { percent: true })).toEqual({ text: '+18%', tone: 'good' });expect(upIsGood(-4)).toEqual({ text: '−4', tone: 'bad' });- expect(upIsGood(0, '%')).toEqual({ text: '±0', tone: 'neutral' });+ expect(upIsGood(0, { percent: true })).toEqual({ text: '±0', tone: 'neutral' });expect(upIsGood(null)).toBeNull();});+ it('writes every number in the UI’s locale (VIS-005)', () => {+ expect(signedChange(-1234.5, 'tr')).toBe('−1.234,5');+ expect(upIsGood(18.5, { percent: true, locale: 'tr' })?.text).toBe('+%18,5');+ expect(lowerIsGood(-0.3, 'tr')?.text).toBe('↑0,3');+ expect(arrowChange(4.1, 'tr')?.text).toBe('↑ 4,1');+ expect(formatWindowBound('2026-08-16', 'tr')).toBe('16 Ağu 2026');+ });+it('reads a lower Avg. position as an improvement', () => {expect(lowerIsGood(-0.3)).toEqual({ text: '↑0.3', tone: 'good' });expect(lowerIsGood(0.5)).toEqual({ text: '↓0.5', tone: 'bad' });@@ -41,6 +50,15 @@ describe('KPI card formatting', () => {expect(arrowChange(null)).toBeNull();});+ it('takes each rate over its own answers (VIS-005)', () => {+ const samples = rateSamples({ totalResults: 300, mentioningResults: 6, positionedResults: 4 });+ expect(samples.visibility).toEqual({ count: 300, of: 'all' });+ expect(samples.citationRate).toEqual({ count: 300, of: 'all' });+ // Net sentiment and Avg. position can be a low sample in a full period.+ expect(samples.netSentiment).toEqual({ count: 6, of: 'named' });+ expect(samples.avgPosition).toEqual({ count: 4, of: 'placed' });+ });+it('labels whole-day windows by their UTC days', () => {// A day-only bound is the UTC day itself, whatever the viewer's zone.expect(formatWindowBound('2026-08-16')).toBe('Aug 16, 2026');diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.ts b/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.tsindex 578a3dd27..e0240b2a8 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.ts+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.ts@@ -4,6 +4,8 @@* tested on their own.*/+import { numberFormat } from '@/lib/number-format';+/** Whether a change is good news, bad news, or neither (counts like tracked prompts). */export type Tone = 'good' | 'bad' | 'neutral';@@ -21,54 +23,109 @@ export interface Change {const MINUS = '−';+/**+ * The writers below take the UI's locale (VIS-005); English when left out,+ * which is also what the tests read.+ */+/** A change: "+1.5", "−3.2", "±0". */-export function signedChange(n: number): string {- if (n === 0) return '±0';- return `${n > 0 ? '+' : MINUS}${Math.abs(n).toLocaleString('en-US')}`;+export function signedChange(n: number, locale = 'en'): string {+ return numberFormat(locale).signed(n);}/** A value that can be negative, like Net sentiment: "+34", "−6", "0". */-export function signedValue(n: number): string {- return n === 0 ? '0' : signedChange(n);+export function signedValue(n: number, locale = 'en'): string {+ return n === 0 ? numberFormat(locale).number(0) : signedChange(n, locale);}-/** A change where up is good (most cards). */-export function upIsGood(change: number | null, suffix = ''): Change | null {+/**+ * A change where up is good (most cards). `percent` writes a relative change+ * as a percent in the locale's way: "+18%", "+%18".+ */+export function upIsGood(+ change: number | null,+ { percent = false, locale = 'en' }: { percent?: boolean; locale?: string } = {},+): Change | null {if (change === null) return null;- return {- text: `${signedChange(change)}${change === 0 ? '' : suffix}`,- tone: change > 0 ? 'good' : change < 0 ? 'bad' : 'neutral',- };+ const f = numberFormat(locale);+ const text =+ change === 0+ ? '±0'+ : percent+ ? `${change > 0 ? '+' : MINUS}${f.percent(Math.abs(change))}`+ : f.signed(change);+ return { text, tone: change > 0 ? 'good' : change < 0 ? 'bad' : 'neutral' };}/** Avg. position: a lower number is better, shown as an arrow up when it improves. */-export function lowerIsGood(change: number | null): Change | null {+export function lowerIsGood(change: number | null, locale = 'en'): Change | null {if (change === null) return null;if (change === 0) return { text: '±0', tone: 'neutral' };return {- text: `${change < 0 ? '↑' : '↓'}${Math.abs(change)}`,+ text: `${change < 0 ? '↑' : '↓'}${numberFormat(locale).number(Math.abs(change))}`,tone: change < 0 ? 'good' : 'bad',};}/** A score change on the leaderboard, as in the v2 mockup: "↑ 4.1", "↓ 1.1", "±0". */-export function arrowChange(change: number | null): Change | null {+export function arrowChange(change: number | null, locale = 'en'): Change | null {if (change === null) return null;if (change === 0) return { text: '±0', tone: 'neutral' };+ const abs = Math.round(Math.abs(change) * 10) / 10;return {- text: `${change > 0 ? '↑' : '↓'} ${Math.abs(change).toLocaleString('en-US', { maximumFractionDigits: 1 })}`,+ text: `${change > 0 ? '↑' : '↓'} ${numberFormat(locale).number(abs)}`,tone: change > 0 ? 'good' : 'bad',};}+/** A rate card's sample: how many answers its rate is taken over, and which ones. */+export interface RateSample {+ count: number;+ /** 'all' answers, those that 'named' the brand, or those that 'placed' it. */+ of: 'all' | 'named' | 'placed';+}++/**+ * Each rate card's sample (VIS-005: "Every rate comes with its sample size;+ * under 20 is Low sample"). Net sentiment is a share of the answers that name+ * the brand and Avg. position an average over those that place it, so they+ * can rest on far fewer answers than the period has.+ */+export function rateSamples(s: {+ totalResults: number;+ mentioningResults: number;+ positionedResults: number;+}): Record<+ 'visibility' | 'shareOfVoice' | 'citationRate' | 'netSentiment' | 'avgPosition',+ RateSample+> {+ const all: RateSample = { count: s.totalResults, of: 'all' };+ return {+ visibility: all,+ shareOfVoice: all,+ citationRate: all,+ netSentiment: { count: s.mentioningResults, of: 'named' },+ avgPosition: { count: s.positionedResults, of: 'placed' },+ };+}++/** A 'YYYY-MM-DD' UTC day as "Sep 29", in the UI's locale. */+export function dayLabel(day: string, locale = 'en'): string {+ return new Date(`${day}T00:00:00Z`).toLocaleDateString(locale, {+ month: 'short',+ day: 'numeric',+ timeZone: 'UTC',+ });+}+/*** A comparison-window bound for the "vs <range>" label. Whole-day windows* come as 'YYYY-MM-DD' UTC days and are shown as those days; the 24h and* topic views come as timestamps and are shown in local time.*/-export function formatWindowBound(value: string): string {+export function formatWindowBound(value: string, locale = 'en'): string {const dayOnly = /^\d{4}-\d{2}-\d{2}$/.test(value);- return new Date(dayOnly ? `${value}T00:00:00Z` : value).toLocaleDateString('en-US', {+ return new Date(dayOnly ? `${value}T00:00:00Z` : value).toLocaleDateString(locale, {month: 'short',day: '2-digit',year: 'numeric',diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsxindex 563765549..87332e6e5 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx@@ -3,7 +3,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 { useLocale, useTranslations } from 'next-intl';import { Skeleton } from '@/components/ui/skeleton';import { MetricBreakdownSheet, type BreakdownTab } from './_metric-breakdown-sheet';import { FormulaDialog } from './_formula-dialog';@@ -698,6 +698,7 @@ export default function InsightsPage() {const tCommon = useTranslations('common');const router = useRouter();const { isCloud } = usePlanContext();+ const locale = useLocale();const brand = useBrandStore((s) => s.getActiveBrand());const [summary, setSummary] = useState<InsightsSummary | null>(null);const [trackedPrompts, setTrackedPrompts] = useState<TrackedPromptsKpi | null>(null);@@ -1191,8 +1192,8 @@ export default function InsightsPage() {const trendRangeLabel =filters.datePreset === 'custom'? t('trend.range.custom', {- from: formatWindowBound(filters.dateFrom),- to: formatWindowBound(filters.dateTo),+ from: formatWindowBound(filters.dateFrom, locale),+ to: formatWindowBound(filters.dateTo, locale),}): t(`trend.range.${filters.datePreset}`);@@ -1301,6 +1302,7 @@ export default function InsightsPage() {competitors={competitorData}comparison={comparison}platformChanges={platformChanges}+ answers={summary?.totalResults}/>{/* KPI cards (VIS-003): today's five, then the new rates. */}@@ -1329,6 +1331,7 @@ export default function InsightsPage() {data={rateTrend}markers={trendMarkers}rangeLabel={trendRangeLabel}+ answers={summary?.totalResults}onPinnedChange={(pinned) =>setRateTrend((current) => current && { ...current, pinned })}@@ -1339,6 +1342,7 @@ export default function InsightsPage() {brands={competitorData.brands}providerRows={competitorData.providerRows}platforms={platforms}+ answers={summary?.totalResults}/></div>) : (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 83133c734..49b811ddd 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@@ -14,6 +14,7 @@ const messages: Record<string, string> = {upMost: 'Up most:',downMost: 'Down most:',vs: 'vs {from} – {to}',+ lowSample: '(low sample · {count} answers)',newExcluded: '{count} new prompts excluded',newIncluded: 'includes {count} new prompts',};@@ -93,4 +94,27 @@ describe('summary line', () => {expect(context).toBe('vs Aug 14, 2026 – Sep 12, 2026 · includes 509 new prompts');});++ it('marks a score on under 20 answers and reads no change into it (VIS-005)', () => {+ const facts = summaryFacts(input({ answers: 14 }), t);+ expect(facts[0].parts.map((p) => p.text)).toEqual([+ '17.4',+ 'visibility',+ '(low sample · 14 answers)',+ ]);+ // 20 or more is a full sample: the change shows, no mark.+ expect(summaryFacts(input({ answers: 20 }), t)[0].parts.map((p) => p.text)).toEqual([+ '17.4',+ 'visibility',+ '+1.5',+ ]);+ });++ it('writes every number in the UI’s locale (VIS-005)', () => {+ const tr = input({ locale: 'tr', trend: trend(1234.5, -3.2) });+ const text = summaryText(summaryFacts(tr, t), summaryContext(tr, t, t));+ expect(text).toContain('1.234,5 visibility −3,2');+ expect(text).toContain('0,9 pts behind Peec AI');+ expect(text).toContain('vs 14 Ağu 2026 – 12 Eyl 2026');+ });});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/summary-format.ts b/web/src/app/[locale]/(dashboard)/dashboard/insights/summary-format.tsindex c3f9bf850..46296439f 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/summary-format.ts+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/summary-format.ts@@ -1,6 +1,12 @@import type { CompetitorComparisonData, VisibilityRateTrendData } from '@/lib/actions/tracking';import type { PromptComparison } from '@/lib/insights-same-prompts';-import { platformMovers, rankSummary, type PlatformChange } from '@/lib/insights-summary';+import {+ LOW_SAMPLE_ANSWERS,+ platformMovers,+ rankSummary,+ type PlatformChange,+} from '@/lib/insights-summary';+import { numberFormat } from '@/lib/number-format';import { formatWindowBound, upIsGood, type Tone } from './kpi-format';/**@@ -28,21 +34,30 @@ export interface SummaryInput {competitors: CompetitorComparisonData | null;comparison: PromptComparison | null;platformChanges: PlatformChange[] | null;+ /** The period's answers: under 20, the score is a low sample (VIS-005). */+ answers?: number;+ /** The UI's locale, for every number (VIS-005); English when left out. */+ locale?: string;}/** The line's facts, left to right; a fact without its data is left out. */export function summaryFacts(input: SummaryInput, t: Translate): SummaryFact[] {const facts: SummaryFact[] = [];+ const locale = input.locale ?? 'en';+ const f = numberFormat(locale);+ const lowSample = input.answers !== undefined && input.answers < LOW_SAMPLE_ANSWERS;- // No score without the trend: a missing read must not read as 0.+ // No score without the trend: a missing read must not read as 0. Under 20+ // answers the score says so, and no change is read into so few.if (input.trend) {- const change = upIsGood(input.trend.summary.change);+ const change = lowSample ? null : upIsGood(input.trend.summary.change, { locale });facts.push({key: 'visibility',parts: [- { text: String(input.trend.summary.rate), bold: true },+ { text: f.number(input.trend.summary.rate), bold: true },{ text: t('visibility') },...(change ? [{ text: change.text, tone: change.tone }] : []),+ ...(lowSample ? [{ text: t('lowSample', { count: input.answers! }) }] : []),],});}@@ -53,12 +68,12 @@ export function summaryFacts(input: SummaryInput, t: Translate): SummaryFact[] {facts.push({key: 'rank',parts: [- { text: t('rank', { rank: rank.rank }), bold: true },- { text: `${t('ofCount', { count: rank.count })} ·` },+ { text: t('rank', { rank: f.number(rank.rank) }), bold: true },+ { text: `${t('ofCount', { count: f.number(rank.count) })} ·` },...(neighbour.side === 'tied'? [{ text: t('tied', { name: neighbour.name }) }]: [- { text: t('pts', { value: neighbour.gap }), bold: true },+ { text: t('pts', { value: f.number(neighbour.gap) }), bold: true },{text:neighbour.side === 'behind'@@ -76,7 +91,7 @@ export function summaryFacts(input: SummaryInput, t: Translate): SummaryFact[] {['down', t('downMost'), down],] as const) {if (!mover) continue;- const moved = upIsGood(mover.change)!;+ const moved = upIsGood(mover.change, { locale })!;facts.push({key,parts: [@@ -100,8 +115,8 @@ export function summaryContext(const parts = [trend && trend.summary.change !== null && trend.summary.prevFrom? t('vs', {- from: formatWindowBound(trend.summary.prevFrom),- to: formatWindowBound(trend.summary.prevTo),+ from: formatWindowBound(trend.summary.prevFrom, input.locale),+ to: formatWindowBound(trend.summary.prevTo, input.locale),}): null,comparison && comparison.newPrompts > 0diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.tsindex 2a7aa484a..a8ffb5d17 100644--- a/web/src/lib/actions/tracking.ts+++ b/web/src/lib/actions/tracking.ts@@ -43,6 +43,7 @@ import { getOrgPlan } from '@/lib/guards/plan-guard';import { getOrgLocationUsage } from '@/lib/prompt-locations';import { getPromptSuggestions } from '@/lib/actions/prompt-suggestions';import { nextScheduledRun } from '@/lib/tracking-schedule';+import { numberFormat, type NumberFormat } from '@/lib/number-format';import { getContentUsage } from '@/lib/actions/content';import type { ContentUsage } from '@/lib/content-usage';import { percentageChange } from '@/lib/metrics';@@ -228,6 +229,12 @@ export interface InsightsSummary {netSentimentChange: number | null;avgPosition: number | null;avgPositionChange: number | null;+ /**+ * The answers Net sentiment and Avg. position are taken over (VIS-005):+ * those that name the brand, and those that place it.+ */+ mentioningResults: number;+ positionedResults: number;}/**@@ -1847,6 +1854,8 @@ export async function getInsightsSummary(netSentimentChange: null,avgPosition: null,avgPositionChange: null,+ mentioningResults: 0,+ positionedResults: 0,};}@@ -1991,6 +2000,8 @@ export async function getInsightsSummary(netSentimentChange,avgPosition: curRates.avgPosition,avgPositionChange,+ mentioningResults: Number(cur.mentioning_results ?? 0),+ positionedResults: Number(cur.position_count ?? 0),};}@@ -3402,7 +3413,10 @@ export async function getInsightsBreakdown(brandId: string,metric: BreakdownMetric,opts?: BreakdownFilters,+ /** The UI's locale, for the numbers in the root-cause sentence (VIS-005). */+ locale = 'en',): Promise<InsightsBreakdown> {+ const f = numberFormat(locale);const supabase = await dbClient();const windows = comparisonWindows(opts);const p_models = modelFilterArray(opts?.model);@@ -3531,13 +3545,13 @@ export async function getInsightsBreakdown(rootCause = `${metricLabel} held steady vs the previous ${windowDays}-day window.`;} else if (!topPrompt) {const dir = totalDelta > 0 ? 'rose' : 'fell';- const magnitude = formatTotalMagnitude(totalDelta, totalDeltaPct, metric);+ const magnitude = formatTotalMagnitude(totalDelta, totalDeltaPct, metric, f);rootCause = `${metricLabel} ${dir} ${magnitude} vs the previous ${windowDays}d — the change is spread evenly across prompts, no single driver.`;} else {const headline = totalDelta < 0 ? 'Biggest drop' : 'Biggest gain';- const promptClause = `"${truncate(topPrompt.label, 60)}" ${formatContribution(topPrompt, metric)}`;+ const promptClause = `"${truncate(topPrompt.label, 60)}" ${formatContribution(topPrompt, metric, f)}`;const platformClause = topPlatform- ? ` Top platform ${totalDelta < 0 ? 'drop' : 'gain'}: ${topPlatform.label} ${formatContribution(topPlatform, metric)}.`+ ? ` Top platform ${totalDelta < 0 ? 'drop' : 'gain'}: ${topPlatform.label} ${formatContribution(topPlatform, metric, f)}.`: '';rootCause = `${headline}: ${promptClause}.${platformClause}`;}@@ -3567,37 +3581,37 @@ function truncate(s: string, max: number): string {* - mentions: "lost 84 mentions (−38%)" or "gained 12 mentions"* - visibility: "dropped 2.1 pts" or "rose 2.1 pts"*/-function formatContribution(row: BreakdownRow, metric: BreakdownMetric): string {+function formatContribution(row: BreakdownRow, metric: BreakdownMetric, f: NumberFormat): string {const delta = row.delta ?? 0;const isLoss = delta < 0;const abs = Math.abs(delta);if (metric === 'visibility') {const verb = isLoss ? 'dropped' : 'rose';- const value = Math.round(abs * 10) / 10;- return `${verb} ${value} pts`;+ return `${verb} ${f.number(Math.round(abs * 10) / 10)} pts`;}const verb = isLoss ? 'lost' : 'gained';- const core = `${verb} ${abs.toLocaleString('en-US')} mentions`;+ const core = `${verb} ${f.number(abs)} mentions`;if (row.deltaPct === null) return core;const sign = row.deltaPct < 0 ? '−' : '+';- return `${core} (${sign}${Math.abs(row.deltaPct)}%)`;+ return `${core} (${sign}${f.percent(Math.abs(row.deltaPct))})`;}function formatTotalMagnitude(delta: number,deltaPct: number | null,metric: BreakdownMetric,+ f: NumberFormat,): string {const abs = Math.abs(delta);if (metric === 'visibility') {- return `${Math.round(abs * 10) / 10} pts`;+ return `${f.number(Math.round(abs * 10) / 10)} pts`;}- const core = `${abs.toLocaleString('en-US')} mentions`;+ const core = `${f.number(abs)} mentions`;if (deltaPct === null) return core;const sign = deltaPct < 0 ? '−' : '+';- return `${core} (${sign}${Math.abs(deltaPct)}%)`;+ return `${core} (${sign}${f.percent(Math.abs(deltaPct))})`;}// ─── Topic detail bundle (#312) ───────────────────────────────────────────diff --git a/web/src/lib/insights-breakdown.test.ts b/web/src/lib/insights-breakdown.test.tsindex 86ea93a92..fb8881028 100644--- a/web/src/lib/insights-breakdown.test.ts+++ b/web/src/lib/insights-breakdown.test.ts@@ -124,15 +124,15 @@ describe('buildBreakdownRows', () => {});describe('pickDriver', () => {- const row = (id: string, delta: number | null): BreakdownRow => ({+ const row = (id: string, delta: number | null, runs = { prev: 5, cur: 5 }): BreakdownRow => ({id,label: id,cur: 0,prev: delta === null ? null : 0,delta,deltaPct: null,- curRuns: 0,- prevRuns: 0,+ curRuns: runs.cur,+ prevRuns: runs.prev,});it('picks the biggest drop when the total fell, and the biggest gain when it rose', () => {@@ -147,6 +147,13 @@ describe('pickDriver', () => {expect(pickDriver([row('a', 5)], 0)).toBeNull();expect(pickDriver([row('a', null)], null)).toBeNull();});++ it('credits no row answered in only one window (VIS-005)', () => {+ // A prompt added this period "rising" from no answers isn't a gain.+ const rows = [row('new', 80, { prev: 0, cur: 4 }), row('gone', -60, { prev: 3, cur: 0 })];+ expect(pickDriver([...rows, row('kept', 2)], 1)?.id).toBe('kept');+ expect(pickDriver(rows, -1)).toBeNull();+ });});describe('parseBreakdownGroups', () => {diff --git a/web/src/lib/insights-breakdown.ts b/web/src/lib/insights-breakdown.tsindex 581d74356..7b223a10f 100644--- a/web/src/lib/insights-breakdown.ts+++ b/web/src/lib/insights-breakdown.ts@@ -277,13 +277,15 @@ export function buildBreakdownRows(/*** The row that did the most in the direction of the overall change: the* biggest drop when the total fell, the biggest gain when it rose. Null when- * nothing moved that way, or when there is no previous window.+ * nothing moved that way, or when there is no previous window. A row+ * answered in only one window has no change to credit: a new prompt didn't+ * "rise 80 pts" from nothing (VIS-005).*/export function pickDriver(rows: BreakdownRow[], totalDelta: number | null): BreakdownRow | null {if (totalDelta === null || totalDelta === 0) return null;let best: BreakdownRow | null = null;for (const r of rows) {- if (r.delta === null) continue;+ if (r.delta === null || r.prevRuns === 0 || r.curRuns === 0) continue;if (totalDelta < 0 ? r.delta < (best?.delta ?? 0) : r.delta > (best?.delta ?? 0)) best = r;}return best;diff --git a/web/src/lib/insights-drivers.test.ts b/web/src/lib/insights-drivers.test.tsindex a4bd4020a..45aa2a9e0 100644--- a/web/src/lib/insights-drivers.test.ts+++ b/web/src/lib/insights-drivers.test.ts@@ -96,6 +96,8 @@ describe('whyChanged', () => {name: 'ChatGPT',prev: Math.round(score(100, 30) * 10) / 10,cur: Math.round(score(100, 60) * 10) / 10,+ // Each score's sample size, for a Low sample mark on the row (VIS-005).+ answers: { prev: 100, cur: 100 },impact: change,},]);diff --git a/web/src/lib/insights-drivers.ts b/web/src/lib/insights-drivers.tsindex 86f2398d0..7326d0d9e 100644--- a/web/src/lib/insights-drivers.ts+++ b/web/src/lib/insights-drivers.ts@@ -84,6 +84,8 @@ export interface Driver {/** The slice's own Visibility in each window, as the breakdown panel scores it. */prev: number;cur: number;+ /** The slice's answers in each window: its scores' sample sizes (VIS-005). */+ answers: { prev: number; cur: number };/** Points the overall score moved because of this slice. */impact: number;}@@ -191,6 +193,7 @@ export function whyChanged(name: s.name,prev: round1(score(s.prev)),cur: round1(score(s.cur)),+ answers: { prev: s.prev.answers, cur: s.cur.answers },impact,});}diff --git a/web/src/lib/insights-opportunities.test.ts b/web/src/lib/insights-opportunities.test.tsindex 5f8d91874..24a0f13ce 100644--- a/web/src/lib/insights-opportunities.test.ts+++ b/web/src/lib/insights-opportunities.test.ts@@ -136,6 +136,11 @@ describe('opportunities', () => {});});+ it('has no volume when no suggestion has an estimate, never 0 (VIS-005)', () => {+ const result = opportunities([suggestion('a', { estVolume: null })], unknown);+ expect(result.status === 'ready' && result.items[0].volume).toBeNull();+ });+it('groups by topic name when a suggestion has no topic id', () => {const result = opportunities([suggestion('a', { topicName: 'GEO tools' }), suggestion('b', { topicName: 'geo tools ' })],diff --git a/web/src/lib/insights-opportunities.ts b/web/src/lib/insights-opportunities.tsindex 3924071b8..ce61ebada 100644--- a/web/src/lib/insights-opportunities.ts+++ b/web/src/lib/insights-opportunities.ts@@ -40,8 +40,11 @@ export interface Opportunity {topicId: string | null;/** What Track adds, highest volume first. */suggestionIds: string[];- /** Monthly AI search volume: the prompt's, or the sum of the topic's. */- volume: number;+ /**+ * Monthly AI search volume: the prompt's, or the sum of the topic's; null+ * when none of them has an estimate (shown as nothing, never "~0/mo").+ */+ volume: number | null;standing: OpportunityStanding;}@@ -125,7 +128,9 @@ export function opportunities(const topicId = sorted[0].topicId;const isTopic = sorted.length > 1;const standing = standingOf(topicId);- const volume = sorted.reduce((sum, s) => sum + (s.estVolume ?? 0), 0);+ const estimated = sorted.filter((s) => s.estVolume !== null);+ const volume =+ estimated.length > 0 ? estimated.reduce((sum, s) => sum + s.estVolume!, 0) : null;const relevance = sorted.reduce((sum, s) => sum + s.relevance!, 0) / sorted.length;const item: Opportunity = {kind: isTopic ? 'topic' : 'prompt',@@ -136,7 +141,7 @@ export function opportunities(volume,standing,};- return { item, relevance, rank: relevance * volume * gapWeight(standing) };+ return { item, relevance, rank: relevance * (volume ?? 0) * gapWeight(standing) };});ranked.sort(diff --git a/web/src/lib/insights-summary.ts b/web/src/lib/insights-summary.tsindex 7a937a6b0..0679af466 100644--- a/web/src/lib/insights-summary.ts+++ b/web/src/lib/insights-summary.ts@@ -270,10 +270,25 @@ export interface PlatformTableRow {* window read "No runs this period", never 0%. Sorted by Visibility, then the* low-sample ones, then the ones without runs.*/+/** A platform's share of voice; null when no brand at all was named there (0 of 0 isn't 0%). */+function shareOf(+ p: { sov: number; brandMentions?: number; competitorMentions?: number } | undefined,+): number | null {+ if (!p) return null;+ const named = (p.brandMentions ?? 0) + (p.competitorMentions ?? 0);+ return p.brandMentions === undefined || named > 0 ? p.sov : null;+}+export function platformTable(rows: PlatformRow[],changes: PlatformChange[],- shareOfVoice: { provider: string; sov: number }[],+ /** With the mention counts behind each share, when known: no mentions at all is no share (VIS-005). */+ shareOfVoice: {+ provider: string;+ sov: number;+ brandMentions?: number;+ competitorMentions?: number;+ }[],platformOf: (modelUsed: string | null, platform: string | null) => string,): PlatformTableRow[] {const cur = new Map<@@ -319,7 +334,7 @@ export function platformTable(visibility: ok ? score(s) : null,change: ok ? (changes.find((c) => c.name === name)?.change ?? null) : null,coverage: ok ? coverage(s.visible.size, s.active.size) : null,- shareOfVoice: ok ? (shareOfVoice.find((p) => p.provider === name)?.sov ?? null) : null,+ shareOfVoice: ok ? shareOf(shareOfVoice.find((p) => p.provider === name)) : null,avgPosition: ok && s.positions > 0 ? round1(s.sumPosition / s.positions) : null,worst: false,};diff --git a/web/src/lib/number-format.test.ts b/web/src/lib/number-format.test.tsnew file mode 100644index 000000000..6f24dc0c9--- /dev/null+++ b/web/src/lib/number-format.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from 'vitest';+import { numberFormat } from './number-format';++describe('numberFormat', () => {+ const en = numberFormat('en');+ const tr = numberFormat('tr');++ it('writes numbers in the locale, with fixed decimals when asked', () => {+ expect(en.number(1234.5)).toBe('1,234.5');+ expect(tr.number(1234.5)).toBe('1.234,5');+ expect(en.number(48, 1)).toBe('48.0');+ expect(en.number(17.4)).toBe('17.4');+ });++ it('places the percent sign as the locale does', () => {+ expect(en.percent(64.3)).toBe('64.3%');+ expect(tr.percent(64.3)).toBe('%64,3');+ expect(en.percent(38)).toBe('38%');+ });++ it('shortens large counts', () => {+ expect(en.compact(39_900)).toBe('39.9K');+ expect(en.compact(1_200_000)).toBe('1.2M');+ expect(en.compact(940)).toBe('940');+ });++ it('signs changes with a true minus and ±0', () => {+ expect(en.signed(1.5)).toBe('+1.5');+ expect(en.signed(-3.2)).toBe('−3.2');+ expect(en.signed(0)).toBe('±0');+ expect(tr.signed(-1234.5)).toBe('−1.234,5');+ });+});diff --git a/web/src/lib/number-format.ts b/web/src/lib/number-format.tsnew file mode 100644index 000000000..fd2167583--- /dev/null+++ b/web/src/lib/number-format.ts@@ -0,0 +1,51 @@+/**+ * Numbers in the UI's locale (Visibility spec v2, VIS-005: "Every number uses+ * the UI's locale format"). next-intl leaves a plain `{n}` message argument as+ * String(n), so numbers are formatted here before they go into a message.+ * A sign is written with the true minus (−) the Insights cards use, whatever+ * the locale's own hyphen.+ */++export interface NumberFormat {+ /** 1,234 or 17.4; with `digits`, always that many decimals ("48.0"). */+ number(n: number, digits?: number): string;+ /** A 0–100 value as a percent: "64.3%" in English, "%64,3" in Turkish. */+ percent(n: number, digits?: number): string;+ /** A large count, shortened: "39.9K", "1.2M". */+ compact(n: number): string;+ /** A change with its sign: "+1.5", "−3.2", "±0". */+ signed(n: number, digits?: number): string;+}++const MINUS = '−';+const formatters = new Map<string, Intl.NumberFormat>();++function formatter(locale: string, options: Intl.NumberFormatOptions): Intl.NumberFormat {+ const key = `${locale}|${JSON.stringify(options)}`;+ let f = formatters.get(key);+ if (!f) {+ f = new Intl.NumberFormat(locale, options);+ formatters.set(key, f);+ }+ return f;+}++/** Decimals: exactly `digits` when given, else as many as the value has (up to 3). */+const decimals = (digits?: number): Intl.NumberFormatOptions =>+ digits === undefined+ ? { maximumFractionDigits: 3 }+ : { minimumFractionDigits: digits, maximumFractionDigits: digits };++export function numberFormat(locale: string): NumberFormat {+ const number = (n: number, digits?: number) => formatter(locale, decimals(digits)).format(n);+ return {+ number,+ percent: (n, digits) =>+ formatter(locale, { style: 'percent', ...decimals(digits) }).format(n / 100),+ compact: (n) => formatter(locale, { notation: 'compact', maximumFractionDigits: 1 }).format(n),+ signed: (n, digits) => {+ if (n === 0) return '±0';+ return `${n > 0 ? '+' : MINUS}${number(Math.abs(n), digits)}`;+ },+ };+}