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): show the AI shelf for each shopping question, with the brand's place and its sales from AI (Product Visibility, part 3) (#1638)
Cihan93f221d72ff0
diff --git a/web/messages/en.json b/web/messages/en.jsonindex bffd78684..073d934c5 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -7948,6 +7948,44 @@"connectGa": "Connect Google Analytics","ga": "Google Analytics"},+ "shelf": {+ "label": "AI shelves",+ "kpis": {+ "share": "AI shelf share",+ "shareSub": "of product slots in AI answers",+ "products": "Products on the shelf",+ "productsOf": "{count} of {total}",+ "productsSub": "shown at least once",+ "productsTitlesSub": "shown at least once · connect your catalog to count them against it",+ "revenue": "AI revenue · 30d",+ "orders": "{count, plural, one {# order} other {# orders}} from AI visits",+ "noOrders": "No orders from AI visits yet",+ "connectSales": "Connect to see sales",+ "channel": "Top AI channel",+ "channelOrders": "{percent}% of AI orders",+ "channelSlots": "{percent}% of your products on the shelf",+ "channelNone": "None of your products on a shelf yet"+ },+ "allChannels": "All channels",+ "you": "You",+ "via": "via {place}",+ "absent": "You're not on this shelf",+ "rank": "You: #{rank}",+ "rankWeek": "You: #{rank} · {own} of {count} shelves this week",+ "price": {+ "label": "Price",+ "all": "All",+ "under50": "Under $50",+ "50to100": "$50–100",+ "100to200": "$100–200",+ "over200": "$200 and up"+ },+ "empty": "No shopping answers in this period. Track shopping questions on a channel that shows products.",+ "emptyBand": "No shelf in this price range.",+ "more": "Show {count} more",+ "trends": "Trends",+ "failed": "Couldn't read the shelves right now. The other tabs still work; try again in a moment."+ },"sources": {"label": "Data sources","catalog": "Product catalog",@@ -7967,14 +8005,6 @@"soon": "Soon","manage": "Manage"},- "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","seriesCardRate": "Card rate",@@ -8022,24 +8052,10 @@"compSov": "Shopping SOV","compSummaryTitle": "Competitor Summary","competitorName": "Competitor",- "tabPrompts": "Card-eligible prompts",- "kpiTriggerRate": "Trigger rate",- "kpiTriggerRateSub": "% of tracked prompts returning ≥1 card","searchPrompts": "Search prompts...",- "tablePrompt": "Prompt",- "tableTopic": "Topic",- "tablePlatforms": "Platforms with cards",- "tableTotalCards": "Total cards",- "tableSplitBar": "Own / Competitor / Other",- "tableLastSeen": "Last seen",- "noPromptsFound": "No card-eligible prompts found",- "noPromptsFoundSub": "Try widening your date range or removing filters.",- "drawerTitle": "Shopping Card Appearances",- "drawerSubtitle": "Occurrences of product cards for this prompt","drawerTimestamp": "Timestamp","drawerPlatform": "Platform","drawerRegion": "Region",- "drawerCardsTitle": "Cards returned","matchScore": {"title": "Match with each prompt","estimate": "Ansvisor estimate",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.test.tsxnew file mode 100644index 000000000..e1b6f7eb6--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.test.tsx@@ -0,0 +1,188 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../messages/en.json';+import type { ShoppingAiOrders, ShoppingShelf } from '@/lib/actions/shopping';+import { buildShelf, shelfStats, type ShelfCardRow } from '@/lib/shopping/shelf';++/** The Shelf's numbers and rows (ECOM-006). */++vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, children }: { href: string; children: React.ReactNode }) => (+ <a href={href}>{children}</a>+ ),+}));++const { ShelfKpis, ShelfRows, priceText } = await import('./_shelf');++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++function render(node: React.ReactNode) {+ act(() => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ {node}+ </NextIntlClientProvider>,+ );+ });+ return container.textContent ?? '';+}++const card = (over: Partial<ShelfCardRow>): ShelfCardRow => ({+ prompt_result_id: 'r1',+ position: 0,+ created_at: new Date().toISOString(),+ platform: 'chatgpt-shopping',+ product_title: 'Summit Daypack 30 W',+ price_amount: 110,+ price_currency: 'USD',+ image_url: null,+ merchant_domain: 'summitgear.example',+ rating: 4.8,+ review_count: 2140,+ matched_brand_role: 'competitor',+ merchant_kind: 'reseller',+ marketplace: null,+ catalog_product_id: null,+ prompt_id: 'p1',+ prompt_text: 'lightweight 30L hiking backpack for women',+ ...over,+});++const cards = [+ card({}),+ card({ position: 1, product_title: 'TrailCo Lite 28', price_amount: 95 }),+ card({+ prompt_id: 'p2',+ prompt_text: 'best waterproof trail running shoes under $150',+ prompt_result_id: 'r2',+ product_title: 'Summit Peak GTX',+ price_amount: 139,+ }),+ card({+ prompt_id: 'p2',+ prompt_text: 'best waterproof trail running shoes under $150',+ prompt_result_id: 'r2',+ position: 1,+ product_title: 'Trail Runner X',+ price_amount: 129,+ matched_brand_role: 'own',+ merchant_kind: 'marketplace',+ marketplace: 'amazon',+ catalog_product_id: 'cp1',+ }),+];+const shelf: ShoppingShelf = {+ rows: buildShelf(cards),+ stats: shelfStats(cards),+ catalogProducts: 320,+};+const orders: ShoppingAiOrders = {+ orders: 152,+ previousOrders: 120,+ revenue: { value: 24_900, currency: 'USD' },+ previousRevenue: 19_000,+ channels: [+ { source: 'chatgpt.com', orders: 108 },+ { source: 'copilot.microsoft.com', orders: 44 },+ ],+};++describe('ShelfKpis', () => {+ it("shows the brand's shelf share, its products of the catalog's, AI revenue and the top channel", () => {+ const text = render(<ShelfKpis shelf={shelf} orders={orders} salesConnected />);+ expect(text).toContain('AI shelf share25%');+ expect(text).toContain('1 of 320');+ expect(text).toContain('$24.9k+31%');+ expect(text).toContain('152 orders from AI visits');+ expect(text).toContain('ChatGPT71% of AI orders');+ });++ it('asks to connect sales without orders or a source, and names the channel showing the products', () => {+ const none = { ...orders, orders: 0, revenue: null, previousRevenue: null, channels: [] };+ const text = render(<ShelfKpis shelf={shelf} orders={none} salesConnected={false} />);+ expect(container.querySelector('a[href="/dashboard/traffic"]')?.textContent).toBe(+ 'Connect to see sales',+ );+ expect(text).toContain('100% of your products on the shelf');+ expect(render(<ShelfKpis shelf={shelf} orders={none} salesConnected />)).toContain(+ 'No orders from AI visits yet',+ );+ });+});++describe('ShelfRows', () => {+ it("lists the shelves the brand isn't on first, its products ringed with where they're sold", () => {+ const text = render(+ <ShelfRows+ shelf={shelf}+ platforms={['chatgpt-shopping']}+ platform="all"+ onPlatform={() => {}}+ />,+ );+ const rows = [+ ...container.querySelectorAll('section > div.rounded-xl, section [data-slot="card"]'),+ ];+ expect(rows.length).toBeGreaterThan(0);+ expect(text.indexOf("You're not on this shelf")).toBeLessThan(text.indexOf('You: #2'));+ expect(text).toContain('2 · You');+ expect(text).toContain('via Amazon');+ expect(text).toContain('$129');+ });++ it('filters by channel through the page, and by the price of the shelf', () => {+ const onPlatform = vi.fn();+ render(+ <ShelfRows+ shelf={shelf}+ platforms={['chatgpt-shopping']}+ platform="all"+ onPlatform={onPlatform}+ />,+ );+ const chip = [...container.querySelectorAll('button[aria-pressed]')].find(+ (b) => b.textContent === 'ChatGPT Shopping' || b.textContent === 'chatgpt-shopping',+ ) as HTMLButtonElement;+ act(() => chip.click());+ expect(onPlatform).toHaveBeenCalledWith('chatgpt-shopping');+ });++ it('says when there is nothing to show', () => {+ expect(+ render(+ <ShelfRows+ shelf={{ ...shelf, rows: [] }}+ platforms={[]}+ platform="all"+ onPlatform={() => {}}+ />,+ ),+ ).toContain('No shopping answers in this period');+ });+});++describe('priceText', () => {+ it('writes whole prices without cents, others with', () => {+ expect(priceText(139, 'USD')).toBe('$139');+ expect(priceText(24.5, 'USD')).toBe('$24.50');+ expect(priceText(89, 'EUR')).toBe('€89');+ expect(priceText(10, 'XYZ1')).toBe('10 XYZ1');+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.tsxnew file mode 100644index 000000000..9859dc22d--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.tsx@@ -0,0 +1,418 @@+'use client';++import { useState } from 'react';+import { useTranslations } from 'next-intl';+import { ShoppingBag, Star } from 'lucide-react';+import { Link } from '@/i18n/navigation';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { Card, CardContent } from '@/components/ui/card';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';+import { Skeleton } from '@/components/ui/skeleton';+import { AIProviderAvatar, resolveAIProvider } from '@/components/ai-provider-avatar';+import { PLATFORM_LABELS } from '@/config/platform-labels';+import { getFaviconUrl } from '@/lib/favicon';+import { formatCompactNumber, formatNumber } from '@/lib/format';+import { getPlatformName } from '@/lib/traffic-platforms';+import { cn } from '@/lib/utils';+import type { ShoppingAiOrders, ShoppingShelf } from '@/lib/actions/shopping';+import {+ PRICE_BANDS,+ inPriceBand,+ type PriceBand,+ type ShelfCard,+ type ShelfRow,+} from '@/lib/shopping/shelf';++/** Rows shown before "Show more". */+const ROWS_SHOWN = 20;++const platformName = (platform: string) => PLATFORM_LABELS[platform] ?? platform;++const MARKETPLACE_NAMES: Record<string, string> = {+ amazon: 'Amazon',+ ebay: 'eBay',+ walmart: 'Walmart',+ etsy: 'Etsy',+};+const marketplaceName = (id: string) =>+ MARKETPLACE_NAMES[id] ?? id.charAt(0).toUpperCase() + id.slice(1);++/** A price as the card shows it: "$139", "$24.50", "€89", or the amount and its code. */+export function priceText(value: number, currency: string | null): string {+ const digits = Number.isInteger(value) ? 0 : 2;+ try {+ return new Intl.NumberFormat('en-US', {+ style: 'currency',+ currency: currency || 'USD',+ minimumFractionDigits: digits,+ maximumFractionDigits: digits,+ }).format(value);+ } catch {+ return `${value.toFixed(digits)} ${currency ?? ''}`.trim();+ }+}++/** A month's revenue, short: "$24.9k". */+function revenueText(value: number, currency: string | null): string {+ if (value < 1000) return priceText(Math.round(value), currency);+ const symbol = priceText(0, currency).replace(/[\d.,\s]/g, '');+ return `${symbol}${formatCompactNumber(Math.round(value))}`;+}++/** A change against the period before, in percent, or null when there's nothing to compare. */+function change(current: number, previous: number): number | null {+ if (!previous) return null;+ return Math.round(((current - previous) / previous) * 100);+}++function Kpi({+ title,+ value,+ delta,+ sub,+}: {+ title: string;+ value: string;+ delta?: string | null;+ sub: React.ReactNode;+}) {+ return (+ <Card>+ <CardContent className="space-y-1.5 p-4">+ <p className="text-xs font-medium text-muted-foreground">{title}</p>+ <p className="flex items-baseline gap-2">+ <span className="truncate text-2xl font-bold tabular-nums">{value}</span>+ {delta && (+ <span+ className={cn(+ 'text-xs font-medium tabular-nums',+ delta.startsWith('-')+ ? 'text-red-600 dark:text-red-400'+ : 'text-emerald-600 dark:text-emerald-400',+ )}+ >+ {delta}+ </span>+ )}+ </p>+ <p className="text-xs text-muted-foreground">{sub}</p>+ </CardContent>+ </Card>+ );+}++/**+ * The Shelf's four numbers (ECOM-006): the brand's share of the product+ * slots in AI answers, its products on the shelf (of the catalog's), its+ * orders from AI visits in the last 30 days, and the AI channel most of them+ * came from (else the one showing its products most).+ */+export function ShelfKpis({+ shelf,+ orders,+ salesConnected,+}: {+ shelf: ShoppingShelf | null;+ orders: ShoppingAiOrders | null;+ /** Whether a source of sales is in: the tracking snippet, the Shopify pixel or GA. */+ salesConnected: boolean;+}) {+ const t = useTranslations('shopping.shelf.kpis');+ if (!shelf) {+ return (+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">+ {[0, 1, 2, 3].map((i) => (+ <Skeleton key={i} className="h-[104px]" />+ ))}+ </div>+ );+ }+ const { stats } = shelf;+ const share = stats.slots ? Math.round((stats.ownSlots / stats.slots) * 100) : 0;+ const revenueChange =+ orders?.revenue && orders.previousRevenue !== null+ ? change(orders.revenue.value, orders.previousRevenue)+ : null;+ const topOrders = orders?.channels[0];+ const topShelf = stats.channels[0];+ return (+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">+ <Kpi title={t('share')} value={`${share}%`} sub={t('shareSub')} />+ <Kpi+ title={t('products')}+ value={+ stats.fromCatalog && shelf.catalogProducts+ ? t('productsOf', {+ count: formatNumber(stats.products),+ total: formatNumber(shelf.catalogProducts),+ })+ : formatNumber(stats.products)+ }+ sub={stats.fromCatalog ? t('productsSub') : t('productsTitlesSub')}+ />+ <Kpi+ title={t('revenue')}+ value={+ orders?.revenue && orders.orders+ ? revenueText(orders.revenue.value, orders.revenue.currency)+ : orders?.orders+ ? formatNumber(orders.orders)+ : '—'+ }+ delta={+ revenueChange !== null && orders?.orders+ ? `${revenueChange >= 0 ? '+' : ''}${revenueChange}%`+ : null+ }+ sub={+ orders?.orders ? (+ t('orders', { count: orders.orders })+ ) : salesConnected ? (+ t('noOrders')+ ) : (+ <Link href="/dashboard/traffic" className="text-primary hover:underline">+ {t('connectSales')}+ </Link>+ )+ }+ />+ <Kpi+ title={t('channel')}+ value={+ topOrders+ ? getPlatformName(topOrders.source)+ : topShelf+ ? platformName(topShelf.platform)+ : '—'+ }+ sub={+ topOrders && orders+ ? t('channelOrders', { percent: Math.round((topOrders.orders / orders.orders) * 100) })+ : topShelf+ ? t('channelSlots', {+ percent: Math.round((topShelf.ownSlots / stats.ownSlots) * 100),+ })+ : t('channelNone')+ }+ />+ </div>+ );+}++function ProductCard({ card }: { card: ShelfCard }) {+ const t = useTranslations('shopping.shelf');+ return (+ <li+ className={cn(+ 'flex min-w-0 flex-col gap-1.5 rounded-lg border bg-card p-2.5',+ card.own && 'border-primary/60 bg-primary/5 ring-1 ring-primary/40',+ )}+ >+ <div className="flex flex-wrap items-center justify-between gap-1">+ <span className="whitespace-nowrap text-xs font-semibold tabular-nums text-muted-foreground">+ {card.rank}+ {card.own && <span className="text-primary"> · {t('you')}</span>}+ </span>+ {card.via && (+ <Badge variant="outline" className="h-4 px-1 text-[10px] font-normal">+ {t('via', { place: marketplaceName(card.via) })}+ </Badge>+ )}+ </div>+ <div className="grid h-20 place-items-center overflow-hidden rounded bg-muted/50">+ {card.image ? (+ // eslint-disable-next-line @next/next/no-img-element -- answer images from any host+ <img+ src={card.image}+ alt=""+ loading="lazy"+ referrerPolicy="no-referrer"+ className="h-full w-full object-contain"+ />+ ) : (+ <ShoppingBag className="h-6 w-6 text-muted-foreground/40" aria-hidden />+ )}+ </div>+ <p className="line-clamp-2 text-xs font-medium" title={card.title}>+ {card.title}+ </p>+ <p className="flex flex-wrap items-center gap-x-1.5 text-[11px] text-muted-foreground tabular-nums">+ {card.price !== null && <span>{priceText(card.price, card.currency)}</span>}+ {card.rating !== null && (+ <span className="inline-flex items-center gap-0.5">+ <Star className="h-2.5 w-2.5 fill-current" aria-hidden />+ {card.rating.toFixed(1)}+ </span>+ )}+ </p>+ {card.merchant && (+ <p className="flex min-w-0 items-center gap-1 text-[11px] text-muted-foreground">+ {/* eslint-disable-next-line @next/next/no-img-element -- a merchant's favicon */}+ <img+ src={getFaviconUrl(card.merchant, 32)}+ alt=""+ className="h-3 w-3 shrink-0 rounded-sm"+ loading="lazy"+ />+ <span className="truncate">{card.merchant}</span>+ </p>+ )}+ </li>+ );+}++function ShelfRowCard({ row }: { row: ShelfRow }) {+ const t = useTranslations('shopping.shelf');+ return (+ <Card>+ <CardContent className="space-y-3 p-4">+ <div className="flex flex-wrap items-start justify-between gap-2">+ <div className="min-w-0 space-y-1">+ <p className="text-sm font-medium" title={row.promptText}>+ {row.promptText}+ </p>+ <p className="flex items-center gap-1.5 text-xs text-muted-foreground">+ <AIProviderAvatar+ provider={resolveAIProvider(row.platform, row.platform)}+ className="h-3.5 w-3.5"+ plain+ />+ {platformName(row.platform)}+ </p>+ </div>+ <span+ className={cn(+ 'shrink-0 rounded-full px-2 py-0.5 text-xs font-medium',+ row.ownRank === null+ ? 'bg-amber-500/10 text-amber-700 dark:text-amber-400'+ : row.ownRank === 1+ ? 'bg-emerald-500/10 text-emerald-700 dark:text-emerald-400'+ : 'bg-primary/10 text-primary',+ )}+ >+ {row.ownRank === null+ ? t('absent')+ : row.weekShelves > 1+ ? t('rankWeek', {+ rank: row.ownRank,+ own: row.weekOwnShelves,+ count: row.weekShelves,+ })+ : t('rank', { rank: row.ownRank })}+ </span>+ </div>+ <ol className="grid grid-cols-2 gap-2 sm:grid-cols-3 xl:grid-cols-6">+ {row.cards.map((card) => (+ <ProductCard key={card.rank} card={card} />+ ))}+ </ol>+ </CardContent>+ </Card>+ );+}++/**+ * The shelves (ECOM-006): one row per shopping question and channel, its+ * latest products in order with their photos, prices, ratings and+ * merchants, the brand's own ringed. Filters: the channel (the page's+ * platform filter, as chips) and the shelf's price.+ */+export function ShelfRows({+ shelf,+ platforms,+ platform,+ onPlatform,+}: {+ shelf: ShoppingShelf | null;+ /** The channels with data, for the chips. */+ platforms: string[];+ platform: string;+ onPlatform: (platform: string) => void;+}) {+ const t = useTranslations('shopping.shelf');+ const [band, setBand] = useState<PriceBand>('all');+ const [shown, setShown] = useState(ROWS_SHOWN);++ if (!shelf) {+ return (+ <div className="space-y-3">+ {[0, 1, 2].map((i) => (+ <Skeleton key={i} className="h-[180px]" />+ ))}+ </div>+ );+ }+ const rows = shelf.rows.filter((row) => inPriceBand(row, band));+ const chip = (id: string, label: string) => (+ <button+ key={id}+ type="button"+ aria-pressed={platform === id}+ onClick={() => onPlatform(id)}+ className={cn(+ 'inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50',+ platform === id+ ? 'border-primary bg-primary text-primary-foreground'+ : 'bg-card text-muted-foreground hover:bg-muted hover:text-foreground',+ )}+ >+ {label}+ </button>+ );++ return (+ <section className="space-y-3" aria-label={t('label')}>+ <div className="flex flex-wrap items-center gap-1.5">+ {chip('all', t('allChannels'))}+ {platforms.map((id) => chip(id, platformName(id)))}+ <Select+ value={band}+ onValueChange={(value) => {+ setBand(value as PriceBand);+ setShown(ROWS_SHOWN);+ }}+ items={PRICE_BANDS.map((id) => ({+ value: id,+ label: `${t('price.label')}: ${t(`price.${id}`)}`,+ }))}+ >+ <SelectTrigger size="sm" className="ml-auto h-7" aria-label={t('price.label')}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent align="end">+ {PRICE_BANDS.map((id) => (+ <SelectItem key={id} value={id}>+ {t(`price.${id}`)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ {rows.length === 0 ? (+ <p className="rounded-lg border border-dashed px-4 py-10 text-center text-sm text-muted-foreground">+ {shelf.rows.length ? t('emptyBand') : t('empty')}+ </p>+ ) : (+ <>+ {rows.slice(0, shown).map((row) => (+ <ShelfRowCard key={row.key} row={row} />+ ))}+ {rows.length > shown && (+ <div className="flex justify-center">+ <Button variant="outline" size="sm" onClick={() => setShown((n) => n + ROWS_SHOWN)}>+ {t('more', { count: rows.length - shown })}+ </Button>+ </div>+ )}+ </>+ )}+ </section>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsxindex 80dd05b09..67173bc64 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx@@ -20,17 +20,10 @@ const DynamicShoppingTrendChart = dynamic();import {ShoppingBag,- Store,- ArrowUpRight,Crown,- Lock,Download,ExternalLink,Layers,- Target,- Search,- Calendar,- Globe,AlertTriangle,HelpCircle,} from 'lucide-react';@@ -44,15 +37,16 @@ import {getOwnProducts,getCompetitorProducts,getCompetitorSummary,- getCardEligiblePrompts,+ getShoppingAiOrders,+ getShoppingShelf,type ShoppingChartData,type ShoppingDatePreset,type ShoppingFilters,type ShoppingKpis,type ShoppingProduct,type CompetitorShoppingSummary,- type CardEligiblePromptRow,- type CardEligiblePromptsResponse,+ type ShoppingAiOrders,+ type ShoppingShelf,} from '@/lib/actions/shopping';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import {@@ -66,7 +60,6 @@ import { Skeleton } from '@/components/ui/skeleton';import { Badge } from '@/components/ui/badge';import { Link } from '@/i18n/navigation';import { Button, buttonVariants } from '@/components/ui/button';-import { Input } from '@/components/ui/input';import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';import {Table,@@ -99,6 +92,7 @@ import { googleSourceStatus } from '@/lib/traffic-sources';import { readUrlChoice, writeUrlParams } from '@/lib/url-state';import { CatalogNote } from './_catalog-note';import { ProductDataStrip, useProductSources } from './_data-strip';+import { ShelfKpis, ShelfRows } from './_shelf';import { ShoppingMarketSwitch, useShoppingMarket } from './_market-switch';import { WhyDialog } from './_why-dialog';import { MerchantSplitCard } from './merchant_split_card';@@ -111,20 +105,13 @@ import { useOpenAiIndex } from './use_openai_index';const DATE_PRESETS: ShoppingDatePreset[] = ['7d', '30d', '90d', 'all'];/** The page's tabs, the one open in the URL (?tab=products). */-const SHOPPING_TABS = ['shelf', 'prompts', 'products', 'competitors'] as const;+const SHOPPING_TABS = ['shelf', 'products', 'competitors'] as const;type ShoppingTab = (typeof SHOPPING_TABS)[number];// 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).-function getDomainName(url: string): string {- try {- return new URL(url).hostname.replace('www.', '');- } catch {- return url;- }-}export default function ShoppingPage() {const t = useTranslations('shopping');const tCommon = useTranslations('common');@@ -155,7 +142,8 @@ export default function ShoppingPage() {const [ownProducts, setOwnProducts] = useState<ShoppingProduct[]>([]);const [competitorProducts, setCompetitorProducts] = useState<ShoppingProduct[]>([]);const [competitorSummary, setCompetitorSummary] = useState<CompetitorShoppingSummary[]>([]);- const [promptsData, setPromptsData] = useState<CardEligiblePromptsResponse | null>(null);+ const [shelf, setShelf] = useState<ShoppingShelf | 'failed' | null>(null);+ const [orders, setOrders] = useState<ShoppingAiOrders | null>(null);const [tableLoading, setTableLoading] = useState(false);const [selectedProduct, setSelectedProduct] = useState<ShoppingProduct | null>(null);const [activeTab, setActiveTab] = useState<ShoppingTab>('shelf');@@ -163,6 +151,10 @@ export default function ShoppingPage() {const sources = useProductSources(activeBrandId);const primaryDomain =activeBrand?.domains?.find((d) => d.isPrimary)?.domain ?? activeBrand?.domains?.[0]?.domain;+ // Sales come from the tracking snippet (with the Shopify pixel) or GA.+ const salesConnected =+ !!sources.google &&+ (!!sources.google.snippetLastVisitAt || googleSourceStatus(sources.google.ga) === 'connected');// Connect Google Analytics in the Why popup: while GA isn't connected.const offerGa =canManage && !!sources.google && googleSourceStatus(sources.google.ga) === 'not_connected';@@ -233,7 +225,11 @@ export default function ShoppingPage() {getOwnProducts(activeBrandId, filters),getCompetitorProducts(activeBrandId, filters),getCompetitorSummary(activeBrandId, filters),- getCardEligiblePrompts(activeBrandId, filters),+ // The Shelf reads on its own: a failure there leaves the rest.+ getShoppingShelf(activeBrandId, filters).catch((err) => {+ console.error('Failed to read the shelves:', err);+ return 'failed' as const;+ }),);}@@ -247,7 +243,7 @@ export default function ShoppingPage() {setOwnProducts(results[1] as ShoppingProduct[]);setCompetitorProducts(results[2] as ShoppingProduct[]);setCompetitorSummary(results[3] as CompetitorShoppingSummary[]);- setPromptsData(results[4] as CardEligiblePromptsResponse);+ setShelf(results[4] as ShoppingShelf | 'failed');}}} finally {@@ -263,6 +259,22 @@ export default function ShoppingPage() {void loadData();}, [loadData, shoppingMarket.ready]);+ // Orders from AI visits, the last 30 days whatever the filters (ECOM-006).+ useEffect(() => {+ if (!activeBrandId || !hasFullAccess) return;+ let cancelled = false;+ getShoppingAiOrders(activeBrandId)+ .then((read) => {+ if (!cancelled) setOrders(read);+ })+ .catch(() => {+ if (!cancelled) setOrders(null);+ });+ return () => {+ cancelled = true;+ };+ }, [activeBrandId, hasFullAccess]);+// This alert always evaluates five consecutive rolling seven-day windows// ending at query time, independently of display/platform/region filters.useEffect(() => {@@ -358,13 +370,6 @@ export default function ShoppingPage() {<EmptyState title={t('emptyTitle')} description={t('emptyDescription')} />) : (<>- <KpiGrid- t={t}- kpis={kpis}- loading={loading}- hasFullAccess={hasFullAccess}- triggerRate={promptsData?.triggerRate}- /><Tabsvalue={activeTab}onValueChange={(value) => changeTab(value as ShoppingTab)}@@ -372,7 +377,6 @@ export default function ShoppingPage() {><TabsList><TabsTrigger value="shelf">{t('tabShelf')}</TabsTrigger>- <TabsTrigger value="prompts">{t('tabPrompts')}</TabsTrigger><TabsTrigger value="products">{t('tabProducts')}</TabsTrigger><TabsTrigger value="competitors">{t('tabCompetitors')}</TabsTrigger></TabsList>@@ -380,6 +384,33 @@ export default function ShoppingPage() {<TabsContent value="shelf" className="space-y-6">{hasFullAccess ? (<>+ {shelf === 'failed' && (+ <p+ role="alert"+ className="rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-200"+ >+ {t('shelf.failed')}+ </p>+ )}+ <ShelfKpis+ shelf={shelf === 'failed' ? null : shelf}+ orders={orders}+ salesConnected={salesConnected}+ />+ <div className="grid gap-4 lg:grid-cols-2">+ <MerchantSplitCard split={destinations.split} loading={destinationsLoading} />+ <ResellerPriceAlerts+ alerts={destinations.priceAlerts}+ loading={destinationsLoading}+ />+ </div>+ <ShelfRows+ shelf={tableLoading || shelf === 'failed' ? null : shelf}+ platforms={filterOpts.platforms}+ platform={platform}+ onPlatform={setPlatform}+ />+ <h2 className="pt-2 text-sm font-semibold">{t('shelf.trends')}</h2><div className="grid gap-4 lg:grid-cols-2"><PlatformCardRateChartt={t}@@ -392,13 +423,6 @@ export default function ShoppingPage() {loading={loading}/></div>- <div className="grid gap-4 lg:grid-cols-2">- <MerchantSplitCard split={destinations.split} loading={destinationsLoading} />- <ResellerPriceAlerts- alerts={destinations.priceAlerts}- loading={destinationsLoading}- />- </div>{showOpenAiIndex && (<OpenAiIndexCardread={openAiIndex.read}@@ -413,19 +437,6 @@ export default function ShoppingPage() {)}</TabsContent>- <TabsContent value="prompts" className="space-y-6">- {hasFullAccess ? (- <PromptsTabContent- t={t}- brandId={activeBrandId}- promptsData={promptsData}- loading={tableLoading}- />- ) : (- <UpgradeCard t={t} requiredPlan={requiredPlanFor('shopping_analytics')} />- )}- </TabsContent>-<TabsContent value="products" className="space-y-6">{hasFullAccess ? (<>@@ -572,311 +583,6 @@ export default function ShoppingPage() {);}-function PromptsTabContent({- t,- brandId,- promptsData,- loading,-}: {- t: ReturnType<typeof useTranslations<'shopping'>>;- brandId: string;- promptsData: CardEligiblePromptsResponse | null;- loading: boolean;-}) {- const tCommon = useTranslations('common');- const [searchQuery, setSearchQuery] = useState('');- const [selectedPrompt, setSelectedPrompt] = useState<CardEligiblePromptRow | null>(null);-- const brand = useBrandStore((s) => s.brands.find((b) => b.id === brandId) ?? null);- const brandSlug = brand?.slug || brandId;-- const filteredPrompts = useMemo(() => {- if (!promptsData?.prompts) return [];- const q = searchQuery.toLowerCase().trim();- if (!q) return promptsData.prompts;- return promptsData.prompts.filter(- (p) => p.promptText.toLowerCase().includes(q) || p.topic.toLowerCase().includes(q),- );- }, [promptsData, searchQuery]);-- const handleExportCsv = useCallback(() => {- if (!promptsData?.prompts.length) return;- const exportRows = promptsData.prompts.map((p) => ({- prompt: p.promptText,- topic: p.topic,- platforms: p.platforms.join('; '),- total_cards: p.totalCards,- own_cards: p.ownCardsCount,- competitor_cards: p.competitorCardsCount,- other_cards: p.otherCardsCount,- last_seen: p.lastTriggered ? p.lastTriggered.slice(0, 10) : '—',- }));- const headers = [- 'prompt',- 'topic',- 'platforms',- 'total_cards',- 'own_cards',- 'competitor_cards',- 'other_cards',- 'last_seen',- ];- const csv = toCsv(exportRows, headers);- const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });- const url = URL.createObjectURL(blob);- const link = document.createElement('a');- link.setAttribute('href', url);- const date = new Date().toISOString().slice(0, 10);- link.setAttribute('download', `ansvisor_${brandSlug}_shopping_prompts_${date}.csv`);- link.style.visibility = 'hidden';- document.body.appendChild(link);- link.click();- document.body.removeChild(link);- }, [promptsData, brandSlug]);-- if (loading && !promptsData) {- return (- <div className="space-y-6">- <div className="flex items-center justify-between gap-4">- <Skeleton className="h-9 w-64" />- <Skeleton className="h-9 w-32" />- </div>- <div className="space-y-2">- {Array.from({ length: 5 }).map((_, i) => (- <Skeleton key={i} className="h-12 w-full" />- ))}- </div>- </div>- );- }-- return (- <div className="space-y-6">- <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">- <div className="relative flex-1 max-w-sm">- <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />- <Input- placeholder={t('searchPrompts')}- value={searchQuery}- onChange={(e) => setSearchQuery(e.target.value)}- className="pl-8"- />- </div>- <Button- variant="outline"- size="sm"- onClick={handleExportCsv}- disabled={!promptsData?.prompts.length}- className="gap-1.5"- >- <Download className="h-3.5 w-3.5" />- {tCommon('exportCsv')}- </Button>- </div>-- <div className="rounded-md border bg-card">- <Table>- <TableHeader>- <TableRow>- <TableHead>{t('tablePrompt')}</TableHead>- <TableHead>{t('tableTopic')}</TableHead>- <TableHead>{t('tablePlatforms')}</TableHead>- <TableHead className="text-right">{t('tableTotalCards')}</TableHead>- <TableHead className="w-[120px]">{t('tableSplitBar')}</TableHead>- <TableHead className="text-right">{t('tableLastSeen')}</TableHead>- </TableRow>- </TableHeader>- <TableBody>- {loading ? (- <TableRow>- <TableCell colSpan={6} className="h-24 text-center">- {t('common.loading')}- </TableCell>- </TableRow>- ) : filteredPrompts.length === 0 ? (- <TableRow>- <TableCell colSpan={6} className="h-32 text-center">- <div className="flex flex-col items-center justify-center text-muted-foreground">- <ShoppingBag className="h-8 w-8 opacity-40 mb-2" />- <p className="font-medium text-sm">{t('noPromptsFound')}</p>- <p className="text-xs mt-1">{t('noPromptsFoundSub')}</p>- </div>- </TableCell>- </TableRow>- ) : (- filteredPrompts.map((row) => {- const ownPct = row.totalCards > 0 ? (row.ownCardsCount / row.totalCards) * 100 : 0;- const compPct =- row.totalCards > 0 ? (row.competitorCardsCount / row.totalCards) * 100 : 0;- const otherPct =- row.totalCards > 0 ? (row.otherCardsCount / row.totalCards) * 100 : 0;-- return (- <TableRow- key={row.promptId}- className="cursor-pointer transition-colors hover:bg-muted/50"- onClick={() => setSelectedPrompt(row)}- >- <TableCell className="max-w-[320px]">- <Link- href={`/dashboard/prompts/${row.promptId}`}- className="font-medium text-primary hover:underline block truncate"- onClick={(e) => e.stopPropagation()}- >- {row.promptText}- </Link>- </TableCell>- <TableCell>- <Badge variant="outline" className="text-xs font-normal">- {row.topic}- </Badge>- </TableCell>- <TableCell>- <div className="flex items-center gap-1">- {row.platforms.map((p) => (- <AIProviderAvatar- key={p}- provider={resolveAIProvider(p)}- className="h-5 w-5 border"- />- ))}- </div>- </TableCell>- <TableCell className="text-right font-medium tabular-nums">- {formatNumber(row.totalCards)}- </TableCell>- <TableCell>- <div- className="flex h-2 w-24 overflow-hidden rounded-full bg-muted-foreground/10"- title={`Own: ${row.ownCardsCount}, Competitors: ${row.competitorCardsCount}, Other: ${row.otherCardsCount}`}- >- {ownPct > 0 && (- <div className="h-full bg-primary" style={{ width: `${ownPct}%` }} />- )}- {compPct > 0 && (- <div className="h-full bg-orange-500" style={{ width: `${compPct}%` }} />- )}- {otherPct > 0 && (- <div- className="h-full bg-muted-foreground/40"- style={{ width: `${otherPct}%` }}- />- )}- </div>- </TableCell>- <TableCell className="text-right text-xs text-muted-foreground tabular-nums">- {row.lastTriggered ? row.lastTriggered.slice(0, 10) : '—'}- </TableCell>- </TableRow>- );- })- )}- </TableBody>- </Table>- </div>-- <Sheet open={!!selectedPrompt} onOpenChange={(open) => !open && setSelectedPrompt(null)}>- <SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-md overflow-y-auto px-4">- <SheetHeader className="pb-4 border-b">- <SheetTitle>{t('drawerTitle')}</SheetTitle>- <SheetDescription>{t('drawerSubtitle')}</SheetDescription>- </SheetHeader>- {selectedPrompt && (- <div className="space-y-6 py-4">- <div>- <h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-1">- {t('tablePrompt')}- </h4>- <p className="text-sm font-medium text-foreground bg-muted/30 rounded-lg p-3 border">- {selectedPrompt.promptText}- </p>- </div>-- <div className="space-y-4">- {selectedPrompt.appearances.map((app) => (- <div key={app.promptResultId} className="rounded-lg border bg-card p-4 space-y-3">- <div className="flex items-center justify-between border-b pb-2 text-xs">- <div className="flex items-center gap-1.5 font-medium text-foreground">- <AIProviderAvatar- provider={resolveAIProvider(app.platform)}- className="h-4.5 w-4.5"- />- <span>{getAIProviderDisplayName(resolveAIProvider(app.platform))}</span>- </div>- <div className="flex items-center gap-3 text-muted-foreground">- {app.region && (- <span className="flex items-center gap-1">- <Globe className="h-3 w-3" />- {app.region}- </span>- )}- <span className="flex items-center gap-1">- <Calendar className="h-3 w-3" />- {new Date(app.timestamp).toLocaleString('en-US', {- month: 'short',- day: 'numeric',- hour: '2-digit',- minute: '2-digit',- })}- </span>- </div>- </div>-- <div className="space-y-3">- <h5 className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wide">- {t('drawerCardsTitle')} ({app.cards.length})- </h5>- <div className="grid gap-2">- {app.cards.map((card) => (- <div- key={card.id}- className="flex gap-3 rounded-md border bg-muted/10 p-2 text-xs"- >- {card.imageUrl ? (- // eslint-disable-next-line @next/next/no-img-element -- product images come from arbitrary merchant domains; next/image remotePatterns would need an open-ended wildcard- <img- src={card.imageUrl}- alt=""- className="h-12 w-12 rounded border object-contain bg-white shrink-0"- onError={(e) => {- (e.target as HTMLElement).style.display = 'none';- }}- />- ) : null}- <div className="flex flex-1 flex-col justify-between min-w-0">- <span className="font-medium text-foreground line-clamp-1">- {card.title}- </span>- <div className="flex items-center justify-between mt-1 text-muted-foreground">- <span className="font-semibold text-foreground">{card.price}</span>- {card.merchantUrl && (- <a- href={card.merchantUrl}- target="_blank"- rel="noreferrer noopener"- className="inline-flex items-center gap-0.5 hover:text-primary transition-colors"- >- <span>{getDomainName(card.merchantUrl)}</span>- <ExternalLink className="h-3 w-3" />- </a>- )}- </div>- </div>- </div>- ))}- </div>- </div>- </div>- ))}- </div>- </div>- )}- </SheetContent>- </Sheet>- </div>- );-}-// ── Header ────────────────────────────────────────────────────────────────────/** The title, with "Why Ansvisor Product Visibility?" beside it (ECOM-010). */@@ -1004,111 +710,6 @@ function FilterField({ label, children }: { label: string; children: React.React);}-// ── KPI grid ──────────────────────────────────────────────────────────────────--function KpiGrid({- t,- kpis,- loading,- hasFullAccess,- triggerRate,-}: {- t: ReturnType<typeof useTranslations<'shopping'>>;- kpis: ShoppingKpis | null;- loading: boolean;- hasFullAccess: boolean;- triggerRate?: number;-}) {- if (loading && !kpis) {- return (- <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">- {Array.from({ length: 5 }).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-5">- <KpiCard- title={t('kpiCardRate')}- value={formatPercent(cardRate)}- subtitle={t('kpiCardRateSub')}- icon={ShoppingBag}- />- <KpiCard- title={t('kpiTriggerRate')}- value={triggerRate !== undefined ? formatPercent(triggerRate) : '—'}- subtitle={t('kpiTriggerRateSub')}- icon={Target}- locked={!hasFullAccess}- />- <KpiCard- title={t('kpiOwnProducts')}- value={formatNumber(productsSurfaced)}- 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({diff --git a/web/src/config/platform-labels.ts b/web/src/config/platform-labels.tsindex 49a1974a2..f465e53aa 100644--- a/web/src/config/platform-labels.ts+++ b/web/src/config/platform-labels.ts@@ -23,6 +23,7 @@ export const PLATFORM_LABELS: Record<string, string> = {// Tracked scraper platform slugs, as stored in `prompt_results.platform`.'chatgpt-web': 'ChatGPT',+ 'chatgpt-shopping': 'ChatGPT Shopping','google-aio': 'Google AI Overviews','google-aimode': 'Google AI Mode','copilot-web': 'Microsoft Copilot',diff --git a/web/src/lib/actions/shopping-shelf.test.ts b/web/src/lib/actions/shopping-shelf.test.tsnew file mode 100644index 000000000..9ebab0c9b--- /dev/null+++ b/web/src/lib/actions/shopping-shelf.test.ts@@ -0,0 +1,170 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/** The Shelf's reads (ECOM-006): the cards with their questions, the catalog's count, and AI orders. */++const BRAND = '33333333-3333-3333-3333-333333333333';++let tables: Record<string, Record<string, unknown>[]>;+let catalogCount: number | null;+const reads: { table: string; eq: Record<string, unknown>; gte?: [string, string] }[] = [];++function query(table: string) {+ const state: {+ table: string;+ eq: Record<string, unknown>;+ gte?: [string, string];+ range?: [number, number];+ head?: boolean;+ } = {+ table,+ eq: {},+ };+ const q = {+ select: (_columns: string, opts?: { head?: boolean }) => ((state.head = opts?.head), q),+ eq: (column: string, value: unknown) => ((state.eq[column] = value), q),+ is: () => q,+ in: () => q,+ lte: () => q,+ or: () => q,+ gte: (column: string, value: string) => ((state.gte = [column, value]), q),+ order: () => q,+ range: (from: number, to: number) => ((state.range = [from, to]), q),+ then: (resolve: (value: unknown) => void) => {+ reads.push({ table: state.table, eq: state.eq, gte: state.gte });+ if (state.head) return resolve({ data: null, count: catalogCount, error: null });+ const rows = (tables[table] ?? []).filter((row) =>+ Object.entries(state.eq).every(([k, v]) => !(k in row) || row[k] === v),+ );+ const [from, to] = state.range ?? [0, 999];+ resolve({ data: rows.slice(from, to + 1), error: null });+ },+ };+ return q;+}++vi.mock('@/lib/supabase/server', () => ({+ createClient: vi.fn(async () => ({ from: query })),+}));++const { getShoppingAiOrders, getShoppingShelf } = await import('./shopping');++beforeEach(() => {+ tables = {};+ catalogCount = null;+ reads.length = 0;+ vi.useFakeTimers({ now: new Date('2026-10-27T12:00:00Z'), toFake: ['Date'] });+});++describe('getShoppingShelf', () => {+ it("reads the cards with their questions, and counts the catalog's products", async () => {+ catalogCount = 320;+ tables.prompt_result_shopping_cards = [+ {+ prompt_result_id: 'r1',+ position: 0,+ created_at: '2026-10-27T08:00:00Z',+ platform: 'chatgpt-shopping',+ product_title: 'Trail Runner X',+ price_amount: 129,+ price_currency: 'USD',+ image_url: null,+ merchant_domain: 'northwind.example',+ rating: 4.6,+ review_count: 86,+ matched_brand_role: 'own',+ merchant_kind: 'own',+ marketplace: null,+ catalog_product_id: 'cp1',+ prompt_results: { prompt: { id: 'p1', text: 'best trail shoes' } },+ },+ ];+ const shelf = await getShoppingShelf(BRAND, { datePreset: '30d' });+ expect(shelf.catalogProducts).toBe(320);+ expect(shelf.rows.map((row) => [row.promptText, row.ownRank])).toEqual([+ ['best trail shoes', 1],+ ]);+ expect(shelf.stats).toMatchObject({ slots: 1, ownSlots: 1, products: 1, fromCatalog: true });+ });++ it('reads no catalog as none', async () => {+ catalogCount = 0;+ expect((await getShoppingShelf(BRAND, { datePreset: '7d' })).catalogProducts).toBeNull();+ });+});++describe('getShoppingAiOrders', () => {+ it("counts the last 30 days' orders against the 30 before, in the main currency, by AI source", async () => {+ tables.ai_traffic_events = [+ {+ value: 100,+ currency: 'USD',+ first_source: 'chatgpt.com',+ occurred_at: '2026-10-20T00:00:00Z',+ },+ {+ value: 50,+ currency: 'USD',+ first_source: 'chatgpt.com',+ occurred_at: '2026-10-10T00:00:00Z',+ },+ {+ value: 80,+ currency: 'EUR',+ first_source: 'copilot.microsoft.com',+ occurred_at: '2026-10-05T00:00:00Z',+ },+ {+ value: null,+ currency: null,+ first_source: 'perplexity.ai',+ occurred_at: '2026-10-01T00:00:00Z',+ },+ // The 30 days before.+ {+ value: 60,+ currency: 'USD',+ first_source: 'chatgpt.com',+ occurred_at: '2026-09-20T00:00:00Z',+ },+ {+ value: 40,+ currency: 'EUR',+ first_source: 'chatgpt.com',+ occurred_at: '2026-09-15T00:00:00Z',+ },+ ];+ const orders = await getShoppingAiOrders(BRAND);+ expect(orders).toEqual({+ orders: 4,+ previousOrders: 2,+ revenue: { value: 150, currency: 'USD' },+ previousRevenue: 60,+ channels: [+ { source: 'chatgpt.com', orders: 2 },+ { source: 'copilot.microsoft.com', orders: 1 },+ { source: 'perplexity.ai', orders: 1 },+ ],+ });+ expect(reads.at(-1)).toMatchObject({+ table: 'ai_traffic_events',+ eq: { brand_id: BRAND, kind: 'conversion', goal: 'order' },+ gte: ['occurred_at', '2026-08-28T12:00:00.000Z'],+ });+ });++ it('has no revenue when no order carries a value', async () => {+ tables.ai_traffic_events = [+ {+ value: null,+ currency: null,+ first_source: 'chatgpt.com',+ occurred_at: '2026-10-20T00:00:00Z',+ },+ ];+ expect(await getShoppingAiOrders(BRAND)).toMatchObject({+ orders: 1,+ revenue: null,+ previousRevenue: null,+ });+ });+});diff --git a/web/src/lib/actions/shopping.ts b/web/src/lib/actions/shopping.tsindex 24486b414..7bb77af40 100644--- a/web/src/lib/actions/shopping.ts+++ b/web/src/lib/actions/shopping.ts@@ -9,6 +9,13 @@ import {import { z } from 'zod';import { marketRegionCodes, type ShoppingMarket } from '@/lib/shopping/markets';import { matchScores, missingWords, queryTerms, sameProduct } from '@/lib/shopping/match-score';+import {+ buildShelf,+ shelfStats,+ type ShelfCardRow,+ type ShelfRow,+ type ShelfStats,+} from '@/lib/shopping/shelf';import {toMerchantSplit,type MerchantSplitRow,@@ -1072,3 +1079,145 @@ export async function getCardEligiblePrompts(totalTrackedPrompts: totalTracked,};}++// ── Shelf (Product Visibility, ECOM-006) ──────────────────────────────────────++const SHELF_CARD_COLUMNS = `+ prompt_result_id,+ position,+ created_at,+ platform,+ product_title,+ price_amount,+ price_currency,+ image_url,+ merchant_domain,+ rating,+ review_count,+ matched_brand_role,+ merchant_kind,+ marketplace,+ catalog_product_id,+ prompt_results:prompt_result_id (+ prompt:prompt_id (+ id,+ text+ )+ )+ `;++export interface ShoppingShelf {+ rows: ShelfRow[];+ stats: ShelfStats;+ /** The brand's live catalog products, or null when it has no catalog. */+ catalogProducts: number | null;+}++/**+ * The Shelf over the filter window: each question's latest shelf per+ * channel, the brand's share of the product slots and its products on them,+ * against the catalog's count.+ */+export async function getShoppingShelf(+ brandId: string,+ filters: ShoppingFilters,+): Promise<ShoppingShelf> {+ const supabase = await createClient();+ const [rows, catalog] = await Promise.all([+ fetchAllCards<+ Omit<ShelfCardRow, 'prompt_id' | 'prompt_text'> & {+ prompt_results: { prompt: { id: string; text: string } | null } | null;+ }+ >(() => cardsInWindow(supabase, brandId, filters, SHELF_CARD_COLUMNS)),+ supabase+ .from('catalog_products')+ .select('id', { count: 'exact', head: true })+ .eq('brand_id', brandId)+ .is('removed_at', null),+ ]);+ if (catalog.error) throw new Error(catalog.error.message);+ const cards: ShelfCardRow[] = rows.map(({ prompt_results, ...card }) => ({+ ...card,+ prompt_id: prompt_results?.prompt?.id ?? null,+ prompt_text: prompt_results?.prompt?.text ?? null,+ }));+ return {+ rows: buildShelf(cards),+ stats: shelfStats(cards),+ catalogProducts: catalog.count ? catalog.count : null,+ };+}++/** Orders from AI visits (CE-017): the last 30 days, the 30 before, and by AI channel. */+export interface ShoppingAiOrders {+ orders: number;+ previousOrders: number;+ /** The month's order value in its main currency, or null with no value. */+ revenue: { value: number; currency: string | null } | null;+ /** The 30 days before's, in the same currency. */+ previousRevenue: number | null;+ /** Orders by the AI source that first brought the visitor, most first. */+ channels: { source: string; orders: number }[];+}++const ORDERS_DAYS = 30;+const ORDER_PAGE = 1000;+const ORDER_MAX_ROWS = 50_000;++/**+ * The brand's orders from AI visits, as the tracking snippet and the Shopify+ * pixel record them (ai_traffic_events, 00286): a conversion with goal+ * 'order', credited to the AI source that first brought the visitor.+ */+export async function getShoppingAiOrders(brandId: string): Promise<ShoppingAiOrders> {+ const supabase = await createClient();+ const now = Date.now();+ const since = new Date(now - 2 * ORDERS_DAYS * 86_400_000).toISOString();+ const split = new Date(now - ORDERS_DAYS * 86_400_000).toISOString();+ const rows: {+ value: number | null;+ currency: string | null;+ first_source: string;+ occurred_at: string;+ }[] = [];+ for (let start = 0; start < ORDER_MAX_ROWS; start += ORDER_PAGE) {+ const { data, error } = await supabase+ .from('ai_traffic_events')+ .select('value, currency, first_source, occurred_at')+ .eq('brand_id', brandId)+ .eq('kind', 'conversion')+ .eq('goal', 'order')+ .gte('occurred_at', since)+ .order('occurred_at', { ascending: false })+ .order('id', { ascending: false })+ .range(start, start + ORDER_PAGE - 1);+ if (error) throw new Error(error.message);+ rows.push(...((data ?? []) as typeof rows));+ if ((data ?? []).length < ORDER_PAGE) break;+ }+ const current = rows.filter((row) => row.occurred_at >= split);+ const previous = rows.filter((row) => row.occurred_at < split);+ // The currency most of the month's valued orders are in.+ const counts = new Map<string, number>();+ for (const row of current) {+ if (row.value !== null)+ counts.set(row.currency ?? '', (counts.get(row.currency ?? '') ?? 0) + 1);+ }+ const main = [...counts].sort((a, b) => b[1] - a[1])[0]?.[0];+ const sum = (list: typeof rows) =>+ list+ .filter((row) => row.value !== null && (row.currency ?? '') === main)+ .reduce((total, row) => total + Number(row.value), 0);+ const channels = new Map<string, number>();+ for (const row of current)+ channels.set(row.first_source, (channels.get(row.first_source) ?? 0) + 1);+ return {+ orders: current.length,+ previousOrders: previous.length,+ revenue: main === undefined ? null : { value: sum(current), currency: main || null },+ previousRevenue: main === undefined ? null : sum(previous),+ channels: [...channels]+ .map(([source, orders]) => ({ source, orders }))+ .sort((a, b) => b.orders - a.orders || a.source.localeCompare(b.source)),+ };+}diff --git a/web/src/lib/shopping/shelf.test.ts b/web/src/lib/shopping/shelf.test.tsnew file mode 100644index 000000000..beed959b7--- /dev/null+++ b/web/src/lib/shopping/shelf.test.ts@@ -0,0 +1,157 @@+import { describe, expect, it } from 'vitest';+import { buildShelf, inPriceBand, shelfStats, SHELF_CARDS, type ShelfCardRow } from './shelf';++/** Product Visibility's Shelf (ECOM-006). */++const NOW = Date.parse('2026-10-27T12:00:00Z');++const card = (over: Partial<ShelfCardRow>): ShelfCardRow => ({+ prompt_result_id: 'r1',+ position: 0,+ created_at: '2026-10-27T08:00:00Z',+ platform: 'chatgpt-shopping',+ product_title: 'Summit Peak GTX',+ price_amount: 139,+ price_currency: 'USD',+ image_url: null,+ merchant_domain: 'summitgear.example',+ rating: 4.8,+ review_count: 2140,+ matched_brand_role: 'competitor',+ merchant_kind: 'reseller',+ marketplace: null,+ catalog_product_id: null,+ prompt_id: 'p1',+ prompt_text: 'best waterproof trail running shoes under $150',+ ...over,+});++describe('buildShelf', () => {+ it("shows each question's latest shelf per channel, in order, and the brand's week on it", () => {+ const rows = buildShelf(+ [+ // The latest shelf on ChatGPT: the brand second, through Amazon.+ card({+ position: 1,+ product_title: 'Trail Runner X',+ matched_brand_role: 'own',+ merchant_kind: 'marketplace',+ marketplace: 'amazon',+ catalog_product_id: 'cp1',+ price_amount: 129,+ }),+ card({ position: 0 }),+ // An older shelf this week, without the brand.+ card({ prompt_result_id: 'r0', created_at: '2026-10-24T08:00:00Z' }),+ // Older than a week: not counted in the week.+ card({+ prompt_result_id: 'r-old',+ created_at: '2026-10-10T08:00:00Z',+ matched_brand_role: 'own',+ }),+ // The same question on Copilot: the brand first.+ card({+ prompt_result_id: 'r2',+ platform: 'copilot-web',+ matched_brand_role: 'own',+ product_title: 'StormShell',+ }),+ ],+ NOW,+ );+ expect(+ rows.map((row) => [row.platform, row.ownRank, row.weekShelves, row.weekOwnShelves]),+ ).toEqual([+ ['chatgpt-shopping', 2, 2, 1],+ ['copilot-web', 1, 1, 1],+ ]);+ expect(rows[0].cards.map((c) => [c.rank, c.title, c.own, c.via, c.productId])).toEqual([+ [1, 'Summit Peak GTX', false, null, null],+ [2, 'Trail Runner X', true, 'amazon', 'cp1'],+ ]);+ });++ it("puts the shelves the brand isn't on first, then the lowest places", () => {+ const rows = buildShelf(+ [+ card({ prompt_id: 'a', prompt_text: 'a', matched_brand_role: 'own' }),+ card({ prompt_id: 'b', prompt_text: 'b', prompt_result_id: 'rb' }),+ card({ prompt_id: 'c', prompt_text: 'c', prompt_result_id: 'rc' }),+ card({+ prompt_id: 'c',+ prompt_text: 'c',+ prompt_result_id: 'rc',+ position: 1,+ matched_brand_role: 'own',+ }),+ ],+ NOW,+ );+ expect(rows.map((row) => [row.promptId, row.ownRank])).toEqual([+ ['b', null],+ ['c', 2],+ ['a', 1],+ ]);+ });++ it('shows a few products a shelf, and leaves out cards without a question', () => {+ const rows = buildShelf(+ [+ ...Array.from({ length: 10 }, (_, i) => card({ position: i })),+ card({ prompt_id: null, prompt_result_id: 'x' }),+ ],+ NOW,+ );+ expect(rows).toHaveLength(1);+ expect(rows[0].cards).toHaveLength(SHELF_CARDS);+ });+});++describe('shelfStats', () => {+ it("counts the brand's slots, its catalog products and the channels showing them", () => {+ const stats = shelfStats([+ card({ matched_brand_role: 'own', catalog_product_id: 'cp1', platform: 'copilot-web' }),+ card({ matched_brand_role: 'own', catalog_product_id: 'cp1' }),+ card({ matched_brand_role: 'own', catalog_product_id: 'cp2', platform: 'copilot-web' }),+ card({}),+ ]);+ expect(stats).toEqual({+ slots: 4,+ ownSlots: 3,+ products: 2,+ fromCatalog: true,+ channels: [+ { platform: 'copilot-web', ownSlots: 2 },+ { platform: 'chatgpt-shopping', ownSlots: 1 },+ ],+ });+ });++ it('counts titles when no card is matched to the catalog', () => {+ const stats = shelfStats([+ card({ matched_brand_role: 'own', product_title: 'Trail Runner X' }),+ card({ matched_brand_role: 'own', product_title: ' trail runner x ' }),+ card({ matched_brand_role: 'own', product_title: 'StormShell' }),+ ]);+ expect([stats.products, stats.fromCatalog]).toEqual([2, false]);+ });+});++describe('inPriceBand', () => {+ it("reads a shelf's middle price", () => {+ const [row] = buildShelf(+ [+ card({ position: 0, price_amount: 119 }),+ card({ position: 1, price_amount: 139 }),+ card({ position: 2, price_amount: 145 }),+ card({ position: 3, price_amount: null }),+ ],+ NOW,+ );+ expect(inPriceBand(row, 'all')).toBe(true);+ expect(inPriceBand(row, '100to200')).toBe(true);+ expect(inPriceBand(row, 'under50')).toBe(false);+ const [noPrices] = buildShelf([card({ price_amount: null })], NOW);+ expect(inPriceBand(noPrices, 'over200')).toBe(false);+ });+});diff --git a/web/src/lib/shopping/shelf.ts b/web/src/lib/shopping/shelf.tsnew file mode 100644index 000000000..fff091da6--- /dev/null+++ b/web/src/lib/shopping/shelf.ts@@ -0,0 +1,213 @@+/**+ * Product Visibility's Shelf (ECOM-006): for each shopping question the+ * brand tracks, the products AI put on its "shelf", in order, on each+ * channel, and where the brand's own products stand. Read from the product+ * cards of AI answers (prompt_result_shopping_cards), a card the brand's own+ * when matched_brand_role is 'own', and its catalog product when 00360+ * matched one.+ */++/** A card as the shelf reads it. */+export interface ShelfCardRow {+ prompt_result_id: string;+ position: number;+ created_at: string;+ platform: string;+ product_title: string | null;+ price_amount: number | null;+ price_currency: string | null;+ image_url: string | null;+ merchant_domain: string | null;+ rating: number | null;+ review_count: number | null;+ matched_brand_role: string;+ merchant_kind: string | null;+ marketplace: string | null;+ catalog_product_id: string | null;+ prompt_id: string | null;+ prompt_text: string | null;+}++/** A product on a shelf. */+export interface ShelfCard {+ /** Its place on the shelf, from 1. */+ rank: number;+ title: string;+ price: number | null;+ currency: string | null;+ rating: number | null;+ reviews: number | null;+ image: string | null;+ merchant: string | null;+ own: boolean;+ /** The marketplace an own product was linked through ("via Amazon"), else null. */+ via: string | null;+ productId: string | null;+}++/** One shopping question on one channel: its latest shelf, and the brand's week on it. */+export interface ShelfRow {+ key: string;+ promptId: string;+ promptText: string;+ platform: string;+ /** When its latest shelf was read. */+ at: string;+ cards: ShelfCard[];+ /** The brand's best place on the latest shelf, or null when it isn't on it. */+ ownRank: number | null;+ /** The shelves read in the last 7 days, and how many had one of the brand's products. */+ weekShelves: number;+ weekOwnShelves: number;+}++/** The products a row shows at most. */+export const SHELF_CARDS = 6;++const WEEK_MS = 7 * 86_400_000;++/**+ * The shelves: one row per question and channel, its newest answer's+ * products in order. The rows the brand isn't on come first, then those it+ * ranks lowest on: what needs work first.+ */+export function buildShelf(cards: readonly ShelfCardRow[], now: number = Date.now()): ShelfRow[] {+ const groups = new Map<+ string,+ {+ promptId: string;+ promptText: string;+ platform: string;+ runs: Map<string, { at: string; cards: ShelfCardRow[] }>;+ }+ >();+ for (const card of cards) {+ if (!card.prompt_id) continue;+ const key = `${card.prompt_id}:${card.platform}`;+ let group = groups.get(key);+ if (!group) {+ group = {+ promptId: card.prompt_id,+ promptText: card.prompt_text ?? '',+ platform: card.platform,+ runs: new Map(),+ };+ groups.set(key, group);+ }+ let run = group.runs.get(card.prompt_result_id);+ if (!run) {+ run = { at: card.created_at, cards: [] };+ group.runs.set(card.prompt_result_id, run);+ }+ if (card.created_at > run.at) run.at = card.created_at;+ run.cards.push(card);+ }++ const rows: ShelfRow[] = [];+ for (const [key, group] of groups) {+ const runs = [...group.runs.values()];+ const latest = runs.reduce((a, b) => (b.at > a.at ? b : a));+ const shelf = [...latest.cards]+ .sort((a, b) => a.position - b.position)+ .map(+ (card, i): ShelfCard => ({+ rank: i + 1,+ title: card.product_title?.trim() || '—',+ price: card.price_amount,+ currency: card.price_currency,+ rating: card.rating,+ reviews: card.review_count,+ image: card.image_url,+ merchant: card.merchant_domain,+ own: card.matched_brand_role === 'own',+ via:+ card.matched_brand_role === 'own' && card.merchant_kind === 'marketplace'+ ? card.marketplace+ : null,+ productId: card.catalog_product_id,+ }),+ );+ const week = runs.filter((run) => now - Date.parse(run.at) <= WEEK_MS);+ rows.push({+ key,+ promptId: group.promptId,+ promptText: group.promptText,+ platform: group.platform,+ at: latest.at,+ cards: shelf.slice(0, SHELF_CARDS),+ ownRank: shelf.find((card) => card.own)?.rank ?? null,+ weekShelves: week.length,+ weekOwnShelves: week.filter((run) =>+ run.cards.some((card) => card.matched_brand_role === 'own'),+ ).length,+ });+ }+ return rows.sort(+ (a, b) =>+ (a.ownRank === null ? 0 : 1) - (b.ownRank === null ? 0 : 1) ||+ (b.ownRank ?? 0) - (a.ownRank ?? 0) ||+ a.promptText.localeCompare(b.promptText) ||+ a.platform.localeCompare(b.platform),+ );+}++/** The brand's place on the shelves over the window. */+export interface ShelfStats {+ /** Product slots in the answers read, and how many held one of the brand's products. */+ slots: number;+ ownSlots: number;+ /** The brand's distinct products on the shelf: catalog products when matched, else titles. */+ products: number;+ /** Whether `products` counts catalog products (00360) rather than titles. */+ fromCatalog: boolean;+ /** Each channel's slots holding the brand's products, most first. */+ channels: { platform: string; ownSlots: number }[];+}++const titleKey = (title: string | null) =>+ String(title ?? '')+ .toLowerCase()+ .replace(/\s+/g, ' ')+ .trim();++export function shelfStats(cards: readonly ShelfCardRow[]): ShelfStats {+ const own = cards.filter((card) => card.matched_brand_role === 'own');+ const matched = new Set(+ own.flatMap((card) => (card.catalog_product_id ? [card.catalog_product_id] : [])),+ );+ const titles = new Set(own.map((card) => titleKey(card.product_title)).filter(Boolean));+ const channels = new Map<string, number>();+ for (const card of own) channels.set(card.platform, (channels.get(card.platform) ?? 0) + 1);+ return {+ slots: cards.length,+ ownSlots: own.length,+ products: matched.size || titles.size,+ fromCatalog: matched.size > 0,+ channels: [...channels]+ .map(([platform, ownSlots]) => ({ platform, ownSlots }))+ .sort((a, b) => b.ownSlots - a.ownSlots || a.platform.localeCompare(b.platform)),+ };+}++/** The Shelf's price filter: a shelf is in a band when its products' middle price is. */+export const PRICE_BANDS = ['all', 'under50', '50to100', '100to200', 'over200'] as const;+export type PriceBand = (typeof PRICE_BANDS)[number];++const BAND_RANGE: Record<Exclude<PriceBand, 'all'>, [number, number]> = {+ under50: [0, 50],+ '50to100': [50, 100],+ '100to200': [100, 200],+ over200: [200, Infinity],+};++export function inPriceBand(row: ShelfRow, band: PriceBand): boolean {+ if (band === 'all') return true;+ const prices = row.cards+ .map((card) => card.price)+ .filter((price): price is number => typeof price === 'number')+ .sort((a, b) => a - b);+ if (!prices.length) return false;+ const middle = prices[Math.floor((prices.length - 1) / 2)];+ const [min, max] = BAND_RANGE[band];+ return middle >= min && middle < max;+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex aa221971a..41b41ae54 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -474,6 +474,73 @@ export type Database = {},]}+ ai_traffic_events: {+ Row: {+ brand_id: string+ currency: string | null+ first_at: string+ first_key: string | null+ first_source: string+ first_url: string+ goal: string | null+ id: string+ kind: string+ label: string | null+ occurred_at: string+ order_ref: string | null+ origin: string | null+ page_key: string | null+ units: number | null+ url: string+ value: number | null+ visitor_id: string+ }+ Insert: {+ brand_id: string+ currency?: string | null+ first_at: string+ first_source: string+ first_url: string+ goal?: string | null+ id?: string+ kind: string+ label?: string | null+ occurred_at?: string+ order_ref?: string | null+ origin?: string | null+ units?: number | null+ url: string+ value?: number | null+ visitor_id: string+ }+ Update: {+ brand_id?: string+ currency?: string | null+ first_at?: string+ first_source?: string+ first_url?: string+ goal?: string | null+ id?: string+ kind?: string+ label?: string | null+ occurred_at?: string+ order_ref?: string | null+ origin?: string | null+ units?: number | null+ url?: string+ value?: number | null+ visitor_id?: string+ }+ Relationships: [+ {+ foreignKeyName: "ai_traffic_events_brand_id_fkey"+ columns: ["brand_id"]+ isOneToOne: false+ referencedRelation: "brands"+ referencedColumns: ["id"]+ },+ ]+ }ai_traffic_logs: {Row: {brand_id: string