Skip to content

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

feat(shopping): give each product a page with where it shows and why AI picked another one (Product Visibility, part 6) (#1641)

Cihan1bd3eb2247fb
diff --git a/web/messages/en.json b/web/messages/en.json
index 3c1c55ac6..f5c38a93c 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -7986,6 +7986,59 @@
"trends": "Trends",
"failed": "Couldn't read the shelves right now. The other tabs still work; try again in a moment."
},
+ "detail": {
+ "back": "Products",
+ "onShelves": "On {count} of {total} shelves",
+ "readiness": "Readiness {score}",
+ "viewPage": "View product page",
+ "ai": {
+ "visits": "AI clicks · 30d",
+ "orders": "AI orders · 30d",
+ "revenue": "AI revenue · 30d"
+ },
+ "why": {
+ "title": "Why not your product?",
+ "picked": "“{prompt}” · {platform} picked {winner}",
+ "leads": "Your product leads every shelf it's on. Nothing to explain here.",
+ "noQuestions": "No shopping question you track matches this product yet. Track a few questions shoppers would ask for it.",
+ "you": "You",
+ "winner": "Winner",
+ "rows": {
+ "score": "Match with the question",
+ "price": "Price",
+ "rating": "Rating · reviews",
+ "firstWords": "Key info in the first 40 words",
+ "gtin": "GTIN in the feed",
+ "photo": "Photo in the feed",
+ "stock": "In stock",
+ "merchant": "Sold by"
+ },
+ "states": {
+ "match": "in place",
+ "missing": "missing",
+ "weaker": "weaker than the winner",
+ "info": "for comparison"
+ }
+ },
+ "notes": {
+ "missingWords": "Missing: {words}",
+ "close": "Close",
+ "higher": "{percent}% higher",
+ "lower": "{percent}% lower",
+ "firstWords": "ChatGPT reads about 40 words"
+ },
+ "shelves": {
+ "title": "Where it shows",
+ "question": "Shopping question",
+ "place": "Place",
+ "match": "Match",
+ "missing": "Missing words",
+ "absent": "Not on the shelf"
+ },
+ "locked": "Product Visibility comes with the Growth plan.",
+ "failed": "Couldn't read this product right now. Try again in a moment.",
+ "notFound": "This product isn't in your catalog anymore."
+ },
"categories": {
"columns": {
"category": "Category",
@@ -8086,7 +8139,7 @@
"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.",
+ "lockedDescription": "Growth unlocks your AI shelf, your products and categories on it, where AI sends shoppers, and what it sells.",
"tabShelf": "Shelf",
"tabCategories": "Categories",
"tabProducts": "Products",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_product-detail.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_product-detail.tsx
new file mode 100644
index 000000000..fcf65554d
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_product-detail.tsx
@@ -0,0 +1,241 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { ArrowDown, Check, ExternalLink, Minus, ShoppingBag, X } from 'lucide-react';
+import { buttonVariants } from '@/components/ui/button-variants';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@/components/ui/table';
+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';
+import { PLATFORM_LABELS } from '@/config/platform-labels';
+import type { ShoppingProductDetail } from '@/lib/actions/shopping';
+import { formatNumber } from '@/lib/format';
+import { priceText } from '@/lib/shopping/price';
+import { READINESS_CHECKS } from '@/lib/shopping/products';
+import type { ComparisonState } from '@/lib/shopping/product-detail';
+import { cn } from '@/lib/utils';
+
+const platformName = (platform: string) => PLATFORM_LABELS[platform] ?? platform;
+
+const STATE_ICON: Record<ComparisonState, React.ReactNode> = {
+ match: <Check className="h-4 w-4 text-emerald-600 dark:text-emerald-400" aria-hidden />,
+ missing: <X className="h-4 w-4 text-red-600 dark:text-red-400" aria-hidden />,
+ weaker: <ArrowDown className="h-4 w-4 text-amber-600 dark:text-amber-400" aria-hidden />,
+ info: <Minus className="h-4 w-4 text-muted-foreground" aria-hidden />,
+};
+
+/**
+ * A product's page (ECOM-011), drawn: its header with its AI visits and
+ * orders, "Why not your product?" beside the winner, where it shows, and
+ * its readiness.
+ */
+export function ProductDetailView({ detail }: { detail: ShoppingProductDetail }) {
+ const t = useTranslations('shopping.detail');
+ const tReady = useTranslations('shopping.products.readiness');
+ const { product, focus } = detail;
+ const onShelves = detail.shelves.filter((line) => line.rank !== null).length;
+ return (
+ <div className="space-y-6">
+ <HeaderWithAiUsage>
+ <div className="flex min-w-0 items-start gap-4">
+ <div className="grid h-16 w-16 shrink-0 place-items-center overflow-hidden rounded-lg border bg-muted/50">
+ {product.image ? (
+ // eslint-disable-next-line @next/next/no-img-element -- catalog images from the brand's store
+ <img
+ src={product.image}
+ alt=""
+ referrerPolicy="no-referrer"
+ className="h-full w-full object-cover"
+ />
+ ) : (
+ <ShoppingBag className="h-6 w-6 text-muted-foreground/40" aria-hidden />
+ )}
+ </div>
+ <div className="min-w-0 space-y-1">
+ <h1 className="text-2xl font-bold tracking-tight">{product.title}</h1>
+ <p className="text-sm text-muted-foreground">
+ {[
+ product.price !== null ? priceText(product.price, product.currency) : null,
+ product.category?.split('>').at(-1)?.trim(),
+ t('onShelves', { count: onShelves, total: detail.shelves.length }),
+ t('readiness', { score: detail.readiness.score }),
+ ]
+ .filter(Boolean)
+ .join(' · ')}
+ </p>
+ </div>
+ {product.url && (
+ <a
+ href={product.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className={cn(
+ buttonVariants({ variant: 'outline', size: 'sm' }),
+ 'ml-auto shrink-0 gap-1.5',
+ )}
+ >
+ {t('viewPage')}
+ <ExternalLink className="h-3.5 w-3.5" aria-hidden />
+ </a>
+ )}
+ </div>
+ </HeaderWithAiUsage>
+
+ <div className="grid gap-3 sm:grid-cols-3">
+ {[
+ [t('ai.visits'), formatNumber(detail.ai.visits)],
+ [t('ai.orders'), formatNumber(detail.ai.orders)],
+ [
+ t('ai.revenue'),
+ detail.ai.orders && detail.ai.revenue !== null
+ ? priceText(Math.round(detail.ai.revenue), detail.ai.currency)
+ : '—',
+ ],
+ ].map(([label, value]) => (
+ <Card key={label}>
+ <CardContent className="space-y-1 p-4">
+ <p className="text-xs font-medium text-muted-foreground">{label}</p>
+ <p className="text-2xl font-bold tabular-nums">{value}</p>
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-base">{t('why.title')}</CardTitle>
+ {focus?.winner ? (
+ <p className="text-sm text-muted-foreground">
+ {t('why.picked', {
+ prompt: focus.promptText,
+ platform: platformName(focus.platform),
+ winner: focus.winner.title,
+ })}
+ </p>
+ ) : (
+ <p className="text-sm text-muted-foreground">
+ {detail.shelves.length ? t('why.leads') : t('why.noQuestions')}
+ </p>
+ )}
+ </CardHeader>
+ {focus?.winner && (
+ <CardContent className="px-0">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="pl-6" />
+ <TableHead>{t('why.you')}</TableHead>
+ <TableHead>{t('why.winner')}</TableHead>
+ <TableHead className="pr-6" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {detail.comparison.map((row) => (
+ <TableRow key={row.key}>
+ <TableCell className="pl-6 font-medium">
+ <span className="flex items-center gap-2">
+ {STATE_ICON[row.state]}
+ {t(`why.rows.${row.key}`)}
+ {/* The icon's state, for a screen reader. */}
+ <span className="sr-only">, {t(`why.states.${row.state}`)}</span>
+ </span>
+ </TableCell>
+ <TableCell className="tabular-nums">
+ {row.you ??
+ (row.state === 'match' ? '✓' : row.state === 'missing' ? '✕' : '—')}
+ </TableCell>
+ <TableCell className="tabular-nums text-muted-foreground">
+ {row.winner ?? '—'}
+ </TableCell>
+ <TableCell className="min-w-[140px] whitespace-normal pr-6 text-xs text-muted-foreground">
+ {row.note ? t(`notes.${row.note.key}`, row.note.values) : null}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </CardContent>
+ )}
+ </Card>
+
+ {detail.shelves.length > 0 && (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-base">{t('shelves.title')}</CardTitle>
+ </CardHeader>
+ <CardContent className="px-0">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="pl-6">{t('shelves.question')}</TableHead>
+ <TableHead>{t('shelves.place')}</TableHead>
+ <TableHead className="text-right">{t('shelves.match')}</TableHead>
+ <TableHead className="pr-6">{t('shelves.missing')}</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {detail.shelves.map((line) => (
+ <TableRow key={`${line.promptId}:${line.platform}`}>
+ <TableCell className="max-w-[320px] pl-6">
+ <p className="truncate text-sm" title={line.promptText}>
+ {line.promptText}
+ </p>
+ <p className="text-xs text-muted-foreground">{platformName(line.platform)}</p>
+ </TableCell>
+ <TableCell className="whitespace-nowrap text-sm">
+ {line.rank === null ? (
+ <span className="text-amber-700 dark:text-amber-400">
+ {t('shelves.absent')}
+ </span>
+ ) : (
+ `#${line.rank}`
+ )}
+ </TableCell>
+ <TableCell className="text-right tabular-nums">{line.score}</TableCell>
+ <TableCell className="max-w-[220px] whitespace-normal pr-6 text-xs text-muted-foreground">
+ <span className="line-clamp-2">
+ {line.missing.slice(0, 6).join(', ') || '—'}
+ </span>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </CardContent>
+ </Card>
+ )}
+
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-base">
+ {tReady('label', { score: detail.readiness.score })}
+ </CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-1.5 text-sm">
+ {detail.readiness.missing.length ? (
+ detail.readiness.missing.map((check) => (
+ <p key={check} className="flex items-center gap-2">
+ <X className="h-4 w-4 shrink-0 text-red-600 dark:text-red-400" aria-hidden />
+ {tReady('missing', {
+ check: tReady(`checks.${check}`),
+ points: READINESS_CHECKS[check],
+ })}
+ </p>
+ ))
+ ) : (
+ <p className="flex items-center gap-2">
+ <Check className="h-4 w-4 text-emerald-600 dark:text-emerald-400" aria-hidden />
+ {tReady('complete')}
+ </p>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_products-table.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_products-table.test.tsx
index 3f9d375be..ea68dd9dc 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_products-table.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_products-table.test.tsx
@@ -1,10 +1,19 @@
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { NextIntlClientProvider } from 'next-intl';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import messages from '../../../../../../messages/en.json';
import { productRows, type CatalogProductRow } from '@/lib/shopping/products';
-import { ProductsTable } from './_products-table';
+
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => (
+ <a href={href} {...rest}>
+ {children}
+ </a>
+ ),
+}));
+
+const { ProductsTable } = await import('./_products-table');
/** The Products table (ECOM-007). */
@@ -99,6 +108,13 @@ describe('ProductsTable', () => {
expect(bodyRows().map((row) => row[0])).toEqual(['Ridge 30L BackpackBackpacks · $119']);
});
+ it('links each product to its page', () => {
+ render(<ProductsTable products={{ rows, total: 2 }} loading={false} />);
+ expect(container.querySelector('a[href="/dashboard/shopping/products/p2"]')?.textContent).toBe(
+ 'StormShell Jacket',
+ );
+ });
+
it('says when the catalog is larger than the table reads, and counts All and Never shown out of it', () => {
expect(render(<ProductsTable products={{ rows, total: 2400 }} loading={false} />)).toContain(
'Showing 2 of 2,400 products: every one AI showed or sent visits to, then the rest.',
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_products-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_products-table.tsx
index 93c0ead06..4bd5325a5 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_products-table.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_products-table.tsx
@@ -3,6 +3,7 @@
import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { ShoppingBag } from 'lucide-react';
+import { Link } from '@/i18n/navigation';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
@@ -93,9 +94,13 @@ function ProductCell({ row }: { row: ProductRow }) {
)}
</div>
<div className="min-w-0">
- <p className="truncate text-sm font-medium" title={product.title}>
+ <Link
+ href={`/dashboard/shopping/products/${product.id}`}
+ className="block truncate text-sm font-medium hover:underline"
+ title={product.title}
+ >
{product.title}
- </p>
+ </Link>
<p className="truncate text-xs text-muted-foreground">
{[
product.category?.split('>').at(-1)?.trim(),
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.test.tsx
new file mode 100644
index 000000000..2693cc486
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.test.tsx
@@ -0,0 +1,161 @@
+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 { ShoppingProductDetail } from '@/lib/actions/shopping';
+
+/** A product's page (ECOM-011). */
+
+const getShoppingProductDetail = vi.hoisted(() => vi.fn());
+const gate = vi.hoisted(() => ({ allowed: true }));
+vi.mock('@/lib/actions/shopping', () => ({ getShoppingProductDetail }));
+vi.mock('next/navigation', () => ({ useParams: () => ({ productId: 'p1' }) }));
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => (
+ <a href={href} {...rest}>
+ {children}
+ </a>
+ ),
+}));
+vi.mock('@/stores/use-brand-store', () => ({
+ useBrandStore: (select: (s: { activeBrandId: string }) => unknown) =>
+ select({ activeBrandId: 'b1' }),
+}));
+vi.mock('@/hooks/use-feature-gate', () => ({
+ useFeatureGate: () => ({ canUse: () => gate.allowed }),
+}));
+vi.mock('@/components/ai-usage/ai-usage-meter', () => ({
+ HeaderWithAiUsage: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+}));
+
+const { default: ShoppingProductPage } = await import('./page');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let container: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ gate.allowed = true;
+ getShoppingProductDetail.mockReset();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+async function render() {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <ShoppingProductPage />
+ </NextIntlClientProvider>,
+ );
+ });
+ return container.textContent ?? '';
+}
+
+const line = {
+ promptId: 'q1',
+ promptText: 'lightweight 30L hiking backpack for women',
+ platform: 'chatgpt-shopping',
+ rank: null,
+ winner: {
+ title: 'Summit Daypack 30 W',
+ price: 110,
+ currency: 'USD',
+ rating: 4.8,
+ reviews: 2140,
+ merchant: 'summitgear.example',
+ image: null,
+ },
+ score: 41,
+ winnerScore: 88,
+ missing: ['women', 'lightweight'],
+};
+const detail: ShoppingProductDetail = {
+ product: {
+ id: 'p1',
+ title: 'Ridge 30L Backpack',
+ url: 'https://northwind.example/products/ridge-30',
+ productType: 'Backpacks',
+ brand: 'Northwind',
+ description: null,
+ image: null,
+ category: 'Bags > Hiking backpacks',
+ price: 119,
+ currency: 'USD',
+ inStock: true,
+ hasGtin: false,
+ },
+ readiness: { score: 48, missing: ['gtin', 'description'] },
+ shelves: [
+ line,
+ {
+ ...line,
+ promptId: 'q2',
+ promptText: 'durable daypack',
+ rank: 1,
+ winner: null,
+ winnerScore: null,
+ score: 60,
+ missing: [],
+ },
+ ],
+ focus: line,
+ comparison: [
+ {
+ key: 'score',
+ you: '41',
+ winner: '88',
+ state: 'missing',
+ note: { key: 'missingWords', values: { words: 'women, lightweight' } },
+ },
+ { key: 'price', you: '$119', winner: '$110', state: 'match', note: { key: 'close' } },
+ { key: 'gtin', you: null, winner: null, state: 'missing' },
+ ],
+ ai: { visits: 4, orders: 0, revenue: null, currency: null },
+};
+
+describe('ShoppingProductPage', () => {
+ it('shows the product, where it shows, and why AI picked another one', async () => {
+ getShoppingProductDetail.mockResolvedValue(detail);
+ const text = await render();
+ expect(getShoppingProductDetail).toHaveBeenCalledWith('b1', 'p1', { datePreset: '30d' });
+ expect(text).toContain('Ridge 30L Backpack');
+ expect(text).toContain('$119 · Hiking backpacks · On 1 of 2 shelves · Readiness 48');
+ expect(text).toContain(
+ '“lightweight 30L hiking backpack for women” · ChatGPT Shopping picked Summit Daypack 30 W',
+ );
+ const rows = [...container.querySelectorAll('table')[0].querySelectorAll('tbody tr')].map(
+ (tr) => [...tr.querySelectorAll('td')].map((td) => td.textContent),
+ );
+ // Each row's state in words too, beside its icon.
+ expect(rows).toEqual([
+ ['Match with the question, missing', '41', '88', 'Missing: women, lightweight'],
+ ['Price, in place', '$119', '$110', 'Close'],
+ ['GTIN in the feed, missing', '✕', '—', ''],
+ ]);
+ expect(
+ [...container.querySelectorAll('table')[0].querySelectorAll('.sr-only')].map(
+ (span) => span.textContent,
+ ),
+ ).toEqual([', missing', ', in place', ', missing']);
+ expect(text).toContain('Not on the shelf');
+ expect(text).toContain('Missing: a GTIN (−20)');
+ expect(container.querySelector('a[href="/dashboard/shopping?tab=products"]')).not.toBeNull();
+ });
+
+ it('says when the product is gone, or locked', async () => {
+ getShoppingProductDetail.mockResolvedValue(null);
+ expect(await render()).toContain("This product isn't in your catalog anymore.");
+ gate.allowed = false;
+ expect(await render()).toContain('Product Visibility comes with the Growth plan.');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.tsx
new file mode 100644
index 000000000..2c9d79284
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.tsx
@@ -0,0 +1,88 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import { useParams } from 'next/navigation';
+import { useTranslations } from 'next-intl';
+import { ArrowLeft } from 'lucide-react';
+import { Link } from '@/i18n/navigation';
+import { Skeleton } from '@/components/ui/skeleton';
+import { useFeatureGate } from '@/hooks/use-feature-gate';
+import { getShoppingProductDetail, type ShoppingProductDetail } from '@/lib/actions/shopping';
+import { useBrandStore } from '@/stores/use-brand-store';
+import { ProductDetailView } from '../../_product-detail';
+
+/**
+ * A product's page in Product Visibility (ECOM-011): where it stands on the
+ * AI shelves of the questions it belongs on, and "Why not your product?":
+ * it beside the product AI picked for the question it's missing most, row
+ * by row, with its readiness and its AI visits and orders.
+ */
+export default function ShoppingProductPage() {
+ const t = useTranslations('shopping.detail');
+ const { productId } = useParams<{ productId: string }>();
+ const activeBrandId = useBrandStore((s) => s.activeBrandId);
+ const { canUse } = useFeatureGate();
+ const [read, setRead] = useState<{
+ key: string;
+ detail: ShoppingProductDetail | null | 'failed';
+ } | null>(null);
+ const key = `${activeBrandId}:${productId}`;
+
+ useEffect(() => {
+ if (!activeBrandId || !productId) return;
+ let cancelled = false;
+ getShoppingProductDetail(activeBrandId, productId, { datePreset: '30d' })
+ .then((detail) => {
+ if (!cancelled) setRead({ key, detail });
+ })
+ .catch((err) => {
+ console.error('Failed to read the product:', err);
+ if (!cancelled) setRead({ key, detail: 'failed' });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [activeBrandId, productId, key]);
+
+ const back = (
+ <Link
+ href="/dashboard/shopping?tab=products"
+ className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground"
+ >
+ <ArrowLeft className="h-4 w-4" aria-hidden />
+ {t('back')}
+ </Link>
+ );
+ const detail = read?.key === key ? read.detail : undefined;
+
+ if (!canUse('shopping_analytics') || detail === null || detail === 'failed') {
+ return (
+ <div className="space-y-6">
+ {back}
+ <p className="rounded-lg border border-dashed px-4 py-10 text-center text-sm text-muted-foreground">
+ {!canUse('shopping_analytics')
+ ? t('locked')
+ : detail === 'failed'
+ ? t('failed')
+ : t('notFound')}
+ </p>
+ </div>
+ );
+ }
+ if (detail === undefined) {
+ return (
+ <div className="space-y-6">
+ {back}
+ <Skeleton className="h-24 w-full" />
+ <Skeleton className="h-[320px] w-full" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ {back}
+ <ProductDetailView detail={detail} />
+ </div>
+ );
+}
diff --git a/web/src/lib/actions/shopping-product-detail.test.ts b/web/src/lib/actions/shopping-product-detail.test.ts
new file mode 100644
index 000000000..8ea53a32a
--- /dev/null
+++ b/web/src/lib/actions/shopping-product-detail.test.ts
@@ -0,0 +1,142 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/** A product's page read (ECOM-011). */
+
+const BRAND = '33333333-3333-3333-3333-333333333333';
+const PRODUCT = '11111111-0000-0000-0000-000000000001';
+
+let tables: Record<string, Record<string, unknown>[]>;
+let rpcArgs: Record<string, unknown>[];
+// The id lists the catalog reads filtered by, as [table, column, the ids].
+let byIds: [string, string, unknown[]][];
+
+function query(table: string) {
+ let range: [number, number] | undefined;
+ let single = false;
+ const q = {
+ select: () => q,
+ eq: () => q,
+ is: () => q,
+ in: (column: string, values: unknown[]) => (byIds.push([table, column, values]), q),
+ not: () => q,
+ gte: () => q,
+ lte: () => q,
+ or: () => q,
+ order: () => q,
+ maybeSingle: () => ((single = true), q),
+ range: (from: number, to: number) => ((range = [from, to]), q),
+ then: (resolve: (value: unknown) => void) => {
+ const rows = tables[table] ?? [];
+ if (single) return resolve({ data: rows[0] ?? null, error: null });
+ const [from, to] = 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,
+ rpc: async (_name: string, args: Record<string, unknown>) => {
+ rpcArgs.push(args);
+ return {
+ data: [{ product_id: PRODUCT, ai_visits: 4, orders: 0, revenue: null, currency: null }],
+ error: null,
+ };
+ },
+ })),
+}));
+
+const { getShoppingProductDetail } = await import('./shopping');
+
+beforeEach(() => {
+ tables = {};
+ rpcArgs = [];
+ byIds = [];
+});
+
+const card = (over: Record<string, unknown>) => ({
+ prompt_result_id: 'r1',
+ position: 0,
+ created_at: '2026-10-27T08:00:00Z',
+ platform: 'chatgpt-shopping',
+ product_title: 'Summit Daypack 30 W Hiking Backpack',
+ price_amount: 110,
+ price_currency: 'USD',
+ rating: 4.8,
+ review_count: 2140,
+ merchant_domain: 'summitgear.example',
+ image_url: null,
+ matched_brand_role: 'competitor',
+ catalog_product_id: null,
+ prompt_results: {
+ search_queries: [{ query: 'women hiking backpack' }],
+ prompt: { id: 'q1', text: 'lightweight 30L hiking backpack for women' },
+ },
+ ...over,
+});
+
+describe('getShoppingProductDetail', () => {
+ it("refuses ids that aren't ids, and reads a product not in the catalog as none", async () => {
+ await expect(getShoppingProductDetail(BRAND, 'nope', { datePreset: '30d' })).rejects.toThrow(
+ 'invalid',
+ );
+ expect(await getShoppingProductDetail(BRAND, PRODUCT, { datePreset: '30d' })).toBeNull();
+ });
+
+ it('explains the shelf it misses beside its winner, with its rating as the answers showed it', async () => {
+ tables.catalog_products = [
+ {
+ id: PRODUCT,
+ title: 'Ridge 30L Backpack',
+ url: null,
+ product_type: 'Backpacks',
+ product_brand: 'Northwind',
+ description: null,
+ },
+ ];
+ tables.catalog_product_categories = [
+ { product_id: PRODUCT, category: { name: 'Hiking backpacks' } },
+ ];
+ tables.brand_domains = [{ domain: 'northwind.example' }];
+ tables.prompt_result_shopping_cards = [
+ card({}),
+ card({
+ prompt_result_id: 'r0',
+ created_at: '2026-10-20T08:00:00Z',
+ product_title: 'Ridge 30L Backpack',
+ matched_brand_role: 'own',
+ catalog_product_id: PRODUCT,
+ rating: 4.5,
+ review_count: 86,
+ }),
+ ];
+ const detail = await getShoppingProductDetail(BRAND, PRODUCT, { datePreset: '30d' });
+ expect(detail?.focus).toMatchObject({
+ promptId: 'q1',
+ rank: null,
+ winner: { title: 'Summit Daypack 30 W Hiking Backpack' },
+ });
+ expect(detail?.comparison.find((row) => row.key === 'rating')).toMatchObject({
+ you: '4.5 · 86',
+ winner: '4.8 · 2,140',
+ state: 'weaker',
+ });
+ expect(detail?.comparison.find((row) => row.key === 'merchant')).toMatchObject({
+ you: 'northwind.example',
+ winner: 'summitgear.example',
+ });
+ expect(detail?.ai).toEqual({ visits: 4, orders: 0, revenue: null, currency: null });
+ // Only this product: its catalog rows, and its own AI visits and orders.
+ expect(byIds.filter(([table]) => table.startsWith('catalog_'))).toEqual([
+ ['catalog_products', 'id', [PRODUCT]],
+ ['catalog_variants', 'product_id', [PRODUCT]],
+ ['catalog_images', 'product_id', [PRODUCT]],
+ ['catalog_product_categories', 'product_id', [PRODUCT]],
+ ]);
+ expect(rpcArgs).toEqual([
+ { p_brand_id: BRAND, p_from: expect.any(String), p_product_id: PRODUCT },
+ ]);
+ });
+});
diff --git a/web/src/lib/actions/shopping.ts b/web/src/lib/actions/shopping.ts
index d8162426d..ed0dcf563 100644
--- a/web/src/lib/actions/shopping.ts
+++ b/web/src/lib/actions/shopping.ts
@@ -18,8 +18,18 @@ import {
type ShelfStats,
} from '@/lib/shopping/shelf';
import { categoryRows, type CategoryCardRow, type CategoryRow } from '@/lib/shopping/categories';
+import {
+ comparison,
+ focusShelf,
+ productShelves,
+ type ComparisonRow,
+ type DetailCard,
+ type ProductShelfLine,
+} from '@/lib/shopping/product-detail';
+import { priceText } from '@/lib/shopping/price';
import {
productRows,
+ readiness,
type CatalogProductRow,
type ProductAiStats,
type ProductCardRow,
@@ -1635,3 +1645,124 @@ export async function getShoppingCategories(
},
);
}
+
+// ── A product's page (Product Visibility, ECOM-011) ───────────────────────────
+
+export interface ShoppingProductDetail {
+ product: CatalogProductRow;
+ readiness: ReturnType<typeof readiness>;
+ /** The questions it belongs on, each channel's latest shelf. */
+ shelves: ProductShelfLine[];
+ /** The shelf "Why not your product?" explains, and its rows. */
+ focus: ProductShelfLine | null;
+ comparison: ComparisonRow[];
+ /** AI visits to its page and the orders they led to, over the window (00361). */
+ ai: { visits: number; orders: number; revenue: number | null; currency: string | null };
+}
+
+/** A product of the brand's catalog, on the AI shelves of the questions it belongs on. Null when it isn't the brand's. */
+export async function getShoppingProductDetail(
+ brandId: string,
+ productId: string,
+ filters: ShoppingFilters,
+): Promise<ShoppingProductDetail | null> {
+ if (!z.guid().safeParse(brandId).success || !z.guid().safeParse(productId).success) {
+ throw new Error('invalid');
+ }
+ const supabase = await createClient();
+ const { from } = resolveDateRange(filters);
+ const [[product], cards, stats, domain] = await Promise.all([
+ readCatalogProducts(supabase, brandId, [productId]),
+ fetchAllCards<{
+ prompt_result_id: string;
+ position: number;
+ created_at: string;
+ platform: string;
+ product_title: string | null;
+ price_amount: number | null;
+ price_currency: string | null;
+ rating: number | null;
+ review_count: number | null;
+ merchant_domain: string | null;
+ image_url: string | null;
+ matched_brand_role: string;
+ catalog_product_id: string | null;
+ prompt_results: {
+ search_queries: unknown;
+ prompt: { id: string; text: string } | null;
+ } | null;
+ }>(() =>
+ cardsInWindow(
+ supabase,
+ brandId,
+ filters,
+ 'prompt_result_id, position, created_at, platform, product_title, price_amount, price_currency, rating, review_count, merchant_domain, image_url, matched_brand_role, catalog_product_id, prompt_results:prompt_result_id ( search_queries, prompt:prompt_id ( id, text ) )',
+ ),
+ ),
+ // Its own row only (00361), none without AI visits or orders.
+ supabase.rpc('catalog_product_ai_stats', {
+ p_brand_id: brandId,
+ p_from: from ?? daysAgoIso(90),
+ p_product_id: productId,
+ }),
+ supabase
+ .from('brand_domains')
+ .select('domain')
+ .eq('brand_id', brandId)
+ .eq('is_primary', true)
+ .maybeSingle(),
+ ]);
+ if (!product) return null;
+ if (stats.error) throw new Error(stats.error.message);
+
+ const detailCards: DetailCard[] = cards.flatMap((card) => {
+ const prompt = card.prompt_results?.prompt;
+ if (!prompt || !card.product_title?.trim()) return [];
+ return [
+ {
+ promptId: prompt.id,
+ promptText: prompt.text,
+ platform: card.platform,
+ promptResultId: card.prompt_result_id,
+ at: card.created_at,
+ position: card.position,
+ title: card.product_title.trim(),
+ price: card.price_amount,
+ currency: card.price_currency,
+ rating: card.rating,
+ reviews: card.review_count,
+ merchant: card.merchant_domain,
+ image: card.image_url,
+ role: card.matched_brand_role,
+ productId: card.catalog_product_id,
+ searches: searchesOf(card.prompt_results?.search_queries),
+ },
+ ];
+ });
+ // How the answers showed it, its latest card first: its rating there.
+ const shown = detailCards
+ .filter((card) => card.productId === productId)
+ .sort((a, b) => (a.at < b.at ? 1 : -1))[0];
+ const shelves = productShelves(product, detailCards);
+ const focus = focusShelf(shelves);
+ const ai = (stats.data ?? []).find((row) => row.product_id === productId);
+ return {
+ product,
+ readiness: readiness(product),
+ shelves,
+ focus,
+ comparison: focus
+ ? comparison(product, focus, {
+ own: shown ? { rating: shown.rating, reviews: shown.reviews } : null,
+ price: priceText,
+ storeDomain: domain.data?.domain ?? null,
+ })
+ : [],
+ ai: {
+ visits: Number(ai?.ai_visits ?? 0),
+ orders: Number(ai?.orders ?? 0),
+ revenue: ai?.revenue === null || ai?.revenue === undefined ? null : Number(ai.revenue),
+ currency: ai?.currency ?? null,
+ },
+ };
+}
diff --git a/web/src/lib/shopping/product-detail.test.ts b/web/src/lib/shopping/product-detail.test.ts
new file mode 100644
index 000000000..5d784ac6a
--- /dev/null
+++ b/web/src/lib/shopping/product-detail.test.ts
@@ -0,0 +1,177 @@
+import { describe, expect, it } from 'vitest';
+import {
+ comparison,
+ focusShelf,
+ productShelves,
+ productText,
+ type DetailCard,
+} from './product-detail';
+import { priceText } from './price';
+import type { CatalogProductRow } from './products';
+
+/** A product's page: its shelves and "Why not your product?" (ECOM-011). */
+
+const product: CatalogProductRow = {
+ id: 'ridge',
+ title: 'Ridge 30L Backpack',
+ url: 'https://northwind.example/products/ridge-30',
+ productType: 'Backpacks',
+ brand: 'Northwind',
+ description:
+ 'Built for everyday adventures with tough fabric and lots of pockets, our pack has been a favourite since 1998 for hikers who love the outdoors and want gear that lasts season after season.',
+ image: null,
+ category: 'Bags > Hiking backpacks',
+ price: 119,
+ currency: 'USD',
+ inStock: true,
+ hasGtin: false,
+};
+
+const card = (over: Partial<DetailCard>): DetailCard => ({
+ promptId: 'q1',
+ promptText: 'lightweight 30L hiking backpack for women',
+ platform: 'chatgpt-shopping',
+ promptResultId: 'r1',
+ at: '2026-10-27T08:00:00Z',
+ position: 0,
+ title: 'Summit Daypack 30 W Lightweight Hiking Backpack for Women',
+ price: 110,
+ currency: 'USD',
+ rating: 4.8,
+ reviews: 2140,
+ merchant: 'summitgear.example',
+ image: null,
+ role: 'competitor',
+ productId: null,
+ searches: ['women hiking backpack lightweight'],
+ ...over,
+});
+
+const cards = [
+ card({}),
+ card({ position: 1, title: 'TrailCo Lite 28', price: 95, rating: 4.6, reviews: 300 }),
+ // An older answer with the product on it: not the latest shelf.
+ card({
+ promptResultId: 'r0',
+ at: '2026-10-20T08:00:00Z',
+ title: 'Ridge 30L Backpack',
+ role: 'own',
+ productId: 'ridge',
+ }),
+ // The product leads another question's shelf.
+ card({
+ promptId: 'q2',
+ promptText: 'durable 30 litre daypack',
+ promptResultId: 'r2',
+ title: 'Ridge 30L Backpack',
+ role: 'own',
+ productId: 'ridge',
+ rating: 4.5,
+ reviews: 86,
+ }),
+ card({
+ promptId: 'q2',
+ promptText: 'durable 30 litre daypack',
+ promptResultId: 'r2',
+ position: 1,
+ }),
+ // An unrelated question.
+ card({
+ promptId: 'q3',
+ promptText: 'best trail running shoes',
+ promptResultId: 'r3',
+ title: 'Summit Peak GTX',
+ }),
+];
+
+describe('productShelves', () => {
+ const lines = productShelves(product, cards);
+
+ it("lists the questions of the product's category and those it was on, not the others", () => {
+ expect(lines.map((line) => [line.promptId, line.rank])).toEqual(
+ expect.arrayContaining([
+ ['q1', null],
+ ['q2', 1],
+ ]),
+ );
+ expect(lines.some((line) => line.promptId === 'q3')).toBe(false);
+ });
+
+ it("names the shelf's winner when it isn't the product, with both scores and the missing words", () => {
+ const q1 = lines.find((line) => line.promptId === 'q1')!;
+ expect(q1.winner).toMatchObject({
+ title: 'Summit Daypack 30 W Lightweight Hiking Backpack for Women',
+ price: 110,
+ });
+ expect(q1.winnerScore).toBeGreaterThan(q1.score);
+ expect(q1.missing).toEqual(expect.arrayContaining(['lightweight', 'women']));
+ expect(lines.find((line) => line.promptId === 'q2')!.winner).toBeNull();
+ });
+
+ it('reads the title and the first 40 words of the description', () => {
+ expect(productText({ ...product, description: 'word '.repeat(60) }).split(' ')).toHaveLength(
+ 3 + 40,
+ );
+ expect(productText({ ...product, description: null })).toBe('Ridge 30L Backpack');
+ });
+});
+
+describe('focusShelf', () => {
+ it("explains the most relevant shelf it's missing, else the one it ranks lowest on", () => {
+ const lines = productShelves(product, cards);
+ expect(focusShelf(lines)?.promptId).toBe('q1');
+ const behind = [
+ { ...lines[0], rank: 2 },
+ { ...lines[0], promptId: 'x', rank: 4 },
+ ];
+ expect(focusShelf(behind)?.promptId).toBe('x');
+ expect(focusShelf([{ ...lines[0], rank: 1, winner: null }])).toBeNull();
+ });
+});
+
+describe('comparison', () => {
+ it('sets the product beside the winner, row by row', () => {
+ const q1 = productShelves(product, cards).find((line) => line.promptId === 'q1')!;
+ const rows = comparison(product, q1, {
+ own: { rating: 4.5, reviews: 86 },
+ price: priceText,
+ storeDomain: 'northwind.example',
+ });
+ expect(rows.map((row) => [row.key, row.you, row.winner, row.state, row.note?.key])).toEqual([
+ ['score', String(q1.score), String(q1.winnerScore), 'missing', 'missingWords'],
+ ['price', '$119', '$110', 'match', 'close'],
+ ['rating', '4.5 · 86', '4.8 · 2,140', 'weaker', undefined],
+ ['firstWords', null, null, 'missing', 'firstWords'],
+ ['gtin', null, null, 'missing', undefined],
+ ['photo', null, null, 'missing', undefined],
+ ['stock', null, null, 'match', undefined],
+ ['merchant', 'northwind.example', 'summitgear.example', 'info', undefined],
+ ]);
+ });
+
+ it('says how much higher or lower the price is, and a rating the answers never showed', () => {
+ const q1 = productShelves(product, cards).find((line) => line.promptId === 'q1')!;
+ const pricier = comparison({ ...product, price: 150 }, q1, {
+ own: null,
+ price: priceText,
+ storeDomain: null,
+ });
+ expect(pricier.find((row) => row.key === 'price')).toMatchObject({
+ state: 'weaker',
+ note: { key: 'higher', values: { percent: 36 } },
+ });
+ expect(pricier.find((row) => row.key === 'rating')).toMatchObject({
+ you: null,
+ state: 'missing',
+ });
+ const cheaper = comparison({ ...product, price: 80 }, q1, {
+ own: null,
+ price: priceText,
+ storeDomain: null,
+ });
+ expect(cheaper.find((row) => row.key === 'price')?.note).toEqual({
+ key: 'lower',
+ values: { percent: 27 },
+ });
+ });
+});
diff --git a/web/src/lib/shopping/product-detail.ts b/web/src/lib/shopping/product-detail.ts
new file mode 100644
index 000000000..914a4dee1
--- /dev/null
+++ b/web/src/lib/shopping/product-detail.ts
@@ -0,0 +1,257 @@
+import { categoryWords } from '@/lib/shopping/categories';
+import { matchScores, missingWords, queryTerms } from '@/lib/shopping/match-score';
+import {
+ FIRST_WORDS,
+ readiness,
+ type CatalogProductRow,
+ type ReadinessCheck,
+} from '@/lib/shopping/products';
+
+/**
+ * A product's page in Product Visibility (ECOM-011): the shopping questions
+ * it belongs on, where it stands on each one's latest shelf, and, for the
+ * one it's missing most, "Why not your product?": it beside the product AI
+ * picked, row by row, from what the catalog and the answers hold.
+ */
+
+/** A card of a shopping answer, as the product's page reads it. */
+export interface DetailCard {
+ promptId: string;
+ promptText: string;
+ platform: string;
+ promptResultId: string;
+ at: string;
+ position: number;
+ title: string;
+ price: number | null;
+ currency: string | null;
+ rating: number | null;
+ reviews: number | null;
+ merchant: string | null;
+ image: string | null;
+ role: string;
+ productId: string | null;
+ /** The searches AI ran for the answer (its fan-out). */
+ searches: readonly string[];
+}
+
+export interface ShelfProduct {
+ title: string;
+ price: number | null;
+ currency: string | null;
+ rating: number | null;
+ reviews: number | null;
+ merchant: string | null;
+ image: string | null;
+}
+
+/** The product on one question's shelf, on one channel. */
+export interface ProductShelfLine {
+ promptId: string;
+ promptText: string;
+ platform: string;
+ /** Its place on the latest shelf, from 1, or null when it isn't on it. */
+ rank: number | null;
+ /** The shelf's first product, when it isn't this one. */
+ winner: ShelfProduct | null;
+ /** Its keyword match with the question and AI's searches, 0–100 (Ansvisor estimate). */
+ score: number;
+ winnerScore: number | null;
+ /** The question's words the product's title and opening don't have. */
+ missing: string[];
+}
+
+/** A question is the product's at this score or more, when nothing else ties it to it. */
+export const RELEVANT_SCORE = 40;
+/** Questions a product's page lists at most. */
+export const MAX_LINES = 20;
+
+/** What the product says first: its title and its description's opening (ECOM-024). */
+export function productText(product: CatalogProductRow): string {
+ const opening = String(product.description ?? '')
+ .split(/\s+/)
+ .filter(Boolean)
+ .slice(0, FIRST_WORDS)
+ .join(' ');
+ return `${product.title} ${opening}`.trim();
+}
+
+/**
+ * The product's shelves: the questions of its category (its name in them),
+ * those it was on, and those its words match well enough, each channel's
+ * latest shelf, most relevant first.
+ */
+export function productShelves(
+ product: CatalogProductRow,
+ cards: readonly DetailCard[],
+): ProductShelfLine[] {
+ const category = product.category ? categoryWords(product.category.split('>').at(-1)!) : [];
+ const text = productText(product);
+ const shelves = new Map<string, DetailCard[]>();
+ for (const card of cards) {
+ const key = `${card.promptId}:${card.platform}`;
+ if (!shelves.has(key)) shelves.set(key, []);
+ shelves.get(key)!.push(card);
+ }
+ const lines: ProductShelfLine[] = [];
+ for (const shelf of shelves.values()) {
+ const first = shelf[0];
+ const latestRun = shelf.reduce((a, b) => (b.at > a.at ? b : a)).promptResultId;
+ const latest = shelf
+ .filter((card) => card.promptResultId === latestRun)
+ .sort((a, b) => a.position - b.position);
+ const terms = queryTerms(first.promptText, [...new Set(shelf.flatMap((c) => c.searches))]);
+ const others = latest.filter((card) => card.productId !== product.id);
+ const scores = matchScores(terms, [text, ...others.map((card) => card.title)]);
+ const at = latest.findIndex((card) => card.productId === product.id);
+ const appeared = shelf.some((card) => card.productId === product.id);
+ const promptWords = new Set(categoryWords(first.promptText));
+ const inCategory = category.length > 0 && category.every((word) => promptWords.has(word));
+ if (!appeared && !inCategory && scores[0] < RELEVANT_SCORE) continue;
+ const winnerCard = at === 0 ? null : latest[0];
+ lines.push({
+ promptId: first.promptId,
+ promptText: first.promptText,
+ platform: first.platform,
+ rank: at >= 0 ? at + 1 : null,
+ winner: winnerCard
+ ? {
+ title: winnerCard.title,
+ price: winnerCard.price,
+ currency: winnerCard.currency,
+ rating: winnerCard.rating,
+ reviews: winnerCard.reviews,
+ merchant: winnerCard.merchant,
+ image: winnerCard.image,
+ }
+ : null,
+ score: scores[0],
+ winnerScore: winnerCard ? (scores[1 + others.indexOf(winnerCard)] ?? null) : null,
+ missing: missingWords(terms, text),
+ });
+ }
+ return lines
+ .sort(
+ (a, b) =>
+ b.score - a.score ||
+ (a.rank ?? Infinity) - (b.rank ?? Infinity) ||
+ a.promptText.localeCompare(b.promptText),
+ )
+ .slice(0, MAX_LINES);
+}
+
+/** The shelf to explain: the most relevant one it's missing, else the one it ranks lowest on. */
+export function focusShelf(lines: readonly ProductShelfLine[]): ProductShelfLine | null {
+ const missing = lines.filter((line) => line.rank === null && line.winner);
+ if (missing.length) return missing[0];
+ const behind = lines
+ .filter((line) => line.rank !== null && line.rank > 1 && line.winner)
+ .sort((a, b) => (b.rank ?? 0) - (a.rank ?? 0));
+ return behind[0] ?? null;
+}
+
+/** ✓ the product matches, ✕ it's missing it, ↓ it's weaker, or just what each has. */
+export type ComparisonState = 'match' | 'missing' | 'weaker' | 'info';
+
+export interface ComparisonRow {
+ key: 'score' | 'price' | 'rating' | 'firstWords' | 'gtin' | 'photo' | 'stock' | 'merchant';
+ you: string | null;
+ winner: string | null;
+ state: ComparisonState;
+ /** Values for the row's note (en.json shopping.detail.notes). */
+ note?: { key: string; values?: Record<string, string | number> };
+}
+
+/** Prices this close are "close" (ECOM-011's "Close"). */
+const CLOSE_PRICE = 0.1;
+
+/**
+ * "Why not your product?": the product beside the shelf's winner, row by
+ * row. `own` is how the answers showed the product, for its rating; `price`
+ * formats a price as the page does.
+ */
+export function comparison(
+ product: CatalogProductRow,
+ line: ProductShelfLine,
+ {
+ own,
+ price,
+ storeDomain,
+ }: {
+ own: { rating: number | null; reviews: number | null } | null;
+ price: (value: number, currency: string | null) => string;
+ storeDomain: string | null;
+ },
+): ComparisonRow[] {
+ const winner = line.winner;
+ const rows: ComparisonRow[] = [];
+ rows.push({
+ key: 'score',
+ you: String(line.score),
+ winner: line.winnerScore === null ? null : String(line.winnerScore),
+ state:
+ line.winnerScore !== null && line.score < line.winnerScore
+ ? line.score < line.winnerScore / 2
+ ? 'missing'
+ : 'weaker'
+ : 'match',
+ note: line.missing.length
+ ? { key: 'missingWords', values: { words: line.missing.slice(0, 6).join(', ') } }
+ : undefined,
+ });
+ if (product.price !== null || winner?.price !== null) {
+ const you = product.price;
+ const them = winner?.price ?? null;
+ const gap = you !== null && them !== null && them > 0 ? (you - them) / them : null;
+ rows.push({
+ key: 'price',
+ you: you === null ? null : price(you, product.currency),
+ winner: them === null ? null : price(them, winner?.currency ?? null),
+ state: gap === null ? 'info' : gap > CLOSE_PRICE ? 'weaker' : 'match',
+ note:
+ gap === null
+ ? undefined
+ : Math.abs(gap) <= CLOSE_PRICE
+ ? { key: 'close' }
+ : gap > 0
+ ? { key: 'higher', values: { percent: Math.round(gap * 100) } }
+ : { key: 'lower', values: { percent: Math.round(-gap * 100) } },
+ });
+ }
+ const rating = (r: number | null, n: number | null) =>
+ r === null ? null : n ? `${r.toFixed(1)} · ${n.toLocaleString('en-US')}` : r.toFixed(1);
+ rows.push({
+ key: 'rating',
+ you: rating(own?.rating ?? null, own?.reviews ?? null),
+ winner: rating(winner?.rating ?? null, winner?.reviews ?? null),
+ state:
+ own?.rating === null || own?.rating === undefined
+ ? winner?.rating
+ ? 'missing'
+ : 'info'
+ : winner?.rating && own.rating < winner.rating
+ ? 'weaker'
+ : 'match',
+ });
+ const ready = readiness(product);
+ const has = (check: ReadinessCheck) => !ready.missing.includes(check);
+ rows.push({
+ key: 'firstWords',
+ you: null,
+ winner: null,
+ state: has('typeFirst') ? 'match' : 'missing',
+ note: { key: 'firstWords' },
+ });
+ rows.push({ key: 'gtin', you: null, winner: null, state: has('gtin') ? 'match' : 'missing' });
+ rows.push({ key: 'photo', you: null, winner: null, state: has('image') ? 'match' : 'missing' });
+ rows.push({ key: 'stock', you: null, winner: null, state: has('inStock') ? 'match' : 'missing' });
+ if (winner?.merchant) {
+ rows.push({
+ key: 'merchant',
+ you: storeDomain,
+ winner: winner.merchant,
+ state: 'info',
+ });
+ }
+ return rows;
+}