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): score how ready the shop is for AI shopping, channel by channel and check by check (Product Visibility, part 8) (#1643)
Cihan456836e7e37e
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 226e3d00b..0c1b8171f 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -8000,6 +8000,91 @@"trends": "Trends","failed": "Couldn't read the shelves right now. The other tabs still work; try again in a moment."},+ "readiness": {+ "title": "AI shopping readiness",+ "lead": "What Ansvisor can read of your catalog, your feed and the answers. Each check says where its fix starts.",+ "channelsLabel": "AI shopping channels",+ "market": {+ "us": "Market: United States. In the US, ChatGPT picks products from OpenAI's own product index, built from feeds.",+ "europe": "Market: Europe. In Europe, ChatGPT still takes products from Google Shopping, so your Merchant Center feed decides ChatGPT too."+ },+ "channels": {+ "showing": "Showing your products",+ "notShowing": "Tracked, yours not shown",+ "notTracked": "Not tracked"+ },+ "sources": {+ "chatgpt_us": "OpenAI product index",+ "chatgpt_europe": "Google Shopping · via Merchant Center",+ "google-aio": "Via Merchant Center",+ "google-aimode": "Google Shopping Graph",+ "gemini-web": "Google Shopping Graph",+ "copilot-web": "Microsoft Merchant Center"+ },+ "view": "View products",+ "connect": "Connect",+ "unread": {+ "sources": "Couldn't read your catalog sources right now, so the score waits until they can be. Try again in a moment.",+ "products": "Couldn't read your catalog's products right now, so their checks and the score wait until they can be. Try again in a moment."+ },+ "checks": {+ "catalog": {+ "title": "Catalog connected",+ "pass": "{count, plural, one {# product} other {# products}} from your feed, file or store.",+ "fail": "Connect your catalog: Product Visibility counts your products against it.",+ "unknown": "Couldn't read your catalog sources right now."+ },+ "merchantCenter": {+ "title": "Google Merchant Center feed connected",+ "pass": "Feeds Google AI Overviews and AI Mode shopping results.",+ "warn": "Connect it to feed Google AI Overviews and AI Mode shopping results.",+ "fail": "In Europe it decides ChatGPT too: connect it.",+ "unknown": "Couldn't read your catalog sources right now."+ },+ "openAiIndex": {+ "title": "Catalog in OpenAI's product index",+ "pass": "You send OpenAI a direct product feed.",+ "warn": "Found in ChatGPT's answers, source unknown. A direct feed or Shopify is the safer way in.",+ "fail": "Not found in tracked answers. Send OpenAI a direct product feed, or connect a Shopify store."+ },+ "verifiedSeller": {+ "title": "Verified seller in ChatGPT · unknown",+ "unknown": "Shops without it can be left out of results. How OpenAI grants it isn't public yet; a direct feed is the best bet."+ },+ "firstWords": {+ "title": "First 40 words of descriptions{count, plural, =0 {} other { · # products}}",+ "pass": "Every description says what the product is in its first 40 words.",+ "warn": "ChatGPT reads about 40 words. These don't say what the product is in them.",+ "fail": "ChatGPT reads about 40 words. These don't say what the product is in them."+ },+ "feedFields": {+ "title": "Feed fields complete · {percent}%",+ "pass": "GTIN, photo, price, brand and category on almost every product.",+ "warn": "GTIN missing on {gtin}, photo on {image} products.",+ "fail": "GTIN missing on {gtin}, photo on {image} products."+ },+ "feedLinks": {+ "title": "Feed links tagged utm_medium=feed",+ "pass": "ChatGPT Shopping visits and sales are counted apart.",+ "warn": "{count, plural, one {# product link isn't} other {# product links aren't}} tagged. Add utm_source=chatgpt.com&utm_medium=feed to your feed's product links.",+ "fail": "Without it, ChatGPT Shopping sales can't be told apart from other AI visits. Add utm_source=chatgpt.com&utm_medium=feed to your feed's product links."+ },+ "wrongPrice": {+ "title": "{count, plural, =0 {Prices in AI answers match yours} other {Wrong price in AI answers · # products}}",+ "pass": "Every price AI showed for your products matches your catalog.",+ "fail": "AI shows {seen} for {product}, your price is {yours}."+ },+ "resellerCheaper": {+ "title": "{count, plural, =0 {No reseller cheaper than you} other {Reseller cheaper than you · # products}}",+ "pass": "AI links to no reseller selling your products for less.",+ "fail": "AI links to a reseller selling your product for less. See Shelf › Where AI sends shoppers."+ },+ "amazonShare": {+ "title": "Amazon's share in AI answers fell {from}% → {to}% this week",+ "warn": "Possibly OpenAI's “No Amazon” test. Your own store link matters more."+ }+ }+ },"plan": {"types": {"optimize_page": "Optimize page",@@ -8207,6 +8292,7 @@"lockedDescription": "Growth unlocks your AI shelf, your products and categories on it, where AI sends shoppers, and what it sells.","tabShelf": "Shelf","tabCategories": "Categories",+ "tabReadiness": "Readiness","tabProducts": "Products","tabMyProducts": "My Products","connectCatalog": "These are your products as AI shopping cards showed them. Add your product catalog (a product feed URL or a file you upload) in <link>Settings › Integrations</link>, and the Content Editor checks your product pages' price, GTIN and stock against it.",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_readiness.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_readiness.test.tsxnew file mode 100644index 000000000..4fa9de149--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_readiness.test.tsx@@ -0,0 +1,124 @@+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';++/** The Readiness tab (ECOM-015). */++vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => (+ <a href={href} {...rest}>+ {children}+ </a>+ ),+}));++const { ReadinessTab } = await import('./_readiness');++(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();+});++describe('ReadinessTab', () => {+ it("shows the market, each channel's state and source, and the scored checklist with its fixes", () => {+ const onProducts = vi.fn();+ act(() => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <ReadinessTab+ market="europe"+ tracked={['chatgpt-shopping', 'copilot-web']}+ ownSlots={new Map([['copilot-web', 3]])}+ score={64}+ items={[+ { key: 'catalog', state: 'pass', values: { count: 320 } },+ { key: 'merchantCenter', state: 'fail', action: 'settings' },+ { key: 'firstWords', state: 'fail', values: { count: 132 }, action: 'products' },+ {+ key: 'wrongPrice',+ state: 'fail',+ values: {+ count: 2,+ product: 'Trail Runner X',+ seen: 139,+ yours: 129,+ currency: 'USD',+ },+ action: 'products',+ },+ ]}+ onProducts={onProducts}+ />+ </NextIntlClientProvider>,+ );+ });+ const text = container.textContent ?? '';+ expect(text).toContain('Market: Europe.');+ expect(text).toContain(+ 'ChatGPT ShoppingTracked, yours not shownGoogle Shopping · via Merchant Center',+ );+ expect(text).toContain('Microsoft CopilotShowing your productsMicrosoft Merchant Center');+ expect(text).toContain('Google GeminiNot tracked');+ expect(text).toContain('AI shopping readiness64 / 100');+ expect(text).toContain('Catalog connected320 products from your feed, file or store.');+ expect(text).toContain('First 40 words of descriptions · 132 products');+ expect(text).toContain(+ 'Wrong price in AI answers · 2 productsAI shows $139 for Trail Runner X, your price is $129.',+ );+ expect(container.querySelector('a[href="/dashboard/settings/integrations"]')?.textContent).toBe(+ 'Connect',+ );+ act(() => (container.querySelector('button') as HTMLButtonElement).click());+ expect(onProducts).toHaveBeenCalled();+ });++ function renderTab(props: { loading?: boolean; unread?: ('sources' | 'products')[] }) {+ act(() => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <ReadinessTab+ market="us"+ tracked={[]}+ ownSlots={new Map()}+ score={80}+ items={[{ key: 'catalog', state: 'pass', values: { count: 320 } }]}+ onProducts={vi.fn()}+ {...props}+ />+ </NextIntlClientProvider>,+ );+ });+ return container.textContent ?? '';+ }++ it('waits for the sources and products it reads, without a score or checks', () => {+ const text = renderTab({ loading: true });+ expect(text).not.toContain('80 / 100');+ expect(text).not.toContain('Catalog connected');+ expect(container.querySelector('[aria-busy="true"]')).not.toBeNull();+ });++ it("says what couldn't be read, and shows no score without it", () => {+ const text = renderTab({ unread: ['products'] });+ expect(container.querySelector('[role="status"]')?.textContent).toBe(+ "Couldn't read your catalog's products right now, so their checks and the score wait until they can be. Try again in a moment.",+ );+ expect(text).not.toContain('80 / 100');+ expect(text).toContain('Catalog connected');+ expect(renderTab({})).toContain('AI shopping readiness80 / 100');+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_readiness.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_readiness.tsxnew file mode 100644index 000000000..e2c69ecbd--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_readiness.tsx@@ -0,0 +1,206 @@+'use client';++import type { ReactNode } from 'react';+import { useTranslations } from 'next-intl';+import { AlertTriangle, Check, HelpCircle, X } from 'lucide-react';+import { Link } from '@/i18n/navigation';+import { Button } from '@/components/ui/button';+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';+import { Skeleton } from '@/components/ui/skeleton';+import { AIProviderAvatar, resolveAIProvider } from '@/components/ai-provider-avatar';+import { PLATFORM_LABELS } from '@/config/platform-labels';+import { CATALOG_SETTINGS_PATH } from '@/lib/content/feed-match';+import { priceText } from '@/lib/shopping/price';+import type { ShoppingMarket } from '@/lib/shopping/markets';+import {+ READINESS_CHANNELS,+ channelState,+ type CheckState,+ type ReadinessItem,+} from '@/lib/shopping/readiness';+import { cn } from '@/lib/utils';++const STATE_ICON: Record<CheckState, ReactNode> = {+ pass: <Check className="h-4 w-4 text-emerald-600 dark:text-emerald-400" aria-hidden />,+ warn: <AlertTriangle className="h-4 w-4 text-amber-600 dark:text-amber-400" aria-hidden />,+ fail: <X className="h-4 w-4 text-red-600 dark:text-red-400" aria-hidden />,+ unknown: <HelpCircle className="h-4 w-4 text-muted-foreground" aria-hidden />,+};++const CHANNEL_TONE = {+ showing: 'bg-emerald-500/10 text-emerald-700 dark:text-emerald-400',+ notShowing: 'bg-amber-500/10 text-amber-700 dark:text-amber-400',+ notTracked: 'bg-muted text-muted-foreground',+} as const;++/** The values a check's copy reads, prices written as prices. */+function copyValues(item: ReadinessItem): Record<string, string | number> {+ const values = { ...(item.values ?? {}) };+ if (item.key === 'wrongPrice' && typeof values.seen === 'number') {+ const currency = String(values.currency ?? 'USD');+ values.seen = priceText(Number(values.seen), currency);+ values.yours = priceText(Number(values.yours), currency);+ }+ return values;+}++/** What the checklist reads that may fail: the catalog sources, and the catalog's products. */+export type ReadinessRead = 'sources' | 'products';++/**+ * Readiness (ECOM-015): the market the shop sells in and what it means for+ * ChatGPT, each AI shopping channel with whether it shows the brand's+ * products, and the checklist scored 0–100, each check with its fix's+ * starting point. `children` comes after: OpenAI's product index, in the US.+ *+ * The checklist waits for what it reads (`loading`). What couldn't be read+ * (`unread`) is said, and the score isn't shown: without those checks it+ * would be another score, not this one.+ */+export function ReadinessTab({+ market,+ tracked,+ ownSlots,+ score,+ items,+ loading = false,+ unread = [],+ onProducts,+ children,+}: {+ market: ShoppingMarket;+ /** The channels with shopping answers read. */+ tracked: readonly string[];+ /** The brand's product slots per channel. */+ ownSlots: ReadonlyMap<string, number>;+ score: number | null;+ items: ReadinessItem[];+ /** The catalog sources or products still being read. */+ loading?: boolean;+ /** What couldn't be read. */+ unread?: readonly ReadinessRead[];+ /** Opens the Products tab. */+ onProducts: () => void;+ children?: ReactNode;+}) {+ const t = useTranslations('shopping.readiness');+ return (+ <div className="space-y-6">+ <p className="rounded-lg border bg-muted/40 px-4 py-3 text-sm text-muted-foreground">+ {t(`market.${market}`)}+ </p>++ <section+ aria-label={t('channelsLabel')}+ className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5"+ >+ {READINESS_CHANNELS.map((platform) => {+ const state = channelState(platform, tracked, ownSlots);+ return (+ <Card key={platform}>+ <CardContent className="space-y-2 p-3">+ <p className="flex items-center gap-2 text-sm font-medium">+ <AIProviderAvatar+ provider={resolveAIProvider(platform, platform)}+ className="h-4 w-4"+ plain+ />+ {PLATFORM_LABELS[platform] ?? platform}+ </p>+ <span+ className={cn(+ 'inline-flex rounded-full px-2 py-0.5 text-xs font-medium',+ CHANNEL_TONE[state],+ )}+ >+ {t(`channels.${state}`)}+ </span>+ <p className="text-xs text-muted-foreground">+ {t(`sources.${platform === 'chatgpt-shopping' ? `chatgpt_${market}` : platform}`)}+ </p>+ </CardContent>+ </Card>+ );+ })}+ </section>++ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="flex flex-wrap items-baseline justify-between gap-2 text-base">+ {t('title')}+ {loading ? (+ <Skeleton className="h-8 w-20" />+ ) : (+ score !== null &&+ !unread.length && (+ <span className="text-2xl font-bold tabular-nums">+ {score}+ <span className="text-sm font-normal text-muted-foreground"> / 100</span>+ </span>+ )+ )}+ </CardTitle>+ <p className="text-sm text-muted-foreground">{t('lead')}</p>+ </CardHeader>+ <CardContent className="px-0">+ {!loading &&+ unread.map((read) => (+ <p+ key={read}+ role="status"+ className="mx-6 mb-3 flex items-start gap-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-200"+ >+ <AlertTriangle+ className="mt-0.5 h-4 w-4 shrink-0 text-amber-600 dark:text-amber-500"+ aria-hidden+ />+ {t(`unread.${read}`)}+ </p>+ ))}+ {loading ? (+ <div className="space-y-2 border-t px-6 py-3" aria-busy="true">+ {Array.from({ length: 5 }, (_, i) => (+ <Skeleton key={i} className="h-10 w-full" />+ ))}+ </div>+ ) : (+ <ul className="divide-y border-t">+ {items.map((item) => {+ const values = copyValues(item);+ return (+ <li key={item.key} className="flex items-start gap-3 px-6 py-3">+ <span className="mt-0.5 shrink-0">{STATE_ICON[item.state]}</span>+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium">{t(`checks.${item.key}.title`, values)}</p>+ <p className="text-xs text-muted-foreground">+ {t(`checks.${item.key}.${item.state}`, values)}+ </p>+ </div>+ {item.action === 'products' ? (+ <Button+ variant="outline"+ size="sm"+ className="h-7 shrink-0 text-xs"+ onClick={onProducts}+ >+ {t('view')}+ </Button>+ ) : item.action === 'settings' ? (+ <Link+ href={CATALOG_SETTINGS_PATH}+ className="inline-flex h-7 shrink-0 items-center rounded-md border px-3 text-xs font-medium hover:bg-muted"+ >+ {t('connect')}+ </Link>+ ) : null}+ </li>+ );+ })}+ </ul>+ )}+ </CardContent>+ </Card>+ {children}+ </div>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsxindex df66c1c01..ffac45d08 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx@@ -90,6 +90,7 @@ import { PLATFORM_LABELS } from '@/config/platform-labels';import { formatRegionDisplay } from '@/lib/region';import type { AmazonShareDropAlert } from '@/lib/shopping-amazon-share-alert';import type { CategoryRow } from '@/lib/shopping/categories';+import { readinessChecklist } from '@/lib/shopping/readiness';import { formatNumber } from '@/lib/format';import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';import { googleSourceStatus } from '@/lib/traffic-sources';@@ -98,6 +99,7 @@ import { CatalogNote } from './_catalog-note';import { ProductDataStrip, useProductSources } from './_data-strip';import { CategoriesTable } from './_categories-table';import { ProductsTable } from './_products-table';+import { ReadinessTab } from './_readiness';import { ShelfKpis, ShelfRows } from './_shelf';import { ShoppingMarketSwitch, useShoppingMarket } from './_market-switch';import { WhyDialog } from './_why-dialog';@@ -112,7 +114,7 @@ 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', 'categories', 'products', 'competitors'] as const;+const SHOPPING_TABS = ['shelf', 'categories', 'products', 'readiness', 'competitors'] as const;type ShoppingTab = (typeof SHOPPING_TABS)[number];// Theme tokens in globals.css ship as full oklch values; reference them@@ -266,7 +268,8 @@ export default function ShoppingPage() {// The Shelf (ECOM-006) and the Products table (ECOM-007) read once per// brand and filters, apart from the rest: neither waits for the other, nor- // for the older tables. The Products table reads when its tab is open.+ // for the older tables. The Products table reads when its tab, or+ // Readiness, is open.const readKey = `${activeBrandId}:${JSON.stringify(filters)}`;const canRead = !!activeBrandId && hasFullAccess && shoppingMarket.ready;// Null while it reads.@@ -278,7 +281,7 @@ export default function ShoppingPage() {'the shelves',) ?? null;const productsRead = useKeyedRead(- canRead && activeTab === 'products',+ canRead && (activeTab === 'products' || activeTab === 'readiness'),readKey,() => getShoppingProducts(activeBrandId!, filters),'the products',@@ -442,6 +445,7 @@ export default function ShoppingPage() {)}</TabsTrigger><TabsTrigger value="products">{t('tabProducts')}</TabsTrigger>+ <TabsTrigger value="readiness">{t('tabReadiness')}</TabsTrigger><TabsTrigger value="competitors">{t('tabCompetitors')}</TabsTrigger></TabsList>@@ -487,14 +491,6 @@ export default function ShoppingPage() {loading={loading}/></div>- {showOpenAiIndex && (- <OpenAiIndexCard- read={openAiIndex.read}- loading={openAiIndex.loading}- canManage={canManage}- onDirectFeedChange={openAiIndex.setDirectFeed}- />- )}</>) : (<UpgradeCard t={t} requiredPlan={requiredPlanFor('shopping_analytics')} />@@ -586,6 +582,50 @@ export default function ShoppingPage() {)}</TabsContent>+ <TabsContent value="readiness" className="space-y-6">+ {hasFullAccess ? (+ <ReadinessTab+ market={shoppingMarket.shown ?? 'us'}+ tracked={filterOpts.platforms}+ ownSlots={+ new Map(+ (shelf && shelf !== 'failed' ? shelf.stats.channels : []).map((c) => [+ c.platform,+ c.ownSlots,+ ]),+ )+ }+ {...readinessChecklist({+ market: shoppingMarket.shown ?? 'us',+ catalog: sources.catalog,+ products: catalogTable && catalogTable !== 'failed' ? catalogTable.rows : null,+ openAi: showOpenAiIndex ? openAiIndex.read : null,+ cheaperResellers: destinationsLoading ? null : destinations.priceAlerts.length,+ amazonDrop: amazonShareDropAlert+ ? { from: amazonShareDropAlert.fromShare, to: amazonShareDropAlert.toShare }+ : null,+ })}+ loading={!sources.loaded || productsLoading}+ unread={[+ ...(sources.loaded && sources.catalog === null ? (['sources'] as const) : []),+ ...(catalogTable === 'failed' ? (['products'] as const) : []),+ ]}+ onProducts={() => changeTab('products')}+ >+ {showOpenAiIndex && (+ <OpenAiIndexCard+ read={openAiIndex.read}+ loading={openAiIndex.loading}+ canManage={canManage}+ onDirectFeedChange={openAiIndex.setDirectFeed}+ />+ )}+ </ReadinessTab>+ ) : (+ <UpgradeCard t={t} requiredPlan={requiredPlanFor('shopping_analytics')} />+ )}+ </TabsContent>+<TabsContent value="competitors" className="space-y-6">{hasFullAccess ? (<>diff --git a/web/src/lib/actions/shopping-products.test.ts b/web/src/lib/actions/shopping-products.test.tsindex 63da4e234..ca4b8ddc9 100644--- a/web/src/lib/actions/shopping-products.test.ts+++ b/web/src/lib/actions/shopping-products.test.ts@@ -171,6 +171,12 @@ describe('getShoppingProducts', () => {inStock: true,hasGtin: true,});+ // Every variant's prices, for an answer's price to be checked against (ECOM-016).+ expect(p1.product.prices).toEqual([+ { price: 149, currency: 'USD' },+ { price: 129, currency: 'USD' },+ { price: 99, currency: 'USD' },+ ]);expect(p1).toMatchObject({shelves: 2,winRate: 0.5,diff --git a/web/src/lib/actions/shopping.ts b/web/src/lib/actions/shopping.tsindex 9d9705ee7..0e49daab0 100644--- a/web/src/lib/actions/shopping.ts+++ b/web/src/lib/actions/shopping.ts@@ -1336,13 +1336,16 @@ export async function getShoppingProducts(catalog_product_id: string;position: number;platform: string;+ price_amount: number | null;+ price_currency: string | null;+ created_at: string;prompt_results: { prompt_id: string } | null;}>(() =>cardsInWindow(supabase,brandId,filters,- 'catalog_product_id, position, platform, prompt_results:prompt_result_id ( prompt_id )',+ 'catalog_product_id, position, platform, price_amount, price_currency, created_at, prompt_results:prompt_result_id ( prompt_id )',).eq('matched_brand_role', 'own').not('catalog_product_id', 'is', null),@@ -1355,6 +1358,10 @@ export async function getShoppingProducts(productId: card.catalog_product_id,shelf: `${card.prompt_results?.prompt_id ?? '?'}:${card.platform}`,rank: card.position + 1,+ price: card.price_amount === null ? null : Number(card.price_amount),+ currency: card.price_currency,+ platform: card.platform,+ at: card.created_at,}));const aiStats: ProductAiStats[] = stats.map((row) => ({productId: row.product_id,@@ -1535,6 +1542,12 @@ async function readCatalogProducts(category: categoryOf.get(p.id) ?? null,price: priced[0] ? Number(priced[0].price) : null,currency: priced[0]?.currency ?? null,+ // Each variant's price and sale price, in or out of stock.+ prices: own.flatMap((v) =>+ [v.price, v.sale_price]+ .filter((price): price is number => price !== null)+ .map((price) => ({ price: Number(price), currency: v.currency })),+ ),inStock: stocked.length > 0,hasGtin: own.some((v) => !!v.gtin),};diff --git a/web/src/lib/shopping/products.test.ts b/web/src/lib/shopping/products.test.tsindex dc39cb845..679d371a9 100644--- a/web/src/lib/shopping/products.test.ts+++ b/web/src/lib/shopping/products.test.ts@@ -6,6 +6,7 @@ import {viewCounts,viewRows,type CatalogProductRow,+ type ProductCardRow,} from './products';/** Product Visibility's Products table (ECOM-007). */@@ -136,3 +137,63 @@ describe('productRows and the views', () => {expect(viewCounts(rows, 5000)).toEqual({ ...counts, all: 5000, never: 4997 });});});++describe('wrongPrice', () => {+ const card = (over: Partial<ProductCardRow>): ProductCardRow => ({+ productId: 'p',+ shelf: 'q1',+ rank: 1,+ currency: 'USD',+ ...over,+ });+ // On sale at $129; its other variant $159; $149 before the sale.+ const onSale = product({+ id: 'p',+ price: 129,+ currency: 'USD',+ prices: [+ { price: 149, currency: 'USD' },+ { price: 129, currency: 'USD' },+ { price: 159, currency: 'USD' },+ ],+ });++ it("flags a channel's latest answer whose price is more than 2% off each variant's, in the same currency", () => {+ const [row] = productRows(+ [onSale],+ [+ // Copilot's older answer was off; its latest shows the price before the sale.+ card({ platform: 'copilot-web', price: 99, at: '2026-10-20T08:00:00Z' }),+ card({ platform: 'copilot-web', price: 149, at: '2026-10-26T08:00:00Z' }),+ // Another currency can't be told.+ card({ platform: 'gemini', price: 99, currency: 'EUR', at: '2026-10-26T08:00:00Z' }),+ card({ platform: 'chatgpt-shopping', price: 139, at: '2026-10-25T08:00:00Z' }),+ ],+ [],+ );+ expect(row.wrongPrice).toEqual({ seen: 139, currency: 'USD', platform: 'chatgpt-shopping' });+ });++ it("doesn't flag an older answer's price, nor one a variant has", () => {+ const [row] = productRows(+ [onSale],+ [+ card({ platform: 'chatgpt-shopping', price: 139, at: '2026-10-20T08:00:00Z' }),+ card({ platform: 'chatgpt-shopping', price: 129.5, at: '2026-10-26T08:00:00Z' }),+ card({ platform: 'copilot-web', price: 159, at: '2026-10-26T08:00:00Z' }),+ // A channel whose latest answer shows no price says nothing.+ card({ platform: 'gemini', price: 99, at: '2026-10-20T08:00:00Z' }),+ card({ platform: 'gemini', price: null, at: '2026-10-26T08:00:00Z' }),+ ],+ [],+ );+ expect(row.wrongPrice).toBeNull();+ // Without its variants' prices, the product's own price.+ const [own] = productRows(+ [product({ id: 'p', price: 129 })],+ [card({ price: 149, platform: 'copilot-web' })],+ [],+ );+ expect(own.wrongPrice).toEqual({ seen: 149, currency: 'USD', platform: 'copilot-web' });+ });+});diff --git a/web/src/lib/shopping/products.ts b/web/src/lib/shopping/products.tsindex a60410188..f868440c9 100644--- a/web/src/lib/shopping/products.ts+++ b/web/src/lib/shopping/products.ts@@ -17,6 +17,11 @@ export interface CatalogProductRow {category: string | null;price: number | null;currency: string | null;+ /**+ * Every variant's price and sale price: an AI answer's price that is one+ * of them is right. Absent, `price` alone.+ */+ prices?: { price: number; currency: string | null }[];inStock: boolean;hasGtin: boolean;}@@ -28,6 +33,11 @@ export interface ProductCardRow {shelf: string;/** Its place on the shelf, from 1. */rank: number;+ /** The price the answer showed for it, on which channel, and when (ISO). */+ price?: number | null;+ currency?: string | null;+ platform?: string;+ at?: string;}/** AI visits and orders per product (00361). */@@ -113,6 +123,50 @@ export interface ProductRow {currency: string | null;readiness: number;missing: ReadinessCheck[];+ /**+ * A price a channel's latest AI answer shows for it that is none of its+ * variants' (more than PRICE_TOLERANCE off each, in the same currency);+ * null for none.+ */+ wrongPrice: { seen: number; currency: string | null; platform: string | null } | null;+}++/** An answer's price this far from the catalog's is wrong (ECOM-016). */+export const PRICE_TOLERANCE = 0.02;++function wrongPrice(+ product: CatalogProductRow,+ cards: readonly ProductCardRow[],+): ProductRow['wrongPrice'] {+ const known = (+ product.prices?.length+ ? product.prices+ : product.price === null+ ? []+ : [{ price: product.price, currency: product.currency }]+ ).filter((known) => known.price > 0);+ if (!known.length) return null;+ // Each channel's latest answer: an older one's price may have been right then.+ const latest = new Map<string, ProductCardRow>();+ for (const card of cards) {+ const channel = card.platform ?? '';+ const kept = latest.get(channel);+ if (!kept || (card.at ?? '') > (kept.at ?? '')) latest.set(channel, card);+ }+ for (const card of latest.values()) {+ if (typeof card.price !== 'number') continue;+ const seen = card.price;+ const same = known.filter(+ (known) => !card.currency || !known.currency || known.currency === card.currency,+ );+ if (+ same.length &&+ same.every((known) => Math.abs(seen - known.price) / known.price > PRICE_TOLERANCE)+ ) {+ return { seen, currency: card.currency ?? product.currency, platform: card.platform ?? null };+ }+ }+ return null;}/** The table's ready-made views (ECOM-007), the AI Traffic "Cited, not clicked" pattern. */@@ -124,15 +178,19 @@ export function productRows(cards: readonly ProductCardRow[],stats: readonly ProductAiStats[],): ProductRow[] {- const byProduct = new Map<string, { shelves: Set<string>; ranks: number[] }>();+ const byProduct = new Map<+ string,+ { shelves: Set<string>; ranks: number[]; cards: ProductCardRow[] }+ >();for (const card of cards) {let entry = byProduct.get(card.productId);if (!entry) {- entry = { shelves: new Set(), ranks: [] };+ entry = { shelves: new Set(), ranks: [], cards: [] };byProduct.set(card.productId, entry);}entry.shelves.add(card.shelf);entry.ranks.push(card.rank);+ entry.cards.push(card);}const statsOf = new Map(stats.map((s) => [s.productId, s]));return products.map((product) => {@@ -151,6 +209,7 @@ export function productRows(currency: ai?.currency ?? null,readiness: ready.score,missing: ready.missing,+ wrongPrice: wrongPrice(product, shown?.cards ?? []),};});}diff --git a/web/src/lib/shopping/readiness.test.ts b/web/src/lib/shopping/readiness.test.tsnew file mode 100644index 000000000..0e82b1bee--- /dev/null+++ b/web/src/lib/shopping/readiness.test.ts@@ -0,0 +1,153 @@+import { describe, expect, it } from 'vitest';+import type { CatalogSource } from '@/lib/catalog';+import { productRows, type CatalogProductRow } from './products';+import { channelState, readinessChecklist } from './readiness';++/** Product Visibility's Readiness (ECOM-015). */++const source = (kind: string): CatalogSource => ({+ id: kind,+ kind,+ format: 'auto',+ url: null,+ account: null,+ label: null,+ lastSyncedAt: null,+ lastStatus: 'ok',+ lastError: null,+ lastCounts: null,+ products: 2,+});++const product = (id: string, over: Partial<CatalogProductRow> = {}): CatalogProductRow => ({+ id,+ title: `Product ${id}`,+ url: `https://shop.example/products/${id}?utm_source=chatgpt.com&utm_medium=feed`,+ productType: 'Backpacks',+ brand: 'Northwind',+ description: `A 30 litre hiking backpack ${'with plenty of room for long days on the trail '.repeat(3)}`,+ image: 'https://cdn.example/x.jpg',+ category: 'Bags > Backpacks',+ price: 100,+ currency: 'USD',+ inStock: true,+ hasGtin: true,+ ...over,+});++describe('readinessChecklist', () => {+ it('passes a shop whose catalog, feed and prices are in order, and scores it 100', () => {+ const rows = productRows([product('a'), product('b')], [], []);+ const { score, items } = readinessChecklist({+ market: 'europe',+ catalog: [source('feed_url'), source('merchant_center')],+ products: rows,+ openAi: null,+ cheaperResellers: 0,+ amazonDrop: null,+ });+ expect(items.map((item) => [item.key, item.state])).toEqual([+ ['catalog', 'pass'],+ ['merchantCenter', 'pass'],+ ['firstWords', 'pass'],+ ['feedFields', 'pass'],+ ['feedLinks', 'pass'],+ ['wrongPrice', 'pass'],+ ['resellerCheaper', 'pass'],+ ]);+ expect(score).toBe(100);+ });++ it("says what's missing, a wrong price with its example, and leaves the unknown out of the score", () => {+ const rows = productRows(+ [+ product('a', {+ hasGtin: false,+ url: 'https://shop.example/products/a',+ description: 'Our story.',+ }),+ product('b'),+ ],+ [+ {+ productId: 'b',+ shelf: 'q:chatgpt-shopping',+ rank: 1,+ price: 139,+ currency: 'USD',+ platform: 'chatgpt-shopping',+ },+ ],+ [],+ );+ const { score, items } = readinessChecklist({+ market: 'us',+ catalog: [source('feed_url')],+ products: rows,+ openAi: { directFeed: false, ownCards: 3 },+ cheaperResellers: 2,+ amazonDrop: { from: 0.31, to: 0.04 },+ });+ const byKey = Object.fromEntries(items.map((item) => [item.key, item]));+ expect(byKey.merchantCenter).toMatchObject({ state: 'warn', action: 'settings' });+ expect(byKey.openAiIndex).toMatchObject({ state: 'warn', values: { status: 'found' } });+ expect(byKey.verifiedSeller.state).toBe('unknown');+ expect(byKey.firstWords).toMatchObject({+ state: 'fail',+ values: { count: 1 },+ action: 'products',+ });+ expect(byKey.feedFields).toMatchObject({+ state: 'fail',+ values: { percent: 50, gtin: 1, image: 0 },+ });+ expect(byKey.feedLinks).toMatchObject({ state: 'warn', values: { count: 1 } });+ expect(byKey.wrongPrice).toMatchObject({+ state: 'fail',+ values: { count: 1, product: 'Product b', seen: 139, yours: 100, currency: 'USD' },+ });+ expect(byKey.resellerCheaper).toMatchObject({ state: 'fail', values: { count: 2 } });+ expect(byKey.amazonShare).toMatchObject({ state: 'warn', values: { from: 31, to: 4 } });+ // pass 1 (catalog), warn ×4 (MC, OpenAI, feed links, Amazon), fail ×4: (1 + 2) / 9.+ expect(score).toBe(Math.round((100 * 3) / 9));+ });++ it('asks for the catalog when there is none, and lists no product checks without products', () => {+ const { items } = readinessChecklist({+ market: 'europe',+ catalog: [],+ products: null,+ openAi: null,+ cheaperResellers: null,+ amazonDrop: null,+ });+ expect(items.map((item) => [item.key, item.state, item.action])).toEqual([+ ['catalog', 'fail', 'settings'],+ ['merchantCenter', 'fail', 'settings'],+ ]);+ });++ it("doesn't fail Merchant Center on catalog sources that couldn't be read", () => {+ const { items } = readinessChecklist({+ market: 'europe',+ catalog: null,+ products: null,+ openAi: null,+ cheaperResellers: null,+ amazonDrop: null,+ });+ expect(items.map((item) => [item.key, item.state, item.action])).toEqual([+ ['catalog', 'unknown', 'settings'],+ ['merchantCenter', 'unknown', undefined],+ ]);+ });+});++describe('channelState', () => {+ it("reads a channel as showing the brand's products, tracked without them, or not tracked", () => {+ const own = new Map([['copilot-web', 4]]);+ expect(channelState('copilot-web', ['copilot-web', 'google-aimode'], own)).toBe('showing');+ expect(channelState('google-aimode', ['copilot-web', 'google-aimode'], own)).toBe('notShowing');+ expect(channelState('gemini-web', ['copilot-web'], own)).toBe('notTracked');+ });+});diff --git a/web/src/lib/shopping/readiness.ts b/web/src/lib/shopping/readiness.tsnew file mode 100644index 000000000..63b1cf1ad--- /dev/null+++ b/web/src/lib/shopping/readiness.ts@@ -0,0 +1,205 @@+import type { CatalogSource } from '@/lib/catalog';+import type { ShoppingMarket } from '@/lib/shopping/markets';+import { openAiIndexStatus, type OpenAiIndexRead } from '@/lib/shopping/openai-index';+import type { ProductRow, ReadinessCheck } from '@/lib/shopping/products';++/**+ * Product Visibility's Readiness (ECOM-015, spec §3.4 / §3.4b): how ready+ * the brand is for AI shopping, as a checklist scored 0–100. Only what+ * Ansvisor can read is checked: the catalog and its feed, Merchant Center,+ * OpenAI's product index in the US, the prices AI answers show, resellers+ * and Amazon's share. What it can't read yet (product page schema, return+ * policies, AI bots on product pages, colors as separate items) isn't+ * listed rather than guessed.+ */++export type CheckState = 'pass' | 'warn' | 'fail' | 'unknown';++export type ReadinessKey =+ | 'catalog'+ | 'merchantCenter'+ | 'openAiIndex'+ | 'verifiedSeller'+ | 'firstWords'+ | 'feedFields'+ | 'feedLinks'+ | 'wrongPrice'+ | 'resellerCheaper'+ | 'amazonShare';++export interface ReadinessItem {+ key: ReadinessKey;+ state: CheckState;+ /** Values for its title and line (en.json shopping.readiness.checks). */+ values?: Record<string, string | number>;+ /** Where its fix starts: the Products table, or Settings › Integrations. */+ action?: 'products' | 'settings';+}++export interface ReadinessInput {+ market: ShoppingMarket;+ /** The brand's catalog sources; null when they couldn't be read. */+ catalog: CatalogSource[] | null;+ /** The catalog's products; null without a catalog, or while unread. */+ products: ProductRow[] | null;+ /** OpenAI's product index (US); null when not read. */+ openAi: OpenAiIndexRead | null;+ /** Resellers cheaper than the brand in AI answers; null when not read. */+ cheaperResellers: number | null;+ /** Amazon's share of where AI sends shoppers, when it fell sharply. */+ amazonDrop: { from: number; to: number } | null;+}++const SCORE: Record<CheckState, number | null> = { pass: 1, warn: 0.5, fail: 0, unknown: null };++/** A share of products as a state: all pass, most warn, the rest fail. */+function shareState(bad: number, total: number, warnUpTo = 0.1): CheckState {+ if (bad === 0) return 'pass';+ return bad / total <= warnUpTo ? 'warn' : 'fail';+}++/** The fields AI shopping feeds need on each product. */+const FEED_FIELDS: readonly ReadinessCheck[] = ['gtin', 'image', 'price', 'brand', 'category'];++export function readinessChecklist(input: ReadinessInput): {+ score: number | null;+ items: ReadinessItem[];+} {+ const items: ReadinessItem[] = [];+ const catalog = input.catalog ?? [];+ const products = input.products ?? [];++ items.push({+ key: 'catalog',+ state: input.catalog === null ? 'unknown' : catalog.length ? 'pass' : 'fail',+ values: { count: products.length },+ action: catalog.length ? undefined : 'settings',+ });+ const merchantCenter = catalog.some((source) => source.kind === 'merchant_center');+ items.push({+ key: 'merchantCenter',+ // In Europe the Merchant Center feed decides ChatGPT too (§3.4b). Sources+ // that couldn't be read say nothing either way.+ state:+ input.catalog === null+ ? 'unknown'+ : merchantCenter+ ? 'pass'+ : input.market === 'europe'+ ? 'fail'+ : 'warn',+ action: merchantCenter || input.catalog === null ? undefined : 'settings',+ });+ if (input.market === 'us') {+ if (input.openAi) {+ const status = openAiIndexStatus(input.openAi);+ items.push({+ key: 'openAiIndex',+ state: status === 'direct_feed' ? 'pass' : status === 'found' ? 'warn' : 'fail',+ values: { status },+ });+ }+ items.push({ key: 'verifiedSeller', state: 'unknown' });+ }++ if (products.length) {+ const firstWords = products.filter((row) => row.missing.includes('typeFirst')).length;+ items.push({+ key: 'firstWords',+ state: shareState(firstWords, products.length),+ values: { count: firstWords },+ action: firstWords ? 'products' : undefined,+ });++ const incomplete = products.filter((row) =>+ FEED_FIELDS.some((field) => row.missing.includes(field)),+ ).length;+ const gtin = products.filter((row) => row.missing.includes('gtin')).length;+ const image = products.filter((row) => row.missing.includes('image')).length;+ const complete = Math.round(((products.length - incomplete) / products.length) * 100);+ items.push({+ key: 'feedFields',+ state: complete >= 90 ? 'pass' : complete >= 60 ? 'warn' : 'fail',+ values: { percent: complete, gtin, image },+ action: incomplete ? 'products' : undefined,+ });++ const linked = products.filter((row) => row.product.url);+ if (linked.length) {+ const untagged = linked.filter(+ (row) => !/[?&]utm_medium=feed(?:&|$)/i.test(row.product.url ?? ''),+ ).length;+ items.push({+ key: 'feedLinks',+ state: untagged === 0 ? 'pass' : untagged === linked.length ? 'fail' : 'warn',+ values: { count: untagged },+ });+ }++ const wrong = products.filter((row) => row.wrongPrice);+ const example = wrong[0];+ items.push({+ key: 'wrongPrice',+ state: wrong.length ? 'fail' : 'pass',+ values: example+ ? {+ count: wrong.length,+ product: example.product.title,+ seen: example.wrongPrice!.seen,+ yours: example.product.price ?? 0,+ currency: example.product.currency ?? example.wrongPrice!.currency ?? 'USD',+ }+ : { count: 0 },+ action: wrong.length ? 'products' : undefined,+ });+ }++ if (input.cheaperResellers !== null) {+ items.push({+ key: 'resellerCheaper',+ state: input.cheaperResellers ? 'fail' : 'pass',+ values: { count: input.cheaperResellers },+ });+ }+ if (input.amazonDrop) {+ items.push({+ key: 'amazonShare',+ state: 'warn',+ values: {+ from: Math.round(input.amazonDrop.from * 100),+ to: Math.round(input.amazonDrop.to * 100),+ },+ });+ }++ const scored = items+ .map((item) => SCORE[item.state])+ .filter((value): value is number => value !== null);+ return {+ score: scored.length+ ? Math.round((100 * scored.reduce((a, b) => a + b, 0)) / scored.length)+ : null,+ items,+ };+}++/** The AI channels a shop sells through, in the spec's priority order. */+export const READINESS_CHANNELS = [+ 'chatgpt-shopping',+ 'google-aio',+ 'google-aimode',+ 'gemini-web',+ 'copilot-web',+] as const;++export type ChannelState = 'showing' | 'notShowing' | 'notTracked';++/** A channel's state: the brand's products on its shelves, its shelves without them, or none read. */+export function channelState(+ platform: string,+ tracked: readonly string[],+ ownSlots: ReadonlyMap<string, number>,+): ChannelState {+ if ((ownSlots.get(platform) ?? 0) > 0) return 'showing';+ return tracked.includes(platform) ? 'notShowing' : 'notTracked';+}