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): offer "Why not you?" on a shelf the brand isn't on, and open the product on that shelf (Product Visibility, part 10) (#1645)
Cihan0278cf173e87
diff --git a/web/messages/en.json b/web/messages/en.jsonindex af69fabc4..732389d2a 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -7985,6 +7985,11 @@"you": "You","via": "via {place}","absent": "You're not on this shelf",+ "whyNot": {+ "yours": "Yours, not here",+ "link": "Why not you?",+ "linkLabel": "Why not you? Open {product} beside the product AI picked on this shelf"+ },"rank": "You: #{rank}","rankWeek": "You: #{rank} · {own} of {count} shelves this week","price": {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.test.tsxindex f01e2b024..35936e4c0 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.test.tsx@@ -9,8 +9,10 @@ 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>+ Link: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => (+ <a href={href} {...rest}>+ {children}+ </a>),}));@@ -148,6 +150,56 @@ describe('ShelfRows', () => {expect(text).toContain('$129');});+ it('offers "Why not you?" on a shelf the brand isn’t on, opening its product on that shelf', () => {+ const ridge = {+ product: {+ id: 'ridge',+ title: 'Ridge 30L Hiking Backpack',+ url: null,+ productType: null,+ brand: null,+ description: null,+ image: null,+ category: 'Bags > Hiking backpacks',+ price: 119,+ currency: 'USD',+ inStock: true,+ hasGtin: true,+ },+ shelves: 0,+ winRate: null,+ avgRank: null,+ aiVisits: 0,+ orders: 0,+ revenue: null,+ currency: null,+ readiness: 64,+ missing: [],+ wrongPrice: null,+ };+ const text = render(+ <ShelfRows+ shelf={shelf}+ platforms={['chatgpt-shopping']}+ platform="all"+ onPlatform={() => {}}+ products={[ridge]}+ />,+ );+ expect(text).toContain('Yours, not here');+ const link = container.querySelector('a[href^="/dashboard/shopping/products/ridge"]')!;+ expect(link.textContent).toBe('Why not you?');+ // Its name for a screen reader starts with what it shows.+ expect(link.getAttribute('aria-label')).toBe(+ 'Why not you? Open Ridge 30L Hiking Backpack beside the product AI picked on this shelf',+ );+ expect(link.getAttribute('href')).toBe(+ '/dashboard/shopping/products/ridge?prompt=p1&platform=chatgpt-shopping',+ );+ // Only where the brand is missing: the shoes shelf has its own.+ expect(container.querySelectorAll('a[href^="/dashboard/shopping/products/"]')).toHaveLength(1);+ });+it('filters by channel through the page, and by the price of the shelf', () => {const onPlatform = vi.fn();render(diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.tsxindex 077ce9341..963ff3d93 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.tsx@@ -2,7 +2,7 @@import { useState } from 'react';import { useTranslations } from 'next-intl';-import { ShoppingBag, Star } from 'lucide-react';+import { ChevronRight, ShoppingBag, Star } from 'lucide-react';import { Link } from '@/i18n/navigation';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';@@ -23,9 +23,11 @@ import { getPlatformName } from '@/lib/traffic-platforms';import { cn } from '@/lib/utils';import { priceText } from '@/lib/shopping/price';import type { ShoppingAiOrders, ShoppingShelf } from '@/lib/actions/shopping';+import type { ProductRow } from '@/lib/shopping/products';import {PRICE_BANDS,inPriceBand,+ whyNotYou,type PriceBand,type ShelfCard,type ShelfRow,@@ -254,8 +256,58 @@ function ProductCard({ card }: { card: ShelfCard }) {);}-function ShelfRowCard({ row }: { row: ShelfRow }) {+/**+ * "Why not you?" on a shelf the brand isn't on: its product the question+ * asks for most, greyed after the shelf's own, and the way to its page+ * opened on this shelf, beside the product AI picked.+ */+function WhyNotYouCard({ row, product }: { row: ShelfRow; product: ProductRow }) {+ const t = useTranslations('shopping.shelf.whyNot');+ const { product: p } = product;+ const href = `/dashboard/shopping/products/${p.id}?${new URLSearchParams({+ prompt: row.promptId,+ platform: row.platform,+ })}`;+ return (+ <li className="flex min-w-0 flex-col gap-1.5 rounded-lg border border-dashed bg-muted/30 p-2.5">+ <span className="text-xs font-semibold text-muted-foreground">{t('yours')}</span>+ <div className="grid h-20 place-items-center overflow-hidden rounded bg-muted/50 opacity-60 grayscale">+ {p.image ? (+ // eslint-disable-next-line @next/next/no-img-element -- catalog images from any host+ <img+ src={p.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 text-muted-foreground" title={p.title}>+ {p.title}+ </p>+ {p.price !== null && (+ <p className="text-[11px] text-muted-foreground tabular-nums">+ {priceText(p.price, p.currency)}+ </p>+ )}+ <Link+ href={href}+ className="mt-auto inline-flex items-center gap-0.5 text-xs font-medium text-primary hover:underline"+ aria-label={t('linkLabel', { product: p.title })}+ >+ {t('link')}+ <ChevronRight className="h-3 w-3" aria-hidden />+ </Link>+ </li>+ );+}++function ShelfRowCard({ row, products }: { row: ShelfRow; products: readonly ProductRow[] }) {const t = useTranslations('shopping.shelf');+ const missing = whyNotYou(row, products);return (<Card><CardContent className="space-y-3 p-4">@@ -295,9 +347,11 @@ function ShelfRowCard({ row }: { row: ShelfRow }) {</span></div><ol className="grid grid-cols-2 gap-2 sm:grid-cols-3 xl:grid-cols-6">- {row.cards.map((card) => (+ {/* Room for the brand's own beside a full shelf: its last card gives way. */}+ {(missing ? row.cards.slice(0, 5) : row.cards).map((card) => (<ProductCard key={card.rank} card={card} />))}+ {missing && <WhyNotYouCard row={row} product={missing} />}</ol></CardContent></Card>@@ -315,12 +369,15 @@ export function ShelfRows({platforms,platform,onPlatform,+ products = [],}: {shelf: ShoppingShelf | null;/** The channels with data, for the chips. */platforms: string[];platform: string;onPlatform: (platform: string) => void;+ /** The catalog's products (the Products table's rows), for "Why not you?". */+ products?: readonly ProductRow[];}) {const t = useTranslations('shopping.shelf');const [band, setBand] = useState<PriceBand>('all');@@ -388,7 +445,7 @@ export function ShelfRows({) : (<>{rows.slice(0, shown).map((row) => (- <ShelfRowCard key={row.key} row={row} />+ <ShelfRowCard key={row.key} row={row} products={products} />))}{rows.length > shown && (<div className="flex justify-center">diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsxindex ffac45d08..e6ee3f879 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx@@ -287,6 +287,14 @@ export default function ShoppingPage() {'the products',);const productsLoading = productsRead === undefined;+ // "Why not you?" on the Shelf needs the catalog's products, not the+ // window's numbers: read once per brand there, apart from the table.+ const shelfProducts = useKeyedRead(+ canRead && activeTab === 'shelf' && !productsRead,+ activeBrandId ?? '',+ () => getShoppingProducts(activeBrandId!, filters),+ 'the products for the shelf',+ );// Null for a brand without a catalog, and while it reads.const catalogTable: ShoppingProducts | null | 'failed' = productsRead ?? null;@@ -477,6 +485,13 @@ export default function ShoppingPage() {platforms={filterOpts.platforms}platform={platform}onPlatform={setPlatform}+ products={+ catalogTable && catalogTable !== 'failed'+ ? catalogTable.rows+ : shelfProducts && shelfProducts !== 'failed'+ ? shelfProducts.rows+ : undefined+ }/><h2 className="pt-2 text-sm font-semibold">{t('shelf.trends')}</h2><div className="grid gap-4 lg:grid-cols-2">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.tsxindex 8d63c0ba5..5704a8953 100644--- 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@@ -10,7 +10,12 @@ import type { ShoppingProductDetail } from '@/lib/actions/shopping';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' }) }));+// The query the page opens with: the Shelf's "Why not you?" names a shelf.+const query = vi.hoisted(() => ({ value: '' }));+vi.mock('next/navigation', () => ({+ useParams: () => ({ productId: 'p1' }),+ useSearchParams: () => new URLSearchParams(query.value),+}));vi.mock('@/i18n/navigation', () => ({Link: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => (<a href={href} {...rest}>@@ -49,6 +54,7 @@ let root: Root;beforeEach(() => {gate.allowed = true;getShoppingProductDetail.mockReset();+ query.value = '';container = document.createElement('div');document.body.appendChild(container);root = createRoot(container);@@ -136,7 +142,7 @@ 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(getShoppingProductDetail).toHaveBeenCalledWith('b1', 'p1', { datePreset: '30d' }, null);expect(text).toContain('Ridge 30L Backpack');expect(text).toContain('$119 · Hiking backpacks · On 1 of 2 shelves · Readiness 48');expect(text).toContain(@@ -164,6 +170,18 @@ describe('ShoppingProductPage', () => {expect(text).toContain('Send 4 actions to Action Center');});+ it('asks for the shelf the Shelf’s "Why not you?" opened it on', async () => {+ query.value = 'prompt=q9&platform=gemini-web';+ getShoppingProductDetail.mockResolvedValue(detail);+ await render();+ expect(getShoppingProductDetail).toHaveBeenCalledWith(+ 'b1',+ 'p1',+ { datePreset: '30d' },+ { promptId: 'q9', platform: 'gemini-web' },+ );+ });+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.");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.tsxindex bdcab0fb0..7087c1a05 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.tsx@@ -1,7 +1,7 @@'use client';import { useEffect, useState } from 'react';-import { useParams } from 'next/navigation';+import { useParams, useSearchParams } from 'next/navigation';import { useTranslations } from 'next-intl';import { ArrowLeft } from 'lucide-react';import { Link } from '@/i18n/navigation';@@ -20,18 +20,27 @@ import { ProductDetailView } from '../../_product-detail';export default function ShoppingProductPage() {const t = useTranslations('shopping.detail');const { productId } = useParams<{ productId: string }>();+ // Opened from the Shelf's "Why not you?": the shelf to explain first.+ const search = useSearchParams();+ const prompt = search.get('prompt');+ const platform = search.get('platform');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}`;+ const key = `${activeBrandId}:${productId}:${prompt ?? ''}:${platform ?? ''}`;useEffect(() => {if (!activeBrandId || !productId) return;let cancelled = false;- getShoppingProductDetail(activeBrandId, productId, { datePreset: '30d' })+ getShoppingProductDetail(+ activeBrandId,+ productId,+ { datePreset: '30d' },+ prompt ? { promptId: prompt, platform } : null,+ ).then((detail) => {if (!cancelled) setRead({ key, detail });})@@ -42,7 +51,7 @@ export default function ShoppingProductPage() {return () => {cancelled = true;};- }, [activeBrandId, productId, key]);+ }, [activeBrandId, productId, key, prompt, platform]);const back = (<Linkdiff --git a/web/src/lib/actions/shopping.ts b/web/src/lib/actions/shopping.tsindex 0e49daab0..5911bd5be 100644--- a/web/src/lib/actions/shopping.ts+++ b/web/src/lib/actions/shopping.ts@@ -1679,10 +1679,13 @@ export async function getShoppingProductDetail(brandId: string,productId: string,filters: ShoppingFilters,+ /** The shelf to explain first: the Shelf's "Why not you?" (a question, its channel). */+ focusOn: { promptId: string; platform?: string | null } | null = null,): Promise<ShoppingProductDetail | null> {if (!z.guid().safeParse(brandId).success || !z.guid().safeParse(productId).success) {throw new Error('invalid');}+ const asked = focusOn && z.guid().safeParse(focusOn.promptId).success ? focusOn : null;const supabase = await createClient();const { from } = resolveDateRange(filters);const [[product], cards, stats, domain] = await Promise.all([@@ -1757,8 +1760,8 @@ export async function getShoppingProductDetail(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 shelves = productShelves(product, detailCards, { include: asked?.promptId ?? null });+ const focus = focusShelf(shelves, asked);const ai = (stats.data ?? []).find((row) => row.product_id === productId);return {product,diff --git a/web/src/lib/shopping/product-detail.test.ts b/web/src/lib/shopping/product-detail.test.tsindex 5d784ac6a..baa4cb87d 100644--- a/web/src/lib/shopping/product-detail.test.ts+++ b/web/src/lib/shopping/product-detail.test.ts@@ -129,6 +129,21 @@ describe('focusShelf', () => {});});+describe('a shelf asked for (the Shelf’s "Why not you?")', () => {+ it('keeps the question whatever its match, and explains that shelf first', () => {+ // q3 isn't the product's: kept when it's the one asked for.+ expect(productShelves(product, cards).some((line) => line.promptId === 'q3')).toBe(false);+ const lines = productShelves(product, cards, { include: 'q3' });+ expect(lines.some((line) => line.promptId === 'q3')).toBe(true);+ expect(focusShelf(lines, { promptId: 'q3', platform: 'chatgpt-shopping' })?.promptId).toBe(+ 'q3',+ );+ // Another channel than the one asked for, or a shelf it leads: the usual one.+ expect(focusShelf(lines, { promptId: 'q3', platform: 'gemini-web' })?.promptId).toBe('q1');+ expect(focusShelf(lines, { promptId: 'q2' })?.promptId).toBe('q1');+ });+});+describe('comparison', () => {it('sets the product beside the winner, row by row', () => {const q1 = productShelves(product, cards).find((line) => line.promptId === 'q1')!;diff --git a/web/src/lib/shopping/product-detail.ts b/web/src/lib/shopping/product-detail.tsindex 914a4dee1..535995d15 100644--- a/web/src/lib/shopping/product-detail.ts+++ b/web/src/lib/shopping/product-detail.ts@@ -79,11 +79,13 @@ export function productText(product: CatalogProductRow): string {/*** 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.+ * latest shelf, most relevant first. `include`: a question kept whatever+ * its match, the one the Shelf's "Why not you?" opened the product for.*/export function productShelves(product: CatalogProductRow,cards: readonly DetailCard[],+ { include = null }: { include?: string | null } = {},): ProductShelfLine[] {const category = product.category ? categoryWords(product.category.split('>').at(-1)!) : [];const text = productText(product);@@ -107,7 +109,8 @@ export function productShelves(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 asked = include !== null && first.promptId === include;+ if (!asked && !appeared && !inCategory && scores[0] < RELEVANT_SCORE) continue;const winnerCard = at === 0 ? null : latest[0];lines.push({promptId: first.promptId,@@ -140,8 +143,24 @@ export function productShelves(.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 {+/**+ * The shelf to explain: the one asked for (the Shelf's "Why not you?", a+ * question and its channel) when it has a winner, else the most relevant+ * one it's missing, else the one it ranks lowest on.+ */+export function focusShelf(+ lines: readonly ProductShelfLine[],+ prefer: { promptId: string; platform?: string | null } | null = null,+): ProductShelfLine | null {+ if (prefer) {+ const asked = lines.find(+ (line) =>+ line.promptId === prefer.promptId &&+ (!prefer.platform || line.platform === prefer.platform) &&+ line.winner,+ );+ if (asked) return asked;+ }const missing = lines.filter((line) => line.rank === null && line.winner);if (missing.length) return missing[0];const behind = linesdiff --git a/web/src/lib/shopping/shelf.test.ts b/web/src/lib/shopping/shelf.test.tsindex beed959b7..63130c66a 100644--- a/web/src/lib/shopping/shelf.test.ts+++ b/web/src/lib/shopping/shelf.test.ts@@ -1,5 +1,13 @@import { describe, expect, it } from 'vitest';-import { buildShelf, inPriceBand, shelfStats, SHELF_CARDS, type ShelfCardRow } from './shelf';+import type { ProductRow } from './products';+import {+ buildShelf,+ inPriceBand,+ shelfStats,+ SHELF_CARDS,+ whyNotYou,+ type ShelfCardRow,+} from './shelf';/** Product Visibility's Shelf (ECOM-006). */@@ -155,3 +163,69 @@ describe('inPriceBand', () => {expect(inPriceBand(noPrices, 'over200')).toBe(false);});});++describe('whyNotYou', () => {+ const productRow = (+ id: string,+ over: Partial<ProductRow['product']> = {},+ readiness = 50,+ ): ProductRow => ({+ product: {+ id,+ title: `Product ${id}`,+ url: null,+ productType: null,+ brand: null,+ description: null,+ image: null,+ category: null,+ price: 100,+ currency: 'USD',+ inStock: true,+ hasGtin: true,+ ...over,+ },+ shelves: 0,+ winRate: null,+ avgRank: null,+ aiVisits: 0,+ orders: 0,+ revenue: null,+ currency: null,+ readiness,+ missing: [],+ wrongPrice: null,+ });+ const absent = buildShelf(+ [+ card({+ prompt_text: 'lightweight hiking backpack for women',+ matched_brand_role: 'competitor',+ }),+ ],+ NOW,+ )[0];++ it('names the product the question asks for most, by its title, category and type', () => {+ const products = [+ productRow('boot', { title: 'Peak Hiking Boot' }),+ productRow('ridge', { title: 'Ridge 30L', category: 'Bags > Hiking backpacks' }),+ productRow('trail', { title: 'Trail Daypack', productType: 'Backpack' }, 90),+ ];+ // Ridge shares "hiking" and "backpack"; the others one word each.+ expect(whyNotYou(absent, products)?.product.id).toBe('ridge');+ // On a tie, the readier one.+ expect(+ whyNotYou(absent, [+ productRow('a', { title: 'Backpack A' }, 40),+ productRow('b', { title: 'Backpack B' }, 80),+ ])?.product.id,+ ).toBe('b');+ });++ it('names none for a shelf the brand is on, or when nothing shares a word with the question', () => {+ expect(whyNotYou(absent, [productRow('mug', { title: 'Coffee mug' })])).toBeNull();+ const on = { ...absent, ownRank: 2 };+ expect(whyNotYou(on, [productRow('ridge', { title: 'Hiking backpack' })])).toBeNull();+ });+});diff --git a/web/src/lib/shopping/shelf.ts b/web/src/lib/shopping/shelf.tsindex fff091da6..7dba8d6af 100644--- a/web/src/lib/shopping/shelf.ts+++ b/web/src/lib/shopping/shelf.ts@@ -1,3 +1,6 @@+import { categoryLeaf, categoryWords } from './categories';+import type { ProductRow } from './products';+/*** Product Visibility's Shelf (ECOM-006): for each shopping question the* brand tracks, the products AI put on its "shelf", in order, on each@@ -211,3 +214,44 @@ export function inPriceBand(row: ShelfRow, band: PriceBand): boolean {const [min, max] = BAND_RANGE[band];return middle >= min && middle < max;}++/**+ * "Why not you?" (the mockup's Shelf): for a shelf the brand isn't on, the+ * product of its catalog the question asks for most, by the question's+ * words in the product's title, category and type; the readier one on a+ * tie. Null when none shares a word with the question, or the brand is on+ * the shelf.+ */+export function whyNotYou(row: ShelfRow, products: readonly ProductRow[]): ProductRow | null {+ if (row.ownRank !== null) return null;+ const asked = new Set(categoryWords(row.promptText));+ let best: { row: ProductRow; score: number } | null = null;+ for (const candidate of products) {+ const { product } = candidate;+ const words = new Set(+ categoryWords(+ [+ product.title,+ product.category ? categoryLeaf(product.category) : '',+ product.productType ?? '',+ ]+ .filter(Boolean)+ .join(' '),+ ),+ );+ let score = 0;+ for (const word of asked) if (words.has(word)) score += 1;+ if (score === 0) continue;+ if (+ !best ||+ score > best.score ||+ (score === best.score &&+ (candidate.readiness > best.row.readiness ||+ (candidate.readiness === best.row.readiness &&+ candidate.product.title.localeCompare(best.row.product.title) < 0)))+ ) {+ best = { row: candidate, score };+ }+ }+ return best?.row ?? null;+}