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.

fix(shopping): recover the Shelf from a failed read, read Readiness from every channel, and leave an unknown check out of the score (Product Visibility follow-ups, part 2) (#1666)

Cihan8dcd3f44ddf6
diff --git a/web/messages/en.json b/web/messages/en.json
index 3e583fe47..424bf4f1a 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -8001,16 +8001,15 @@
"price": {
"label": "Price",
"all": "All",
- "under50": "Under $50",
- "50to100": "$50–100",
- "100to200": "$100–200",
- "over200": "$200 and up"
+ "under": "Under {price}",
+ "between": "{from}–{to}",
+ "over": "{price} and up"
},
"empty": "No shopping answers in this period. Track shopping questions on a channel that shows products.",
"emptyBand": "No shelf in this price range.",
"more": "Show {count} more",
"trends": "Trends",
- "failed": "Couldn't read the shelves right now. The other tabs still work; try again in a moment."
+ "failed": "Couldn't read the shelves right now. The other tabs still work."
},
"readiness": {
"title": "AI shopping readiness",
@@ -8023,7 +8022,8 @@
"channels": {
"showing": "Showing your products",
"notShowing": "Tracked, yours not shown",
- "notTracked": "Not tracked"
+ "notTracked": "Not tracked",
+ "unread": "Couldn't read"
},
"sources": {
"chatgpt_us": "OpenAI product index",
@@ -8067,7 +8067,8 @@
"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."
+ "fail": "ChatGPT reads about 40 words. These don't say what the product is in them.",
+ "unknown": "Your products have no product type to look for, so this isn't checked or scored. Add product types to your feed."
},
"feedFields": {
"title": "Feed fields complete · {percent}%",
@@ -8192,7 +8193,8 @@
"close": "Close",
"higher": "{percent}% higher",
"lower": "{percent}% lower",
- "firstWords": "ChatGPT reads about 40 words"
+ "firstWords": "ChatGPT reads about 40 words",
+ "noType": "No product type to look for"
},
"says": {
"title": "What AI says",
@@ -8261,6 +8263,7 @@
"readiness": {
"label": "Readiness {score} of 100",
"missing": "Missing: {check} (−{points})",
+ "unknown": "Not checked: {check}. It needs a product type.",
"complete": "Everything the catalog can tell is in place.",
"checks": {
"gtin": "a GTIN",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_product-detail.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_product-detail.tsx
index aeeb0f5b0..b546d0718 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_product-detail.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_product-detail.tsx
@@ -1,7 +1,7 @@
'use client';
import { useTranslations } from 'next-intl';
-import { ArrowDown, Check, ExternalLink, Minus, ShoppingBag, X } from 'lucide-react';
+import { ArrowDown, Check, ExternalLink, HelpCircle, Minus, ShoppingBag, X } from 'lucide-react';
import { buttonVariants } from '@/components/ui/button-variants';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
@@ -18,7 +18,7 @@ import type { ShoppingProductDetail } from '@/lib/actions/shopping';
import type { ProductAiSays } from '@/lib/shopping/ai-says';
import { formatNumber } from '@/lib/format';
import { priceText } from '@/lib/shopping/price';
-import { READINESS_CHECKS } from '@/lib/shopping/products';
+import { readinessPoints } from '@/lib/shopping/products';
import type { ComparisonState } from '@/lib/shopping/product-detail';
import { productPlan } from '@/lib/shopping/action-plan';
import { cn } from '@/lib/utils';
@@ -261,7 +261,7 @@ export function ProductDetailView({
<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],
+ points: readinessPoints(check, detail.readiness.unknown),
})}
</p>
))
@@ -271,6 +271,12 @@ export function ProductDetailView({
{tReady('complete')}
</p>
)}
+ {detail.readiness.unknown.map((check) => (
+ <p key={check} className="flex items-center gap-2 text-muted-foreground">
+ <HelpCircle className="h-4 w-4 shrink-0" aria-hidden />
+ {tReady('unknown', { check: tReady(`checks.${check}`) })}
+ </p>
+ ))}
</CardContent>
</Card>
</div>
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 4bd5325a5..ea743e8e5 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_products-table.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_products-table.tsx
@@ -21,7 +21,7 @@ import { cn } from '@/lib/utils';
import type { ShoppingProducts } from '@/lib/actions/shopping';
import {
PRODUCT_VIEWS,
- READINESS_CHECKS,
+ readinessPoints,
viewCounts,
viewRows,
type ProductRow,
@@ -64,12 +64,20 @@ function Readiness({ row }: { row: ProductRow }) {
{row.missing.length ? (
row.missing.map((check) => (
<p key={check} className="opacity-90">
- {t('missing', { check: t(`checks.${check}`), points: READINESS_CHECKS[check] })}
+ {t('missing', {
+ check: t(`checks.${check}`),
+ points: readinessPoints(check, row.unknown),
+ })}
</p>
))
) : (
<p className="opacity-90">{t('complete')}</p>
)}
+ {row.unknown?.map((check) => (
+ <p key={check} className="opacity-90">
+ {t('unknown', { check: t(`checks.${check}`) })}
+ </p>
+ ))}
</TooltipContent>
</Tooltip>
);
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_readiness.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_readiness.test.tsx
index 4fa9de149..c52e3ad67 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_readiness.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_readiness.test.tsx
@@ -86,13 +86,17 @@ describe('ReadinessTab', () => {
expect(onProducts).toHaveBeenCalled();
});
- function renderTab(props: { loading?: boolean; unread?: ('sources' | 'products')[] }) {
+ function renderTab(props: {
+ loading?: boolean;
+ unread?: ('sources' | 'products')[];
+ channelsRead?: 'loading' | 'failed';
+ }) {
act(() => {
root.render(
<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
<ReadinessTab
market="us"
- tracked={[]}
+ tracked={['copilot-web']}
ownSlots={new Map()}
score={80}
items={[{ key: 'catalog', state: 'pass', values: { count: 320 } }]}
@@ -121,4 +125,12 @@ describe('ReadinessTab', () => {
expect(text).toContain('Catalog connected');
expect(renderTab({})).toContain('AI shopping readiness80 / 100');
});
+
+ it("doesn't call a channel without the brand's products while every channel's shelves are read, or unread", () => {
+ expect(renderTab({})).toContain('Microsoft CopilotTracked, yours not shown');
+ const reading = renderTab({ channelsRead: 'loading' });
+ expect(reading).not.toContain('Tracked, yours not shown');
+ expect(reading).not.toContain('Not tracked');
+ expect(renderTab({ channelsRead: 'failed' })).toContain("Microsoft CopilotCouldn't read");
+ });
});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_readiness.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_readiness.tsx
index e2c69ecbd..c7db7dc93 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_readiness.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_readiness.tsx
@@ -55,12 +55,15 @@ export type ReadinessRead = 'sources' | 'products';
*
* 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.
+ * would be another score, not this one. The channel cards read every
+ * channel's shelves, whatever channel the page shows (`channelsRead` while
+ * they're read, or when they couldn't be).
*/
export function ReadinessTab({
market,
tracked,
ownSlots,
+ channelsRead,
score,
items,
loading = false,
@@ -71,8 +74,10 @@ export function ReadinessTab({
market: ShoppingMarket;
/** The channels with shopping answers read. */
tracked: readonly string[];
- /** The brand's product slots per channel. */
+ /** The brand's product slots per channel, on every channel's shelves. */
ownSlots: ReadonlyMap<string, number>;
+ /** Those shelves still being read, or not read: `ownSlots` says nothing then. */
+ channelsRead?: 'loading' | 'failed';
score: number | null;
items: ReadinessItem[];
/** The catalog sources or products still being read. */
@@ -98,23 +103,30 @@ export function ReadinessTab({
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">
+ <CardContent className="min-w-0 space-y-2 p-3">
+ {/* A narrow card wraps a long name rather than letting it run out. */}
+ <p className="flex min-w-0 items-start gap-2 text-sm font-medium leading-snug">
<AIProviderAvatar
provider={resolveAIProvider(platform, platform)}
- className="h-4 w-4"
+ className="mt-0.5 h-4 w-4 shrink-0"
plain
/>
- {PLATFORM_LABELS[platform] ?? platform}
+ <span className="min-w-0 break-words">
+ {PLATFORM_LABELS[platform] ?? platform}
+ </span>
</p>
- <span
- className={cn(
- 'inline-flex rounded-full px-2 py-0.5 text-xs font-medium',
- CHANNEL_TONE[state],
- )}
- >
- {t(`channels.${state}`)}
- </span>
+ {channelsRead === 'loading' ? (
+ <Skeleton className="h-5 w-24 rounded-full" />
+ ) : (
+ <span
+ className={cn(
+ 'inline-flex max-w-full rounded-full px-2 py-0.5 text-xs font-medium',
+ channelsRead === 'failed' ? CHANNEL_TONE.notTracked : CHANNEL_TONE[state],
+ )}
+ >
+ {t(`channels.${channelsRead === 'failed' ? 'unread' : state}`)}
+ </span>
+ )}
<p className="text-xs text-muted-foreground">
{t(`sources.${platform === 'chatgpt-shopping' ? `chatgpt_${market}` : platform}`)}
</p>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.test.tsx
index 35936e4c0..1634f0c4e 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.test.tsx
@@ -16,7 +16,7 @@ vi.mock('@/i18n/navigation', () => ({
),
}));
-const { ShelfKpis, ShelfRows } = await import('./_shelf');
+const { ShelfFailed, ShelfKpis, ShelfRows } = await import('./_shelf');
const { priceText } = await import('@/lib/shopping/price');
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
@@ -117,6 +117,17 @@ describe('ShelfKpis', () => {
expect(text).toContain('ChatGPT71% of AI orders');
});
+ it("waits for the brand's orders before its revenue and top channel, and shows a cut value whole on hover", () => {
+ const text = render(<ShelfKpis shelf={shelf} orders={undefined} salesConnected />);
+ expect(text).toContain('AI shelf share25%');
+ // Not "No orders" while they're read, nor another brand's revenue.
+ expect(text).not.toContain('No orders from AI visits yet');
+ expect(text).not.toContain('$24.9k');
+ expect(container.querySelectorAll('[aria-busy="true"]')).toHaveLength(2);
+ render(<ShelfKpis shelf={shelf} orders={orders} salesConnected />);
+ expect(container.querySelector('span[title="$24.9k"]')?.textContent).toBe('$24.9k');
+ });
+
it('asks to connect sales without orders or a source, and names the channel showing the products', () => {
const none = { ...orders, orders: 0, revenue: null, previousRevenue: null, channels: [] };
const text = render(<ShelfKpis shelf={shelf} orders={none} salesConnected={false} />);
@@ -217,6 +228,26 @@ describe('ShelfRows', () => {
expect(onPlatform).toHaveBeenCalledWith('chatgpt-shopping');
});
+ it("names the price bands in the shelves' own currency", async () => {
+ const euro = buildShelf(cards.map((c) => ({ ...c, price_currency: 'EUR' })));
+ render(
+ <ShelfRows
+ shelf={{ ...shelf, rows: euro }}
+ platforms={[]}
+ platform="all"
+ onPlatform={() => {}}
+ />,
+ );
+ const trigger = container.querySelector<HTMLElement>('[aria-label="Price"]')!;
+ await act(async () => {
+ trigger.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
+ trigger.click();
+ });
+ expect(
+ [...document.querySelectorAll<HTMLElement>('[role="option"]')].map((o) => o.textContent),
+ ).toEqual(['All', 'Under €50', '€50–€100', '€100–€200', '€200 and up']);
+ });
+
it('says when there is nothing to show', () => {
expect(
render(
@@ -231,6 +262,20 @@ describe('ShelfRows', () => {
});
});
+describe('ShelfFailed', () => {
+ it("says the shelves couldn't be read, and reads them again on Try again", () => {
+ const onRetry = vi.fn();
+ const text = render(<ShelfFailed onRetry={onRetry} />);
+ expect(container.querySelector('[role="alert"]')).not.toBeNull();
+ expect(text).toContain("Couldn't read the shelves right now.");
+ const retry = [...container.querySelectorAll('button')].find(
+ (b) => b.textContent === 'Try again',
+ )!;
+ act(() => retry.click());
+ expect(onRetry).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('priceText', () => {
it('writes whole prices without cents, others with', () => {
expect(priceText(139, 'USD')).toBe('$139');
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.tsx
index 963ff3d93..2f3bb74b1 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.tsx
@@ -25,8 +25,10 @@ import { priceText } from '@/lib/shopping/price';
import type { ShoppingAiOrders, ShoppingShelf } from '@/lib/actions/shopping';
import type { ProductRow } from '@/lib/shopping/products';
import {
+ BAND_RANGE,
PRICE_BANDS,
inPriceBand,
+ shelfCurrency,
whyNotYou,
type PriceBand,
type ShelfCard,
@@ -65,18 +67,35 @@ function Kpi({
value,
delta,
sub,
+ loading = false,
}: {
title: string;
value: string;
delta?: string | null;
sub: React.ReactNode;
+ /** Its value still being read. */
+ loading?: boolean;
}) {
+ if (loading) {
+ return (
+ <Card aria-busy="true">
+ <CardContent className="space-y-1.5 p-4">
+ <p className="text-xs font-medium text-muted-foreground">{title}</p>
+ <Skeleton className="h-8 w-24" />
+ <Skeleton className="h-4 w-32" />
+ </CardContent>
+ </Card>
+ );
+ }
return (
<Card>
<CardContent className="space-y-1.5 p-4">
<p className="text-xs font-medium text-muted-foreground">{title}</p>
<p className="flex items-baseline gap-2">
- <span className="truncate text-2xl font-bold tabular-nums">{value}</span>
+ {/* A long value is cut: the whole of it on hover. */}
+ <span className="truncate text-2xl font-bold tabular-nums" title={value}>
+ {value}
+ </span>
{delta && (
<span
className={cn(
@@ -100,7 +119,8 @@ function Kpi({
* The Shelf's four numbers (ECOM-006): the brand's share of the product
* slots in AI answers, its products on the shelf (of the catalog's), its
* orders from AI visits in the last 30 days, and the AI channel most of them
- * came from (else the one showing its products most).
+ * came from (else the one showing its products most). The two read from
+ * the orders wait for them (`orders` undefined).
*/
export function ShelfKpis({
shelf,
@@ -108,7 +128,8 @@ export function ShelfKpis({
salesConnected,
}: {
shelf: ShoppingShelf | null;
- orders: ShoppingAiOrders | null;
+ /** The brand's orders from AI visits: undefined while read, null when they couldn't be. */
+ orders: ShoppingAiOrders | null | undefined;
/** Whether a source of sales is in: the tracking snippet, the Shopify pixel or GA. */
salesConnected: boolean;
}) {
@@ -147,6 +168,7 @@ export function ShelfKpis({
/>
<Kpi
title={t('revenue')}
+ loading={orders === undefined}
value={
orders?.revenue && orders.orders
? revenueText(orders.revenue.value, orders.revenue.currency)
@@ -173,6 +195,7 @@ export function ShelfKpis({
/>
<Kpi
title={t('channel')}
+ loading={orders === undefined}
value={
topOrders
? getPlatformName(topOrders.source)
@@ -194,6 +217,26 @@ export function ShelfKpis({
);
}
+/**
+ * The shelves that couldn't be read: said, with a way to read them again,
+ * in place of their numbers and rows (which would wait on them for good).
+ */
+export function ShelfFailed({ onRetry }: { onRetry: () => void }) {
+ const t = useTranslations('shopping.shelf');
+ const tCommon = useTranslations('common');
+ return (
+ <div
+ role="alert"
+ className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-200"
+ >
+ <p>{t('failed')}</p>
+ <Button variant="outline" size="sm" onClick={onRetry}>
+ {tCommon('retry')}
+ </Button>
+ </div>
+ );
+}
+
function ProductCard({ card }: { card: ShelfCard }) {
const t = useTranslations('shopping.shelf');
return (
@@ -393,6 +436,15 @@ export function ShelfRows({
);
}
const rows = shelf.rows.filter((row) => inPriceBand(row, band));
+ // The bands in the shelves' own currency: "Under €50".
+ const currency = shelfCurrency(shelf.rows);
+ const bandLabel = (id: PriceBand) => {
+ if (id === 'all') return t('price.all');
+ const [min, max] = BAND_RANGE[id];
+ if (min === 0) return t('price.under', { price: priceText(max, currency) });
+ if (max === Infinity) return t('price.over', { price: priceText(min, currency) });
+ return t('price.between', { from: priceText(min, currency), to: priceText(max, currency) });
+ };
const chip = (id: string, label: string) => (
<button
key={id}
@@ -423,7 +475,7 @@ export function ShelfRows({
}}
items={PRICE_BANDS.map((id) => ({
value: id,
- label: `${t('price.label')}: ${t(`price.${id}`)}`,
+ label: `${t('price.label')}: ${bandLabel(id)}`,
}))}
>
<SelectTrigger size="sm" className="ml-auto h-7" aria-label={t('price.label')}>
@@ -432,7 +484,7 @@ export function ShelfRows({
<SelectContent align="end">
{PRICE_BANDS.map((id) => (
<SelectItem key={id} value={id}>
- {t(`price.${id}`)}
+ {bandLabel(id)}
</SelectItem>
))}
</SelectContent>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx
index 030b506ae..b6a1bd135 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx
@@ -102,7 +102,7 @@ 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 { ShelfFailed, ShelfKpis, ShelfRows } from './_shelf';
import { ShoppingMarketSwitch, useShoppingMarket } from './_market-switch';
import { WhyDialog } from './_why-dialog';
import { MerchantSplitCard } from './merchant_split_card';
@@ -153,7 +153,6 @@ export default function ShoppingPage() {
const [ownProducts, setOwnProducts] = useState<ShoppingProduct[]>([]);
const [competitorProducts, setCompetitorProducts] = useState<ShoppingProduct[]>([]);
const [competitorSummary, setCompetitorSummary] = useState<CompetitorShoppingSummary[]>([]);
- const [orders, setOrders] = useState<ShoppingAiOrders | null>(null);
// The catalog's categories (ECOM-008), read when their tab opens, for the filters they were read with.
const [categories, setCategories] = useState<{
key: string;
@@ -276,14 +275,31 @@ export default function ShoppingPage() {
// Readiness, is open.
const readKey = `${activeBrandId}:${JSON.stringify(filters)}`;
const canRead = !!activeBrandId && hasFullAccess && shoppingMarket.ready;
+ // Each "Try again" on a shelf that couldn't be read is a new read.
+ const [shelfTry, setShelfTry] = useState(0);
// Null while it reads.
const shelf: ShoppingShelf | 'failed' | null =
useKeyedRead(
canRead,
- readKey,
+ `${readKey}#${shelfTry}`,
() => getShoppingShelf(activeBrandId!, filters),
'the shelves',
) ?? null;
+ // Readiness's channel cards look at every channel whatever the one chosen
+ // (the Shelf's chips): with one chosen, the shelf read for it has only its
+ // cards, and would show the others as not showing the brand's products.
+ const channelFilters = useMemo<ShoppingFilters>(
+ () => ({ ...filters, platforms: undefined }),
+ [filters],
+ );
+ const channelShelfRead = useKeyedRead(
+ canRead && activeTab === 'readiness' && platform !== 'all',
+ `${activeBrandId}:${JSON.stringify(channelFilters)}`,
+ () => getShoppingShelf(activeBrandId!, channelFilters),
+ 'the shelves of every channel',
+ );
+ // Null while it reads.
+ const channelShelf = platform === 'all' ? shelf : (channelShelfRead ?? null);
const productsRead = useKeyedRead(
canRead && (activeTab === 'products' || activeTab === 'readiness'),
readKey,
@@ -342,21 +358,16 @@ export default function ShoppingPage() {
]);
const categoriesRead = categories?.key === categoriesKey ? categories.rows : undefined;
- // Orders from AI visits, the last 30 days whatever the filters (ECOM-006).
- useEffect(() => {
- if (!activeBrandId || !hasFullAccess) return;
- let cancelled = false;
- getShoppingAiOrders(activeBrandId)
- .then((read) => {
- if (!cancelled) setOrders(read);
- })
- .catch(() => {
- if (!cancelled) setOrders(null);
- });
- return () => {
- cancelled = true;
- };
- }, [activeBrandId, hasFullAccess]);
+ // Orders from AI visits, the last 30 days whatever the filters (ECOM-006),
+ // kept by brand: another brand's never show while this one's are read.
+ const ordersRead = useKeyedRead(
+ !!activeBrandId && hasFullAccess,
+ activeBrandId ?? '',
+ () => getShoppingAiOrders(activeBrandId!),
+ 'the orders from AI visits',
+ );
+ // Undefined while they're read, null when they couldn't be.
+ const orders: ShoppingAiOrders | null | undefined = ordersRead === 'failed' ? null : ordersRead;
// This alert always evaluates five consecutive rolling seven-day windows
// ending at query time, independently of display/platform/region filters.
@@ -476,19 +487,11 @@ export default function ShoppingPage() {
<TabsContent value="shelf" className="space-y-6">
{hasFullAccess ? (
<>
- {shelf === 'failed' && (
- <p
- role="alert"
- className="rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-200"
- >
- {t('shelf.failed')}
- </p>
+ {shelf === 'failed' ? (
+ <ShelfFailed onRetry={() => setShelfTry((n) => n + 1)} />
+ ) : (
+ <ShelfKpis shelf={shelf} orders={orders} salesConnected={salesConnected} />
)}
- <ShelfKpis
- shelf={shelf === 'failed' ? null : shelf}
- orders={orders}
- salesConnected={salesConnected}
- />
<div className="grid gap-4 lg:grid-cols-2">
<MerchantSplitCard split={destinations.split} loading={destinationsLoading} />
<ResellerPriceAlerts
@@ -496,19 +499,21 @@ export default function ShoppingPage() {
loading={destinationsLoading}
/>
</div>
- <ShelfRows
- shelf={shelf === 'failed' ? null : shelf}
- platforms={filterOpts.platforms}
- platform={platform}
- onPlatform={setPlatform}
- products={
- catalogTable && catalogTable !== 'failed'
- ? catalogTable.rows
- : shelfProducts && shelfProducts !== 'failed'
- ? shelfProducts.rows
- : undefined
- }
- />
+ {shelf !== 'failed' && (
+ <ShelfRows
+ shelf={shelf}
+ 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">
<PlatformCardRateChart
@@ -621,12 +626,19 @@ export default function ShoppingPage() {
tracked={filterOpts.platforms}
ownSlots={
new Map(
- (shelf && shelf !== 'failed' ? shelf.stats.channels : []).map((c) => [
- c.platform,
- c.ownSlots,
- ]),
+ (channelShelf && channelShelf !== 'failed'
+ ? channelShelf.stats.channels
+ : []
+ ).map((c) => [c.platform, c.ownSlots]),
)
}
+ channelsRead={
+ channelShelf === null
+ ? 'loading'
+ : channelShelf === 'failed'
+ ? 'failed'
+ : undefined
+ }
{...readinessChecklist({
market: shoppingMarket.shown ?? 'us',
catalog: sources.catalog,
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
index 6c6a5a507..c947fe458 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
@@ -111,7 +111,7 @@ const detail: ShoppingProductDetail = {
inStock: true,
hasGtin: false,
},
- readiness: { score: 48, missing: ['gtin', 'description'] },
+ readiness: { score: 48, missing: ['gtin', 'description'], unknown: [] },
shelves: [
line,
{
diff --git a/web/src/lib/shopping/action-plan.test.ts b/web/src/lib/shopping/action-plan.test.ts
index ec62fd462..8a5daf9c9 100644
--- a/web/src/lib/shopping/action-plan.test.ts
+++ b/web/src/lib/shopping/action-plan.test.ts
@@ -20,7 +20,7 @@ const detail = (over: Partial<ShoppingProductDetail> = {}): ShoppingProductDetai
inStock: true,
hasGtin: false,
},
- readiness: { score: 48, missing: ['gtin', 'description'] },
+ readiness: { score: 48, missing: ['gtin', 'description'], unknown: [] },
shelves: [],
focus: {
promptId: 'q1',
@@ -70,7 +70,9 @@ describe('productPlan', () => {
});
it('falls back to the question, a buying guide and a schema check', () => {
- const plan = productPlan(detail({ focus: null, readiness: { score: 100, missing: [] } }));
+ const plan = productPlan(
+ detail({ focus: null, readiness: { score: 100, missing: [], unknown: [] } }),
+ );
expect(plan.map((w) => w.line.key)).toEqual(['optimizeQuestion', 'guide', 'listed', 'schema']);
});
});
diff --git a/web/src/lib/shopping/product-detail.test.ts b/web/src/lib/shopping/product-detail.test.ts
index baa4cb87d..f216e1b74 100644
--- a/web/src/lib/shopping/product-detail.test.ts
+++ b/web/src/lib/shopping/product-detail.test.ts
@@ -164,6 +164,19 @@ describe('comparison', () => {
]);
});
+ it("doesn't count the first 40 words as missing without a product type to look for", () => {
+ const q1 = productShelves(product, cards).find((line) => line.promptId === 'q1')!;
+ const rows = comparison({ ...product, productType: null, category: null }, q1, {
+ own: null,
+ price: priceText,
+ storeDomain: null,
+ });
+ expect(rows.find((row) => row.key === 'firstWords')).toMatchObject({
+ state: 'info',
+ note: { key: 'noType' },
+ });
+ });
+
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, {
diff --git a/web/src/lib/shopping/product-detail.ts b/web/src/lib/shopping/product-detail.ts
index 535995d15..ead79d8de 100644
--- a/web/src/lib/shopping/product-detail.ts
+++ b/web/src/lib/shopping/product-detail.ts
@@ -254,12 +254,14 @@ export function comparison(
});
const ready = readiness(product);
const has = (check: ReadinessCheck) => !ready.missing.includes(check);
+ // Without a product type there's nothing to look for: not a miss (products.ts).
+ const untyped = ready.unknown.includes('typeFirst');
rows.push({
key: 'firstWords',
you: null,
winner: null,
- state: has('typeFirst') ? 'match' : 'missing',
- note: { key: 'firstWords' },
+ state: untyped ? 'info' : has('typeFirst') ? 'match' : 'missing',
+ note: { key: untyped ? 'noType' : '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' });
diff --git a/web/src/lib/shopping/products.test.ts b/web/src/lib/shopping/products.test.ts
index 679d371a9..f0f3d7361 100644
--- a/web/src/lib/shopping/products.test.ts
+++ b/web/src/lib/shopping/products.test.ts
@@ -3,6 +3,7 @@ import {
inView,
productRows,
readiness,
+ readinessPoints,
viewCounts,
viewRows,
type CatalogProductRow,
@@ -30,7 +31,7 @@ const product = (over: Partial<CatalogProductRow>): CatalogProductRow => ({
describe('readiness', () => {
it('scores a complete product 100', () => {
- expect(readiness(product({}))).toEqual({ score: 100, missing: [] });
+ expect(readiness(product({}))).toEqual({ score: 100, missing: [], unknown: [] });
});
it('says what a product misses, and what each costs', () => {
@@ -58,6 +59,27 @@ describe('readiness', () => {
'category',
'brand',
],
+ unknown: [],
+ });
+ });
+
+ it("leaves the first 40 words out of the score without a product type, as Shopify's often is", () => {
+ // No type and no category: what the product is can't be looked for.
+ const untyped = product({ productType: ' ', category: null });
+ expect(readiness(untyped)).toEqual({
+ // 80 of the other checks' 90 points (no category).
+ score: 89,
+ missing: ['category'],
+ unknown: ['typeFirst'],
+ });
+ expect(readiness({ ...untyped, category: 'Shoes' }).unknown).toEqual([]);
+ // A missing check costs its share of the points checked.
+ expect(readinessPoints('gtin')).toBe(20);
+ expect(readinessPoints('gtin', ['typeFirst'])).toBe(22);
+ expect(productRows([untyped], [], [])[0]).toMatchObject({
+ readiness: 89,
+ missing: ['category'],
+ unknown: ['typeFirst'],
});
});
diff --git a/web/src/lib/shopping/products.ts b/web/src/lib/shopping/products.ts
index f868440c9..890997b05 100644
--- a/web/src/lib/shopping/products.ts
+++ b/web/src/lib/shopping/products.ts
@@ -74,39 +74,59 @@ const wordsOf = (text: string | null) =>
.filter(Boolean);
/**
- * A product's readiness, 0–100, and the checks it misses: a GTIN, a photo,
- * in stock, a price, a description that says enough and names what the
- * product is in its first 40 words, a category and a brand.
+ * A product's readiness, 0–100, the checks it misses, and those that can't
+ * be checked: a GTIN, a photo, in stock, a price, a description that says
+ * enough and names what the product is in its first 40 words, a category
+ * and a brand. The first 40 words are checked against the product's type
+ * (its feed's product type, else its category's last part): without one,
+ * as Shopify often leaves it, that check is unknown and left out of the
+ * score, which is then out of the other checks' points.
*/
export function readiness(product: CatalogProductRow): {
score: number;
missing: ReadinessCheck[];
+ unknown: ReadinessCheck[];
} {
const description = wordsOf(product.description);
- const type = wordsOf(product.productType ?? product.category?.split('>').at(-1) ?? null);
+ const type = wordsOf(
+ product.productType?.trim() || product.category?.split('>').at(-1)?.trim() || null,
+ );
const firstWords = new Set(description.slice(0, FIRST_WORDS));
- const passed: Record<ReadinessCheck, boolean> = {
+ const passed: Record<ReadinessCheck, boolean | null> = {
gtin: product.hasGtin,
image: !!product.image,
inStock: product.inStock,
price: product.price !== null,
description: description.length >= DESCRIPTION_WORDS,
// The type's last word, as a description says it: "Trail running shoe" → "shoe".
- typeFirst:
- type.length > 0 &&
- [type.at(-1)!, type.at(-1)!.replace(/s$/, '')].some((word) =>
- [...firstWords].some((w) => w === word || w.replace(/s$/, '') === word),
- ),
+ typeFirst: type.length
+ ? [type.at(-1)!, type.at(-1)!.replace(/s$/, '')].some((word) =>
+ [...firstWords].some((w) => w === word || w.replace(/s$/, '') === word),
+ )
+ : null,
category: !!product.category,
brand: !!product.brand,
};
- const missing = (Object.keys(READINESS_CHECKS) as ReadinessCheck[]).filter(
- (check) => !passed[check],
- );
- const score = (Object.keys(READINESS_CHECKS) as ReadinessCheck[])
+ const checks = Object.keys(READINESS_CHECKS) as ReadinessCheck[];
+ const missing = checks.filter((check) => passed[check] === false);
+ const unknown = checks.filter((check) => passed[check] === null);
+ const points = checks
.filter((check) => passed[check])
.reduce((sum, check) => sum + READINESS_CHECKS[check], 0);
- return { score, missing };
+ return { score: Math.round((100 * points) / checkedPoints(unknown)), missing, unknown };
+}
+
+/** The points of the checks made: all 100, less those that couldn't be. */
+function checkedPoints(unknown: readonly ReadinessCheck[]): number {
+ return unknown.reduce((sum, check) => sum - READINESS_CHECKS[check], 100);
+}
+
+/** What a missing check costs a product's score, the checks it couldn't make aside. */
+export function readinessPoints(
+ check: ReadinessCheck,
+ unknown: readonly ReadinessCheck[] = [],
+): number {
+ return Math.round((100 * READINESS_CHECKS[check]) / checkedPoints(unknown));
}
/** A product's row in the table. */
@@ -123,6 +143,8 @@ export interface ProductRow {
currency: string | null;
readiness: number;
missing: ReadinessCheck[];
+ /** The checks that couldn't be made (no product type), left out of `readiness`. */
+ unknown?: 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);
@@ -209,6 +231,7 @@ export function productRows(
currency: ai?.currency ?? null,
readiness: ready.score,
missing: ready.missing,
+ unknown: ready.unknown,
wrongPrice: wrongPrice(product, shown?.cards ?? []),
};
});
diff --git a/web/src/lib/shopping/readiness.test.ts b/web/src/lib/shopping/readiness.test.ts
index 0e82b1bee..0d4c8c63d 100644
--- a/web/src/lib/shopping/readiness.test.ts
+++ b/web/src/lib/shopping/readiness.test.ts
@@ -112,6 +112,30 @@ describe('readinessChecklist', () => {
expect(score).toBe(Math.round((100 * 3) / 9));
});
+ it('checks the first 40 words only on products with a type, and not at all without one', () => {
+ const untyped = { productType: null, category: null };
+ const firstWords = (products: CatalogProductRow[]) =>
+ readinessChecklist({
+ market: 'us',
+ catalog: [source('shopify')],
+ products: productRows(products, [], []),
+ openAi: null,
+ cheaperResellers: null,
+ amazonDrop: null,
+ }).items.find((item) => item.key === 'firstWords');
+ // One typed product, whose description names it: the untyped one doesn't fail it.
+ expect(firstWords([product('a'), product('b', untyped)])).toMatchObject({
+ state: 'pass',
+ values: { count: 0 },
+ });
+ // None typed: unknown, so the score leaves it out.
+ expect(firstWords([product('a', untyped), product('b', untyped)])).toMatchObject({
+ state: 'unknown',
+ values: { count: 0 },
+ action: undefined,
+ });
+ });
+
it('asks for the catalog when there is none, and lists no product checks without products', () => {
const { items } = readinessChecklist({
market: 'europe',
diff --git a/web/src/lib/shopping/readiness.ts b/web/src/lib/shopping/readiness.ts
index 63b1cf1ad..a57d3f102 100644
--- a/web/src/lib/shopping/readiness.ts
+++ b/web/src/lib/shopping/readiness.ts
@@ -103,10 +103,13 @@ export function readinessChecklist(input: ReadinessInput): {
}
if (products.length) {
- const firstWords = products.filter((row) => row.missing.includes('typeFirst')).length;
+ // Only the products with a type can be checked (products.ts, readiness):
+ // without any, the check is unknown and left out of the score.
+ const typed = products.filter((row) => !row.unknown?.includes('typeFirst'));
+ const firstWords = typed.filter((row) => row.missing.includes('typeFirst')).length;
items.push({
key: 'firstWords',
- state: shareState(firstWords, products.length),
+ state: typed.length ? shareState(firstWords, typed.length) : 'unknown',
values: { count: firstWords },
action: firstWords ? 'products' : undefined,
});
diff --git a/web/src/lib/shopping/shelf.test.ts b/web/src/lib/shopping/shelf.test.ts
index 63130c66a..7d5c144c6 100644
--- a/web/src/lib/shopping/shelf.test.ts
+++ b/web/src/lib/shopping/shelf.test.ts
@@ -3,6 +3,7 @@ import type { ProductRow } from './products';
import {
buildShelf,
inPriceBand,
+ shelfCurrency,
shelfStats,
SHELF_CARDS,
whyNotYou,
@@ -164,6 +165,25 @@ describe('inPriceBand', () => {
});
});
+describe('shelfCurrency', () => {
+ it('is the currency most of the shelves’ priced products show, else none', () => {
+ const rows = buildShelf(
+ [
+ card({ position: 0, price_currency: 'EUR' }),
+ card({ position: 1, price_currency: 'EUR' }),
+ card({ position: 2, price_currency: 'USD' }),
+ // Without a price, its currency says nothing.
+ card({ position: 3, price_amount: null, price_currency: 'GBP' }),
+ card({ position: 4, price_amount: null, price_currency: 'GBP' }),
+ ],
+ NOW,
+ );
+ expect(shelfCurrency(rows)).toBe('EUR');
+ expect(shelfCurrency(buildShelf([card({ price_currency: null })], NOW))).toBeNull();
+ expect(shelfCurrency([])).toBeNull();
+ });
+});
+
describe('whyNotYou', () => {
const productRow = (
id: string,
diff --git a/web/src/lib/shopping/shelf.ts b/web/src/lib/shopping/shelf.ts
index 7dba8d6af..6b9def82e 100644
--- a/web/src/lib/shopping/shelf.ts
+++ b/web/src/lib/shopping/shelf.ts
@@ -196,13 +196,33 @@ export function shelfStats(cards: readonly ShelfCardRow[]): ShelfStats {
export const PRICE_BANDS = ['all', 'under50', '50to100', '100to200', 'over200'] as const;
export type PriceBand = (typeof PRICE_BANDS)[number];
-const BAND_RANGE: Record<Exclude<PriceBand, 'all'>, [number, number]> = {
+/** Each band's prices, from its lower bound up to (not with) its upper one. */
+export const BAND_RANGE: Record<Exclude<PriceBand, 'all'>, [number, number]> = {
under50: [0, 50],
'50to100': [50, 100],
'100to200': [100, 200],
over200: [200, Infinity],
};
+/**
+ * The currency the shelves' prices are in, for the bands' labels: the one
+ * most of their priced products show, else null.
+ */
+export function shelfCurrency(rows: readonly ShelfRow[]): string | null {
+ const counts = new Map<string, number>();
+ for (const row of rows) {
+ for (const card of row.cards) {
+ if (card.price === null || !card.currency) continue;
+ counts.set(card.currency, (counts.get(card.currency) ?? 0) + 1);
+ }
+ }
+ let best: string | null = null;
+ for (const [currency, count] of counts) {
+ if (best === null || count > counts.get(best)!) best = currency;
+ }
+ return best;
+}
+
export function inPriceBand(row: ShelfRow, band: PriceBand): boolean {
if (band === 'all') return true;
const prices = row.cards