Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(shopping): sidebar entry + Shopping overview page (#144)
Gökhan Geyikfbe52e2bcf0a
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 14592a82a..0eed2aa19 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -25,6 +25,7 @@"content": "Content Optimization","competitors": "Competitors","citations": "Citations",+ "shopping": "Shopping","reports": "Reports","settings": "Settings"},@@ -271,6 +272,29 @@"noBrandTitle": "No brand selected","noBrandDescription": "Select or create a brand to see the citations AI platforms use when answering about it."},+ "shopping": {+ "title": "Shopping",+ "description": "Product cards AI engines surface — your products versus the competitive set.",+ "kpiCardRate": "Shopping card rate",+ "kpiCardRateSub": "Tracked prompts that returned ≥1 card",+ "kpiOwnProducts": "Your products surfaced",+ "kpiOwnProductsSub": "Cards matched to your brand",+ "kpiSov": "Shopping share of voice",+ "kpiSovSub": "Your cards ÷ all cards in card-bearing prompts",+ "kpiTopMerchant": "Top merchant for your products",+ "kpiTopMerchantSub": "Most frequent merchant domain",+ "platformBreakdownTitle": "Card rate by platform",+ "trendTitle": "Your shopping presence — last 30 days",+ "filterRegion": "Region",+ "filterPlatform": "Platform",+ "filterDateRange": "Date range",+ "noBrandTitle": "No brand selected",+ "noBrandDescription": "Select or create a brand to see shopping card analytics for it.",+ "emptyTitle": "No shopping cards yet",+ "emptyDescription": "Perplexity, Google AI Mode, and Microsoft Copilot return shopping cards on commercial-intent prompts (\"best running shoes for marathon training\"). Once tracking runs against a card-eligible prompt, results show up here.",+ "lockedTitle": "Upgrade for full shopping analytics",+ "lockedDescription": "Free and Starter plans see the shopping card rate. Growth unlocks the My Products tab, competitor breakdown, card-eligible prompts, and merchant analytics."+ },"reports": {"title": "Reports","description": "Export and share your AI visibility reports.",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsxnew file mode 100644index 000000000..790de2361--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx@@ -0,0 +1,571 @@+'use client';++import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useTranslations } from 'next-intl';+import {+ Bar,+ BarChart,+ CartesianGrid,+ Legend,+ Line,+ LineChart,+ Tooltip,+ XAxis,+ YAxis,+} from 'recharts';+import { ShoppingBag, Store, ArrowUpRight, Crown, Lock } from 'lucide-react';+import { useBrandStore } from '@/stores/use-brand-store';+import { useFeatureGate } from '@/hooks/use-feature-gate';+import {+ getShoppingChartData,+ getShoppingFilterOptions,+ getShoppingKpis,+ type ShoppingChartData,+ type ShoppingDatePreset,+ type ShoppingFilters,+ type ShoppingKpis,+} from '@/lib/actions/shopping';+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';+import { Skeleton } from '@/components/ui/skeleton';+import { Badge } from '@/components/ui/badge';+import { Link } from '@/i18n/navigation';+import { buttonVariants } from '@/components/ui/button';++const DATE_PRESETS: ShoppingDatePreset[] = ['7d', '30d', '90d', 'all'];++// Theme tokens in globals.css ship as full oklch values; reference them+// directly with var(--…). Wrapping in hsl() yields invalid CSS, so chart+// text turns black on dark mode (lesson learned from #138).+const AXIS_TICK = { fill: 'var(--muted-foreground)', fontSize: 11 } as const;+const TOOLTIP_STYLE = {+ background: 'var(--card)',+ border: '1px solid var(--border)',+ borderRadius: '0.5rem',+ fontSize: '0.75rem',+ color: 'var(--foreground)',+} as const;++export default function ShoppingPage() {+ const t = useTranslations('shopping');+ const { activeBrandId } = useBrandStore();+ const { canUse, requiredPlanFor } = useFeatureGate();+ const hasFullAccess = canUse('shopping_analytics');++ const [datePreset, setDatePreset] = useState<ShoppingDatePreset>('30d');+ const [platform, setPlatform] = useState<string>('all');+ const [region, setRegion] = useState<string>('all');++ const [filterOpts, setFilterOpts] = useState<{ platforms: string[]; regions: string[] }>({+ platforms: [],+ regions: [],+ });+ const [kpis, setKpis] = useState<ShoppingKpis | null>(null);+ const [charts, setCharts] = useState<ShoppingChartData | null>(null);+ const [loading, setLoading] = useState(false);++ const filters = useMemo<ShoppingFilters>(+ () => ({+ datePreset,+ platforms: platform === 'all' ? undefined : [platform],+ regions: region === 'all' ? undefined : [region],+ }),+ [datePreset, platform, region],+ );++ // Load filter options once per brand so the dropdowns only show+ // platform / region values that actually appear in this brand's data.+ useEffect(() => {+ if (!activeBrandId) return;+ let cancelled = false;+ (async () => {+ try {+ const opts = await getShoppingFilterOptions(activeBrandId);+ if (!cancelled) setFilterOpts(opts);+ } catch {+ if (!cancelled) setFilterOpts({ platforms: [], regions: [] });+ }+ })();+ return () => {+ cancelled = true;+ };+ }, [activeBrandId]);++ // De-dupe overlapping fetches when filters change in quick succession.+ const reqIdRef = useRef(0);+ const loadData = useCallback(async () => {+ if (!activeBrandId) return;+ const reqId = ++reqIdRef.current;+ setLoading(true);+ try {+ const [k, c] = await Promise.all([+ getShoppingKpis(activeBrandId, filters),+ getShoppingChartData(activeBrandId, filters),+ ]);+ if (reqId === reqIdRef.current) {+ setKpis(k);+ setCharts(c);+ }+ } finally {+ if (reqId === reqIdRef.current) setLoading(false);+ }+ }, [activeBrandId, filters]);++ useEffect(() => {+ void loadData();+ }, [loadData]);++ if (!activeBrandId) {+ return (+ <div className="space-y-6">+ <PageHeader t={t} />+ <EmptyState title={t('noBrandTitle')} description={t('noBrandDescription')} />+ </div>+ );+ }++ const totalCards =+ (charts?.ownPresenceTrend ?? []).reduce((sum, p) => sum + p.totalCards, 0) ++ // platformCardRate's data has card-rate built in, so the trend total is+ // sufficient as a "do we have any data at all?" check.+ 0;+ const isEmpty = !loading && (kpis?.shoppingCardRateSampleSize ?? 0) === 0 && totalCards === 0;++ return (+ <div className="space-y-6">+ <PageHeader t={t} />++ <FilterBar+ t={t}+ datePreset={datePreset}+ setDatePreset={setDatePreset}+ platform={platform}+ setPlatform={setPlatform}+ region={region}+ setRegion={setRegion}+ platformOpts={filterOpts.platforms}+ regionOpts={filterOpts.regions}+ />++ {isEmpty ? (+ <EmptyState title={t('emptyTitle')} description={t('emptyDescription')} />+ ) : (+ <>+ <KpiGrid t={t} kpis={kpis} loading={loading} hasFullAccess={hasFullAccess} />++ {hasFullAccess ? (+ <div className="grid gap-4 lg:grid-cols-2">+ <PlatformCardRateChart+ t={t}+ data={charts?.platformCardRate ?? []}+ loading={loading}+ />+ <OwnPresenceTrendChart+ t={t}+ data={charts?.ownPresenceTrend ?? []}+ loading={loading}+ />+ </div>+ ) : (+ <UpgradeCard t={t} requiredPlan={requiredPlanFor('shopping_analytics')} />+ )}+ </>+ )}+ </div>+ );+}++// ── Header ────────────────────────────────────────────────────────────────────++function PageHeader({ t }: { t: ReturnType<typeof useTranslations<'shopping'>> }) {+ return (+ <div>+ <h1 className="flex items-center gap-2 text-2xl font-bold tracking-tight">+ <ShoppingBag className="h-6 w-6 text-primary" />+ {t('title')}+ </h1>+ <p className="mt-1 text-sm text-muted-foreground">{t('description')}</p>+ </div>+ );+}++// ── Filter bar ────────────────────────────────────────────────────────────────++function FilterBar({+ t,+ datePreset,+ setDatePreset,+ platform,+ setPlatform,+ region,+ setRegion,+ platformOpts,+ regionOpts,+}: {+ t: ReturnType<typeof useTranslations<'shopping'>>;+ datePreset: ShoppingDatePreset;+ setDatePreset: (v: ShoppingDatePreset) => void;+ platform: string;+ setPlatform: (v: string) => void;+ region: string;+ setRegion: (v: string) => void;+ platformOpts: string[];+ regionOpts: string[];+}) {+ return (+ <div className="flex flex-wrap items-center gap-3 rounded-lg border bg-card p-3 text-sm">+ <FilterField label={t('filterDateRange')}>+ <Select value={datePreset} onValueChange={(v) => setDatePreset(v as ShoppingDatePreset)}>+ <SelectTrigger className="h-8 w-32">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {DATE_PRESETS.map((p) => (+ <SelectItem key={p} value={p}>+ {p === 'all' ? 'All time' : `Last ${p}`}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </FilterField>++ <FilterField label={t('filterPlatform')}>+ <Select value={platform} onValueChange={(v) => setPlatform(v ?? 'all')}>+ <SelectTrigger className="h-8 w-40">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="all">All platforms</SelectItem>+ {platformOpts.map((p) => (+ <SelectItem key={p} value={p}>+ {p}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </FilterField>++ <FilterField label={t('filterRegion')}>+ <Select value={region} onValueChange={(v) => setRegion(v ?? 'all')}>+ <SelectTrigger className="h-8 w-32">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="all">All regions</SelectItem>+ {regionOpts.map((r) => (+ <SelectItem key={r} value={r}>+ {r}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </FilterField>+ </div>+ );+}++function FilterField({ label, children }: { label: string; children: React.ReactNode }) {+ return (+ <label className="flex items-center gap-2">+ <span className="text-xs font-medium text-muted-foreground">{label}</span>+ {children}+ </label>+ );+}++// ── KPI grid ──────────────────────────────────────────────────────────────────++function KpiGrid({+ t,+ kpis,+ loading,+ hasFullAccess,+}: {+ t: ReturnType<typeof useTranslations<'shopping'>>;+ kpis: ShoppingKpis | null;+ loading: boolean;+ hasFullAccess: boolean;+}) {+ if (loading && !kpis) {+ return (+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">+ {Array.from({ length: 4 }).map((_, i) => (+ <Skeleton key={i} className="h-[104px]" />+ ))}+ </div>+ );+ }++ const cardRate = kpis?.shoppingCardRate ?? 0;+ const productsSurfaced = kpis?.productsSurfaced ?? 0;+ const sov = kpis?.shoppingSov ?? 0;+ const merchant = kpis?.topMerchant;++ return (+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">+ <KpiCard+ title={t('kpiCardRate')}+ value={formatPercent(cardRate)}+ subtitle={t('kpiCardRateSub')}+ icon={ShoppingBag}+ />+ <KpiCard+ title={t('kpiOwnProducts')}+ value={productsSurfaced.toLocaleString()}+ subtitle={t('kpiOwnProductsSub')}+ icon={ArrowUpRight}+ locked={!hasFullAccess}+ />+ <KpiCard+ title={t('kpiSov')}+ value={formatPercent(sov)}+ subtitle={t('kpiSovSub')}+ icon={Crown}+ locked={!hasFullAccess}+ />+ <KpiCard+ title={t('kpiTopMerchant')}+ value={merchant?.domain ?? '—'}+ subtitle={+ merchant+ ? `${merchant.cardCount} card${merchant.cardCount === 1 ? '' : 's'}`+ : t('kpiTopMerchantSub')+ }+ icon={Store}+ locked={!hasFullAccess}+ />+ </div>+ );+}++function KpiCard({+ title,+ value,+ subtitle,+ icon: Icon,+ locked = false,+}: {+ title: string;+ value: string;+ subtitle: string;+ icon: React.ComponentType<{ className?: string }>;+ locked?: boolean;+}) {+ return (+ <Card className={locked ? 'opacity-70' : ''}>+ <CardContent className="space-y-2 p-4">+ <div className="flex items-start justify-between">+ <span className="text-xs font-medium text-muted-foreground">{title}</span>+ {locked ? (+ <Lock className="h-4 w-4 text-muted-foreground/60" />+ ) : (+ <Icon className="h-4 w-4 text-muted-foreground" />+ )}+ </div>+ <p className="truncate text-2xl font-bold">{locked ? '—' : value}</p>+ <p className="text-xs text-muted-foreground">{subtitle}</p>+ </CardContent>+ </Card>+ );+}++// ── Charts ────────────────────────────────────────────────────────────────────++function PlatformCardRateChart({+ t,+ data,+ loading,+}: {+ t: ReturnType<typeof useTranslations<'shopping'>>;+ data: Array<{ platform: string; cardRate: number; totalResults: number }>;+ loading: boolean;+}) {+ const chartData = data.map((d) => ({ platform: d.platform, rate: Math.round(d.cardRate * 100) }));+ return (+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium">{t('platformBreakdownTitle')}</CardTitle>+ </CardHeader>+ <CardContent>+ {loading ? (+ <Skeleton className="h-[220px] w-full" />+ ) : (+ <ResponsiveBarChart data={chartData} />+ )}+ </CardContent>+ </Card>+ );+}++function ResponsiveBarChart({ data }: { data: Array<{ platform: string; rate: number }> }) {+ const ref = useRef<HTMLDivElement>(null);+ const [width, setWidth] = useState(0);+ useEffect(() => {+ const el = ref.current;+ if (!el) return;+ const update = () => setWidth(el.clientWidth);+ update();+ const ro = new ResizeObserver(update);+ ro.observe(el);+ return () => ro.disconnect();+ }, []);+ return (+ <div ref={ref} style={{ width: '100%', height: 220 }}>+ {width > 0 && (+ <BarChart+ width={width}+ height={220}+ data={data}+ margin={{ top: 8, right: 8, bottom: 0, left: -8 }}+ >+ <CartesianGrid stroke="var(--border)" strokeDasharray="3 3" vertical={false} />+ <XAxis dataKey="platform" stroke="var(--border)" tick={AXIS_TICK} tickLine={false} />+ <YAxis+ stroke="var(--border)"+ tick={AXIS_TICK}+ tickLine={false}+ axisLine={false}+ unit="%"+ />+ <Tooltip contentStyle={TOOLTIP_STYLE} cursor={{ fill: 'var(--muted)', opacity: 0.3 }} />+ <Bar dataKey="rate" name="Card rate" fill="var(--chart-2)" radius={[4, 4, 0, 0]} />+ </BarChart>+ )}+ </div>+ );+}++function OwnPresenceTrendChart({+ t,+ data,+ loading,+}: {+ t: ReturnType<typeof useTranslations<'shopping'>>;+ data: Array<{ date: string; ownCards: number; totalCards: number }>;+ loading: boolean;+}) {+ return (+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium">{t('trendTitle')}</CardTitle>+ </CardHeader>+ <CardContent>+ {loading ? <Skeleton className="h-[220px] w-full" /> : <ResponsiveLineChart data={data} />}+ </CardContent>+ </Card>+ );+}++function ResponsiveLineChart({+ data,+}: {+ data: Array<{ date: string; ownCards: number; totalCards: number }>;+}) {+ const ref = useRef<HTMLDivElement>(null);+ const [width, setWidth] = useState(0);+ useEffect(() => {+ const el = ref.current;+ if (!el) return;+ const update = () => setWidth(el.clientWidth);+ update();+ const ro = new ResizeObserver(update);+ ro.observe(el);+ return () => ro.disconnect();+ }, []);+ return (+ <div ref={ref} style={{ width: '100%', height: 220 }}>+ {width > 0 && (+ <LineChart+ width={width}+ height={220}+ data={data}+ margin={{ top: 8, right: 8, bottom: 0, left: -8 }}+ >+ <CartesianGrid stroke="var(--border)" strokeDasharray="3 3" vertical={false} />+ <XAxis+ dataKey="date"+ stroke="var(--border)"+ tick={AXIS_TICK}+ tickLine={false}+ tickFormatter={(v: string) => v.slice(5)}+ />+ <YAxis stroke="var(--border)" tick={AXIS_TICK} tickLine={false} axisLine={false} />+ <Tooltip contentStyle={TOOLTIP_STYLE} cursor={{ stroke: 'var(--border)' }} />+ <Legend wrapperStyle={{ fontSize: 11, color: 'var(--muted-foreground)' }} />+ <Line+ type="monotone"+ dataKey="ownCards"+ name="Your cards"+ stroke="var(--chart-2)"+ strokeWidth={2}+ dot={{ r: 2 }}+ />+ <Line+ type="monotone"+ dataKey="totalCards"+ name="All cards"+ stroke="var(--chart-4)"+ strokeWidth={2}+ dot={{ r: 2 }}+ />+ </LineChart>+ )}+ </div>+ );+}++// ── States ────────────────────────────────────────────────────────────────────++function EmptyState({ title, description }: { title: string; description: string }) {+ return (+ <div className="rounded-xl border border-dashed py-12 text-center">+ <ShoppingBag className="mx-auto h-10 w-10 text-muted-foreground/40" />+ <h3 className="mt-3 text-sm font-medium">{title}</h3>+ <p className="mx-auto mt-1 max-w-md text-sm text-muted-foreground">{description}</p>+ </div>+ );+}++function UpgradeCard({+ t,+ requiredPlan,+}: {+ t: ReturnType<typeof useTranslations<'shopping'>>;+ requiredPlan: string;+}) {+ return (+ <Card>+ <CardContent className="flex flex-col items-start gap-4 p-6 sm:flex-row sm:items-center sm:justify-between">+ <div className="flex items-start gap-3">+ <Crown className="mt-1 h-5 w-5 text-amber-500" />+ <div>+ <p className="font-medium">{t('lockedTitle')}</p>+ <p className="mt-1 text-sm text-muted-foreground">{t('lockedDescription')}</p>+ </div>+ </div>+ <Link+ href="/dashboard/settings?tab=billing"+ className={buttonVariants({ variant: 'default' })}+ >+ <Badge variant="secondary" className="mr-2 gap-1">+ <Crown className="h-3 w-3" />+ {requiredPlan}+ </Badge>+ Upgrade+ </Link>+ </CardContent>+ </Card>+ );+}++function formatPercent(value: number): string {+ if (!Number.isFinite(value) || value === 0) return '0%';+ if (value < 0.01) return '<1%';+ return `${Math.round(value * 100)}%`;+}diff --git a/web/src/components/layout/sidebar.tsx b/web/src/components/layout/sidebar.tsxindex 592f57872..c74d2dc67 100644--- a/web/src/components/layout/sidebar.tsx+++ b/web/src/components/layout/sidebar.tsx@@ -48,6 +48,7 @@ export function Sidebar() {'Content Optimization': () => t('content'),Competitors: () => t('competitors'),Citations: () => t('citations'),+ Shopping: () => t('shopping'),Reports: () => t('reports'),Settings: () => t('settings'),};diff --git a/web/src/config/dashboard.ts b/web/src/config/dashboard.tsindex 87c0759df..42eb994af 100644--- a/web/src/config/dashboard.ts+++ b/web/src/config/dashboard.ts@@ -6,6 +6,7 @@ import {LineChart,Quote,Settings,+ ShoppingBag,Sparkles,Tag,Users,@@ -66,6 +67,12 @@ export const dashboardNav: NavGroup[] = [href: '/dashboard/citations',icon: Quote,},+ {+ title: 'Shopping',+ href: '/dashboard/shopping',+ icon: ShoppingBag,+ requiredFeature: 'shopping_analytics',+ },{title: 'AI Traffic Analytics',href: '/dashboard/traffic',diff --git a/web/src/config/plans.ts b/web/src/config/plans.tsindex a1f79bdda..a6295407a 100644--- a/web/src/config/plans.ts+++ b/web/src/config/plans.ts@@ -15,6 +15,11 @@ export const FEATURES = [// cloud by plan; self-host gets it unconditionally because the// underlying tool calls run against the user's own infrastructure.'ai_agent',+ // Shopping analytics — the Shopping dashboard page (cards from+ // Perplexity / AI Mode / Copilot, your products vs competitors,+ // merchant breakdown). Free / Starter get the headline KPI only;+ // Growth+ and self-host get the full set of tabs.+ 'shopping_analytics',] as const;export type Feature = (typeof FEATURES)[number];@@ -76,6 +81,7 @@ export const PLANS: Record<PlanId, Plan> = {'custom_reports','api_access','ai_agent',+ 'shopping_analytics',],// Self-host runs against the operator's own infrastructure / API// keys — no platform quota to enforce.@@ -141,6 +147,7 @@ export const PLANS: Record<PlanId, Plan> = {'custom_reports','api_access','ai_agent',+ 'shopping_analytics',],},},@@ -171,6 +178,7 @@ export const PLANS: Record<PlanId, Plan> = {'white_label','sso_saml','ai_agent',+ 'shopping_analytics',],// Enterprise — no platform quota; usage governed by contract.},diff --git a/web/src/lib/actions/shopping.ts b/web/src/lib/actions/shopping.tsnew file mode 100644index 000000000..0594d3294--- /dev/null+++ b/web/src/lib/actions/shopping.ts@@ -0,0 +1,297 @@+'use server';++import { createClient } from '@/lib/supabase/server';+import { expandDateToEndOfDay } from '@/lib/dates';++/**+ * Server actions for the Shopping dashboard page. Reads from the+ * normalized `prompt_result_shopping_cards` table introduced in #103.+ *+ * Org-scoping is enforced via the calling user's auth session — every+ * query joins or filters on `brand_id`, and RLS on+ * `prompt_result_shopping_cards` already restricts to the caller's+ * organization. The action just adds the matching brand filter to keep+ * results scoped to a single brand at a time.+ */++export type ShoppingDatePreset = '7d' | '30d' | '90d' | 'all';++export interface ShoppingFilters {+ datePreset: ShoppingDatePreset;+ /** ISO date strings; only used when datePreset === 'all' wants override. */+ dateFrom?: string;+ dateTo?: string;+ /** Scraper / platform ids, e.g. `['perplexity-web', 'google-aimode']`. */+ platforms?: string[];+ /** Region codes. */+ regions?: string[];+}++export interface ShoppingKpis {+ shoppingCardRate: number;+ shoppingCardRateSampleSize: number;+ productsSurfaced: number;+ shoppingSov: number;+ topMerchant: { domain: string; cardCount: number } | null;+}++export interface PlatformCardRatePoint {+ platform: string;+ cardRate: number;+ totalResults: number;+}++export interface OwnPresenceTrendPoint {+ date: string;+ ownCards: number;+ totalCards: number;+}++export interface ShoppingChartData {+ platformCardRate: PlatformCardRatePoint[];+ ownPresenceTrend: OwnPresenceTrendPoint[];+}++// ── Date helpers ──────────────────────────────────────────────────────────────++function resolveDateRange(filters: ShoppingFilters): {+ from: string | undefined;+ to: string | undefined;+} {+ const now = new Date();+ if (filters.datePreset === 'all') {+ return { from: filters.dateFrom, to: filters.dateTo };+ }+ const days = filters.datePreset === '7d' ? 7 : filters.datePreset === '30d' ? 30 : 90;+ const from = new Date(now.getTime() - days * 24 * 60 * 60 * 1000);+ return { from: from.toISOString(), to: undefined };+}++function daysAgoIso(days: number): string {+ return new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();+}++// ── KPI query ─────────────────────────────────────────────────────────────────++/**+ * Build the four overview KPIs in a single round-trip per metric.+ *+ * `shoppingCardRate` is the only KPI that needs to know about prompts+ * that returned *zero* cards, so it queries `prompt_results` directly to+ * get the denominator. Everything else aggregates over the normalized+ * `prompt_result_shopping_cards` table.+ */+export async function getShoppingKpis(+ brandId: string,+ filters: ShoppingFilters,+): Promise<ShoppingKpis> {+ const supabase = await createClient();+ const { from, to } = resolveDateRange(filters);+ const expandedTo = expandDateToEndOfDay(to);++ // ── 1. Shopping card rate ──+ // numerator = prompt_results with at least one card+ // denominator = prompt_results in the window+ // Both queries hit only `prompt_results.id` so they stay cheap.+ let totalQuery = supabase+ .from('prompt_results')+ .select('id', { count: 'exact', head: true })+ .eq('brand_id', brandId);+ if (from) totalQuery = totalQuery.gte('created_at', from);+ if (expandedTo) totalQuery = totalQuery.lte('created_at', expandedTo);+ if (filters.platforms?.length) totalQuery = totalQuery.in('platform', filters.platforms);+ if (filters.regions?.length) totalQuery = totalQuery.in('region', filters.regions);++ let cardBearingQuery = supabase+ .from('prompt_results')+ .select('id', { count: 'exact', head: true })+ .eq('brand_id', brandId)+ .not('shopping_cards', 'is', null)+ .filter('shopping_cards', 'neq', '[]');+ if (from) cardBearingQuery = cardBearingQuery.gte('created_at', from);+ if (expandedTo) cardBearingQuery = cardBearingQuery.lte('created_at', expandedTo);+ if (filters.platforms?.length)+ cardBearingQuery = cardBearingQuery.in('platform', filters.platforms);+ if (filters.regions?.length) cardBearingQuery = cardBearingQuery.in('region', filters.regions);++ // ── 2-3. Cards by role for products surfaced + SoV ──+ let cardsQuery = supabase+ .from('prompt_result_shopping_cards')+ .select('matched_brand_role, merchant_domain', { count: 'exact' })+ .eq('brand_id', brandId);+ if (from) cardsQuery = cardsQuery.gte('created_at', from);+ if (expandedTo) cardsQuery = cardsQuery.lte('created_at', expandedTo);+ if (filters.platforms?.length) cardsQuery = cardsQuery.in('platform', filters.platforms);+ if (filters.regions?.length) cardsQuery = cardsQuery.in('region', filters.regions);++ const [+ { count: totalResults },+ { count: cardBearingResults },+ { data: cards, error: cardsError },+ ] = await Promise.all([totalQuery, cardBearingQuery, cardsQuery]);++ if (cardsError) throw new Error(cardsError.message);++ const shoppingCardRate =+ totalResults && totalResults > 0 ? (cardBearingResults ?? 0) / totalResults : 0;++ const rows = (cards ?? []) as Array<{+ matched_brand_role: 'own' | 'competitor' | 'other';+ merchant_domain: string | null;+ }>;++ let ownCount = 0;+ const merchantTotals = new Map<string, number>();+ for (const row of rows) {+ if (row.matched_brand_role === 'own') {+ ownCount += 1;+ if (row.merchant_domain) {+ merchantTotals.set(row.merchant_domain, (merchantTotals.get(row.merchant_domain) ?? 0) + 1);+ }+ }+ }++ const totalCards = rows.length;+ const shoppingSov = totalCards > 0 ? ownCount / totalCards : 0;++ let topMerchant: { domain: string; cardCount: number } | null = null;+ for (const [domain, count] of merchantTotals.entries()) {+ if (!topMerchant || count > topMerchant.cardCount) {+ topMerchant = { domain, cardCount: count };+ }+ }++ return {+ shoppingCardRate,+ shoppingCardRateSampleSize: totalResults ?? 0,+ productsSurfaced: ownCount,+ shoppingSov,+ topMerchant,+ };+}++// ── Chart query ───────────────────────────────────────────────────────────────++/**+ * Two compact chart payloads for the Overview tab:+ *+ * - `platformCardRate` — bar chart, one row per platform, `cardRate` is+ * `cards-bearing prompts / total prompts on that platform`.+ * - `ownPresenceTrend` — line chart, one bucket per UTC day for the+ * last 30 days, with own + total card counts.+ */+export async function getShoppingChartData(+ brandId: string,+ filters: ShoppingFilters,+): Promise<ShoppingChartData> {+ const supabase = await createClient();+ const { from, to } = resolveDateRange(filters);+ const expandedTo = expandDateToEndOfDay(to);++ // ── Platform card rate ──+ // Pulls platform + a boolean "has cards" off prompt_results. Aggregating+ // in JS is cheap at this row count and avoids defining another RPC.+ let pageQuery = supabase+ .from('prompt_results')+ .select('platform, shopping_cards')+ .eq('brand_id', brandId);+ if (from) pageQuery = pageQuery.gte('created_at', from);+ if (expandedTo) pageQuery = pageQuery.lte('created_at', expandedTo);+ if (filters.platforms?.length) pageQuery = pageQuery.in('platform', filters.platforms);+ if (filters.regions?.length) pageQuery = pageQuery.in('region', filters.regions);++ const { data: platformRows, error: platformError } = await pageQuery;+ if (platformError) throw new Error(platformError.message);++ const perPlatform = new Map<string, { total: number; withCards: number }>();+ for (const row of (platformRows ?? []) as Array<{+ platform: string;+ shopping_cards: unknown;+ }>) {+ const slot = perPlatform.get(row.platform) ?? { total: 0, withCards: 0 };+ slot.total += 1;+ if (Array.isArray(row.shopping_cards) && row.shopping_cards.length > 0) {+ slot.withCards += 1;+ }+ perPlatform.set(row.platform, slot);+ }+ const platformCardRate: PlatformCardRatePoint[] = [...perPlatform.entries()]+ .filter(([, slot]) => slot.total > 0)+ .map(([platform, slot]) => ({+ platform,+ cardRate: slot.withCards / slot.total,+ totalResults: slot.total,+ }))+ .sort((a, b) => b.cardRate - a.cardRate);++ // ── 30-day own-presence trend ──+ // Always 30d regardless of filter so the trend chart shows a stable+ // window. Same brand + platform + region filters apply.+ const trendFrom = daysAgoIso(30);+ let trendQuery = supabase+ .from('prompt_result_shopping_cards')+ .select('matched_brand_role, created_at')+ .eq('brand_id', brandId)+ .gte('created_at', trendFrom);+ if (filters.platforms?.length) trendQuery = trendQuery.in('platform', filters.platforms);+ if (filters.regions?.length) trendQuery = trendQuery.in('region', filters.regions);++ const { data: trendRows, error: trendError } = await trendQuery;+ if (trendError) throw new Error(trendError.message);++ // Bucket by UTC day.+ const buckets = new Map<string, { ownCards: number; totalCards: number }>();+ for (const row of (trendRows ?? []) as Array<{+ matched_brand_role: 'own' | 'competitor' | 'other';+ created_at: string;+ }>) {+ const day = row.created_at.slice(0, 10);+ const slot = buckets.get(day) ?? { ownCards: 0, totalCards: 0 };+ slot.totalCards += 1;+ if (row.matched_brand_role === 'own') slot.ownCards += 1;+ buckets.set(day, slot);+ }++ // Fill in zero buckets so the line chart doesn't skip empty days.+ const ownPresenceTrend: OwnPresenceTrendPoint[] = [];+ for (let i = 29; i >= 0; i--) {+ const date = new Date(Date.now() - i * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);+ const slot = buckets.get(date) ?? { ownCards: 0, totalCards: 0 };+ ownPresenceTrend.push({+ date,+ ownCards: slot.ownCards,+ totalCards: slot.totalCards,+ });+ }++ return { platformCardRate, ownPresenceTrend };+}++/**+ * Collected once at page load so the filter bar shows only platform / region+ * values that actually appear in this brand's data.+ */+export async function getShoppingFilterOptions(brandId: string): Promise<{+ platforms: string[];+ regions: string[];+}> {+ const supabase = await createClient();+ const { data, error } = await supabase+ .from('prompt_results')+ .select('platform, region')+ .eq('brand_id', brandId)+ .not('shopping_cards', 'is', null)+ .limit(2000);+ if (error) throw new Error(error.message);++ const platforms = new Set<string>();+ const regions = new Set<string>();+ for (const row of (data ?? []) as Array<{ platform: string | null; region: string | null }>) {+ if (row.platform) platforms.add(row.platform);+ if (row.region) regions.add(row.region);+ }+ return {+ platforms: [...platforms].sort(),+ regions: [...regions].sort(),+ };+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex dc68da4f4..53340abc5 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -562,6 +562,87 @@ export type Database = {},];};+ prompt_result_shopping_cards: {+ Row: {+ brand_id: string;+ created_at: string;+ id: string;+ image_url: string | null;+ matched_brand_id: string | null;+ matched_brand_role: string;+ merchant_domain: string | null;+ merchant_url: string | null;+ platform: string;+ position: number;+ price_amount: number | null;+ price_currency: string | null;+ product_brand: string | null;+ product_title: string | null;+ prompt_result_id: string;+ rating: number | null;+ raw: Json;+ region: string | null;+ review_count: number | null;+ };+ Insert: {+ brand_id: string;+ created_at?: string;+ id?: string;+ image_url?: string | null;+ matched_brand_id?: string | null;+ matched_brand_role?: string;+ merchant_domain?: string | null;+ merchant_url?: string | null;+ platform: string;+ position: number;+ price_amount?: number | null;+ price_currency?: string | null;+ product_brand?: string | null;+ product_title?: string | null;+ prompt_result_id: string;+ rating?: number | null;+ raw: Json;+ region?: string | null;+ review_count?: number | null;+ };+ Update: {+ brand_id?: string;+ created_at?: string;+ id?: string;+ image_url?: string | null;+ matched_brand_id?: string | null;+ matched_brand_role?: string;+ merchant_domain?: string | null;+ merchant_url?: string | null;+ platform?: string;+ position?: number;+ price_amount?: number | null;+ price_currency?: string | null;+ product_brand?: string | null;+ product_title?: string | null;+ prompt_result_id?: string;+ rating?: number | null;+ raw?: Json;+ region?: string | null;+ review_count?: number | null;+ };+ Relationships: [+ {+ foreignKeyName: 'prompt_result_shopping_cards_brand_id_fkey';+ columns: ['brand_id'];+ isOneToOne: false;+ referencedRelation: 'brands';+ referencedColumns: ['id'];+ },+ {+ foreignKeyName: 'prompt_result_shopping_cards_prompt_result_id_fkey';+ columns: ['prompt_result_id'];+ isOneToOne: false;+ referencedRelation: 'prompt_results';+ referencedColumns: ['id'];+ },+ ];+ };prompt_results: {Row: {brand_id: string;