Skip to content

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

feat(content): show and change a draft's shopping path in the editor's Brief tab (shopping path, part 3) (#1591)

Cihan24f43462c3a7
diff --git a/web/messages/en.json b/web/messages/en.json
index bb2266054..c397d8650 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -4452,6 +4452,66 @@
},
"rebuild": "Rebuild with selection"
},
+ "shopping": {
+ "title": "Shopping path",
+ "description": "Where this page sends readers. Picked by topic, stock and Merchant Center status. Prices and specs come from the catalog only.",
+ "empty": "Pick the category page and the products in stock this page links, from your catalog.",
+ "build": "Pick from the catalog",
+ "rebuild": "Pick again",
+ "building": "Picking…",
+ "loadError": "Couldn't read the shopping path.",
+ "retry": "Try again",
+ "buildFailed": "Couldn't pick from the catalog. Try again in a moment.",
+ "rateLimited": "Too many picks in a short time. Try again in a few minutes.",
+ "saveFailed": "Couldn't save the change. Try again.",
+ "changed": "The shopping path changed meanwhile. It's shown as it is now: make your change again.",
+ "unreadable": "The saved shopping path can't be read. Pick from the catalog to start it again.",
+ "noPath": {
+ "not_a_shop": "Shopping paths are for brands that sell online. Set the site type to E-commerce in Brand settings.",
+ "page_type": "This page type doesn't link products. Buying guides, best-of lists, comparisons, guides and blog posts do.",
+ "no_catalog": "There's no catalog to pick from yet. Connect Google Merchant Center or a product feed in Settings › Integrations.",
+ "no_match": "Nothing in your catalog matches this page's topic. Name what you sell in the title or the brief's keywords, then pick again.",
+ "other": "No shopping path fits this page right now. Try again later."
+ },
+ "category": "Category page",
+ "categoryPlace": "In the intro, and again at the end",
+ "noCategory": "No category page matches this topic. Check the category pages in Settings › Integrations.",
+ "products": "{count, plural, =0 {No products} one {# product in the page} other {# products in the page}}",
+ "noProducts": "No product in stock matches this page's topic yet.",
+ "place": {
+ "pick": "Top picks #{n}",
+ "compared": "Compared #{n}",
+ "linked": "Linked in the text"
+ },
+ "stock": {
+ "in_stock": "In stock",
+ "limited_availability": "Low stock"
+ },
+ "issues": "{count, plural, one {# Merchant Center issue: {first}} other {# Merchant Center issues: {first} and more}}",
+ "locked": "Locked",
+ "lock": "Lock {title}",
+ "unlock": "Unlock {title}",
+ "swap": "Swap",
+ "swapLabel": "Swap {title} for another product",
+ "remove": "Remove",
+ "removeLabel": "Remove {title} from the page",
+ "lockHint": "Locked products stay when the products are picked again or the agent rewrites.",
+ "add": "Add product",
+ "searchLabel": "Search the catalog",
+ "searchPlaceholder": "Product name…",
+ "searchEmpty": "No product with that name.",
+ "searchFailed": "Couldn't search the catalog. Try again.",
+ "addThis": "Add {title}",
+ "leftOut": "Left out",
+ "reason": {
+ "sold_out": "sold out",
+ "refused": "Merchant Center refuses it",
+ "no_link": "no page to link",
+ "gone": "no longer in the catalog",
+ "other": "can't be linked"
+ },
+ "untitled": "Untitled product"
+ },
"brief": {
"loadError": "Couldn't load the brief.",
"retry": "Retry",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_shopping-path.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_shopping-path.test.tsx
new file mode 100644
index 000000000..89eac007b
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_shopping-path.test.tsx
@@ -0,0 +1,352 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../../../../../../messages/en.json';
+import type { ShoppingChoices, ShoppingPath } from '@/lib/content/shopping-path';
+
+const getDraftShoppingPath = vi.fn();
+const buildDraftShoppingPath = vi.fn();
+const saveDraftShoppingPath = vi.fn();
+const searchCatalogProducts = vi.fn();
+vi.mock('@/lib/actions/shopping-path', () => ({
+ getDraftShoppingPath: (...args: unknown[]) => getDraftShoppingPath(...args),
+ buildDraftShoppingPath: (...args: unknown[]) => buildDraftShoppingPath(...args),
+ saveDraftShoppingPath: (...args: unknown[]) => saveDraftShoppingPath(...args),
+ searchCatalogProducts: (...args: unknown[]) => searchCatalogProducts(...args),
+}));
+const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));
+vi.mock('sonner', () => ({ toast }));
+
+const { ShoppingPathSection, priceText } = await import('./_shopping-path');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+/** Brief › Shopping path (shopping path, part 3). */
+
+const product = (
+ id: string,
+ title: string,
+ extra: Partial<ShoppingPath['products'][number]> = {},
+) => ({
+ id,
+ title,
+ url: `https://shop.example/products/${id}`,
+ price: 189,
+ salePrice: null,
+ currency: 'USD',
+ availability: 'in_stock',
+ image: null,
+ issues: [],
+ score: 9,
+ ...extra,
+});
+
+const PATH: ShoppingPath = {
+ version: 1,
+ builtAt: '2026-10-27T12:00:00.000Z',
+ pageType: 'buying_guide',
+ categories: [
+ {
+ name: 'Shoes > Hiking Boots',
+ url: 'https://shop.example/collections/hiking-boots',
+ title: 'Hiking boots',
+ },
+ ],
+ products: [
+ product('p1', 'Summit GTX Boot'),
+ product('p2', 'Ridge Light Hiker', {
+ price: 149,
+ salePrice: 129,
+ availability: 'limited_availability',
+ issues: [{ code: 'missing_gtin', attribute: 'gtin' }],
+ }),
+ ],
+ leftOut: [{ id: 'p3', title: 'Canyon Low WP', reason: 'sold_out' }],
+ locked: [],
+ removed: [],
+ added: [],
+};
+
+let container: HTMLDivElement;
+let root: Root;
+// The path as saved: each save writes the choices and a new savedAt, as the action does.
+let stored: ShoppingPath;
+let saves: number;
+
+async function render() {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <ShoppingPathSection draftId="d1" brandId="b1" pageType="buying_guide" />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+const button = (label: string) =>
+ [...container.querySelectorAll('button')].find(
+ (b) => b.textContent === label || b.getAttribute('aria-label') === label,
+ );
+
+beforeEach(() => {
+ getDraftShoppingPath.mockReset().mockResolvedValue({ path: PATH });
+ buildDraftShoppingPath.mockReset().mockResolvedValue({ path: PATH });
+ stored = PATH;
+ saves = 0;
+ saveDraftShoppingPath
+ .mockReset()
+ .mockImplementation(async (_id: string, _read: unknown, choices: ShoppingChoices) => {
+ saves += 1;
+ stored = {
+ ...stored,
+ ...choices,
+ products: stored.products.filter((p) => !choices.removed.includes(p.id)),
+ savedAt: `2026-10-27T13:00:0${saves}.000Z`,
+ };
+ return { path: stored };
+ });
+ searchCatalogProducts.mockReset().mockResolvedValue([]);
+ toast.error.mockReset();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('priceText', () => {
+ it('writes a price in its currency, the sale price first, and none without one', () => {
+ expect(priceText({ price: 189, salePrice: null, currency: 'USD' })).toBe('$189.00');
+ expect(priceText({ price: 149, salePrice: 129, currency: 'EUR' })).toBe('€129.00');
+ expect(priceText({ price: null, salePrice: null, currency: 'USD' })).toBeNull();
+ expect(priceText({ price: 10, salePrice: null, currency: 'XX1' })).toBe('10 XX1');
+ });
+});
+
+describe('ShoppingPathSection', () => {
+ it('shows the category page, the products with their stock, issues and place, and those left out', async () => {
+ await render();
+ expect(getDraftShoppingPath).toHaveBeenCalledWith('d1');
+ const text = container.textContent ?? '';
+ expect(text).toContain('Shoes > Hiking Boots');
+ expect(text).toContain('/collections/hiking-boots');
+ expect(text).toContain('In the intro, and again at the end');
+ expect(text).toContain('2 products in the page');
+ expect(text).toContain('Summit GTX Boot');
+ expect(text).toContain('$189.00');
+ expect(text).toContain('$129.00');
+ expect(text).toContain('Low stock');
+ expect(text).toContain('1 Merchant Center issue: gtin');
+ expect(text).toContain('Top picks #1');
+ expect(text).toContain('Top picks #2');
+ expect(text).toContain('Canyon Low WP · sold out');
+ });
+
+ it('picks from the catalog the first time, and says when a draft takes none', async () => {
+ getDraftShoppingPath.mockResolvedValue({ path: null });
+ await render();
+ await act(async () => button('Pick from the catalog')!.click());
+ expect(buildDraftShoppingPath).toHaveBeenCalledWith('d1', 'b1');
+ expect(container.textContent).toContain('Summit GTX Boot');
+
+ act(() => root.unmount());
+ root = createRoot(container);
+ buildDraftShoppingPath.mockResolvedValue({ path: null, reason: 'no_catalog' });
+ await render();
+ await act(async () => button('Pick from the catalog')!.click());
+ expect(container.textContent).toContain("There's no catalog to pick from yet.");
+ });
+
+ it('locks a product, removes one, and swaps one for the next best', async () => {
+ await render();
+ const lock = () => button('Lock Summit GTX Boot')!;
+ expect(lock().getAttribute('aria-pressed')).toBe('false');
+ expect(lock().title).toBe('Lock Summit GTX Boot');
+ await act(async () => lock().click());
+ // The choices alone, over the path as read.
+ expect(saveDraftShoppingPath).toHaveBeenLastCalledWith(
+ 'd1',
+ { builtAt: PATH.builtAt, savedAt: null },
+ { locked: ['p1'], removed: [], added: [] },
+ );
+ // One name; its state pressed, and the tooltip says what a click does.
+ expect(lock().getAttribute('aria-pressed')).toBe('true');
+ expect(lock().title).toBe('Unlock Summit GTX Boot');
+
+ await act(async () => button('Remove Ridge Light Hiker from the page')!.click());
+ // Over the change just saved.
+ expect(saveDraftShoppingPath).toHaveBeenLastCalledWith(
+ 'd1',
+ { builtAt: PATH.builtAt, savedAt: '2026-10-27T13:00:01.000Z' },
+ { locked: ['p1'], removed: ['p2'], added: [] },
+ );
+ expect(container.textContent).not.toContain('Ridge Light Hiker');
+ expect(buildDraftShoppingPath).not.toHaveBeenCalled();
+
+ await act(async () => button('Swap Summit GTX Boot for another product')!.click());
+ expect(saveDraftShoppingPath).toHaveBeenLastCalledWith(
+ 'd1',
+ { builtAt: PATH.builtAt, savedAt: '2026-10-27T13:00:02.000Z' },
+ { locked: [], removed: ['p2', 'p1'], added: [] },
+ );
+ expect(buildDraftShoppingPath).toHaveBeenCalledWith('d1', 'b1');
+ });
+
+ it('puts a change back when it can’t be saved', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ saveDraftShoppingPath.mockRejectedValueOnce(new Error('denied'));
+ await render();
+ await act(async () => button('Remove Ridge Light Hiker from the page')!.click());
+ expect(toast.error).toHaveBeenCalledWith("Couldn't save the change. Try again.");
+ expect(container.textContent).toContain('Ridge Light Hiker');
+ } finally {
+ error.mockRestore();
+ }
+ });
+
+ it('reads the path again when it changed since it was read, and saves nothing over it', async () => {
+ saveDraftShoppingPath.mockResolvedValueOnce({ error: 'changed' });
+ const now = { ...PATH, builtAt: '2026-10-27T12:30:00.000Z', products: [PATH.products[1]] };
+ await render();
+ getDraftShoppingPath.mockResolvedValue({ path: now });
+ await act(async () => button('Lock Summit GTX Boot')!.click());
+ expect(toast.error).toHaveBeenCalledWith(
+ "The shopping path changed meanwhile. It's shown as it is now: make your change again.",
+ );
+ expect(getDraftShoppingPath).toHaveBeenCalledTimes(2);
+ expect(container.textContent).not.toContain('Summit GTX Boot');
+ expect(container.textContent).toContain('Ridge Light Hiker');
+ });
+
+ it('keeps a swap saved when the new pick fails, and says why', async () => {
+ buildDraftShoppingPath.mockResolvedValueOnce({ error: 'rate_limited' });
+ await render();
+ await act(async () => button('Swap Summit GTX Boot for another product')!.click());
+ expect(toast.error).toHaveBeenCalledWith(
+ 'Too many picks in a short time. Try again in a few minutes.',
+ );
+ // The removal is saved, and shown: the next change is made over it.
+ expect(container.textContent).not.toContain('Summit GTX Boot');
+ await act(async () => button('Lock Ridge Light Hiker')!.click());
+ expect(saveDraftShoppingPath).toHaveBeenLastCalledWith(
+ 'd1',
+ { builtAt: PATH.builtAt, savedAt: '2026-10-27T13:00:01.000Z' },
+ { locked: ['p2'], removed: ['p1'], added: [] },
+ );
+
+ buildDraftShoppingPath.mockResolvedValueOnce({ error: 'failed' });
+ await act(async () => button('Pick again')!.click());
+ expect(toast.error).toHaveBeenLastCalledWith(
+ "Couldn't pick from the catalog. Try again in a moment.",
+ );
+ });
+
+ it('reads the path again when another pick changed it meanwhile', async () => {
+ buildDraftShoppingPath.mockResolvedValueOnce({ error: 'changed' });
+ await render();
+ await act(async () => button('Pick again')!.click());
+ expect(toast.error).toHaveBeenCalledWith(
+ "The shopping path changed meanwhile. It's shown as it is now: make your change again.",
+ );
+ expect(getDraftShoppingPath).toHaveBeenCalledTimes(2);
+ });
+
+ it('adds a product found in the catalog, then picks again with it kept', async () => {
+ vi.useFakeTimers();
+ try {
+ searchCatalogProducts.mockResolvedValue([
+ { id: 'p9', title: 'Alpine Pro Leather', url: 'https://shop.example/products/p9' },
+ ]);
+ await render();
+ await act(async () => button('Add product')!.click());
+ const input = container.querySelector<HTMLInputElement>('input[type="search"]')!;
+ await act(async () => {
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
+ setter.call(input, 'alpine');
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(300);
+ });
+ expect(searchCatalogProducts).toHaveBeenCalledWith('b1', 'alpine');
+ await act(async () => button('Add Alpine Pro Leather')!.click());
+ expect(saveDraftShoppingPath).toHaveBeenCalledWith(
+ 'd1',
+ { builtAt: PATH.builtAt, savedAt: null },
+ { locked: [], removed: [], added: ['p9'] },
+ );
+ expect(buildDraftShoppingPath).toHaveBeenCalledWith('d1', 'b1');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('says when the catalog can’t be searched', async () => {
+ vi.useFakeTimers();
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ searchCatalogProducts.mockRejectedValue(new Error('boom'));
+ await render();
+ await act(async () => button('Add product')!.click());
+ const input = container.querySelector<HTMLInputElement>('input[type="search"]')!;
+ await act(async () => {
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
+ setter.call(input, 'alpine');
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(300);
+ });
+ expect(container.textContent).toContain("Couldn't search the catalog. Try again.");
+ expect(container.textContent).not.toContain('No product with that name.');
+ } finally {
+ error.mockRestore();
+ vi.useRealTimers();
+ }
+ });
+
+ it('says why products are left out, a reason added since in general words', async () => {
+ getDraftShoppingPath.mockResolvedValue({
+ path: {
+ ...PATH,
+ leftOut: [
+ { id: 'p4', title: null, reason: 'gone' },
+ { id: 'p4', title: 'Trail Mid', reason: 'recalled' },
+ ],
+ },
+ });
+ await render();
+ const text = container.textContent ?? '';
+ expect(text).toContain('Untitled product · no longer in the catalog');
+ expect(text).toContain("Trail Mid · can't be linked");
+ });
+
+ it('offers a new pick when nothing matched the topic, or the kept path can’t be read', async () => {
+ getDraftShoppingPath.mockResolvedValue({ path: null });
+ buildDraftShoppingPath.mockResolvedValue({ path: null, reason: 'no_match' });
+ await render();
+ await act(async () => button('Pick from the catalog')!.click());
+ expect(container.textContent).toContain("Nothing in your catalog matches this page's topic.");
+ expect(button('Pick from the catalog')).toBeDefined();
+
+ act(() => root.unmount());
+ root = createRoot(container);
+ getDraftShoppingPath.mockResolvedValue({ path: null, unreadable: true });
+ await render();
+ expect(container.textContent).toContain("The saved shopping path can't be read.");
+ expect(button('Pick from the catalog')).toBeDefined();
+ });
+
+ it("says so when the path can't be read, and reads it again", async () => {
+ getDraftShoppingPath.mockResolvedValueOnce(null);
+ await render();
+ expect(container.textContent).toContain("Couldn't read the shopping path.");
+ await act(async () => button('Try again')!.click());
+ expect(getDraftShoppingPath).toHaveBeenCalledTimes(2);
+ expect(container.textContent).toContain('Summit GTX Boot');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_shopping-path.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_shopping-path.tsx
new file mode 100644
index 000000000..2933558af
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_shopping-path.tsx
@@ -0,0 +1,482 @@
+'use client';
+
+import { useCallback, useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { Lock, LockOpen, Plus, RefreshCw, ShoppingBag } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { LoadingDots } from '@/components/ui/loading-dots';
+import {
+ buildDraftShoppingPath,
+ getDraftShoppingPath,
+ saveDraftShoppingPath,
+ searchCatalogProducts,
+ type CatalogProductHit,
+} from '@/lib/actions/shopping-path';
+import {
+ choicesOf,
+ leftOutReason,
+ placementOf,
+ withAdded,
+ withLocked,
+ withRemoved,
+ type NoPathReason,
+ type ShoppingPath,
+ type ShoppingProduct,
+} from '@/lib/content/shopping-path';
+import { pagePath } from '@/lib/content/overlap';
+
+/** A product's price as the catalog has it, in its currency; null without one. */
+export function priceText(product: Pick<ShoppingProduct, 'price' | 'salePrice' | 'currency'>) {
+ const amount = product.salePrice ?? product.price;
+ if (amount == null) return null;
+ try {
+ return product.currency
+ ? new Intl.NumberFormat('en-US', { style: 'currency', currency: product.currency }).format(
+ amount,
+ )
+ : new Intl.NumberFormat('en-US', { minimumFractionDigits: 2 }).format(amount);
+ } catch {
+ // A currency code Intl doesn't know: the amount and the code as the catalog has them.
+ return `${amount} ${product.currency}`;
+ }
+}
+
+type PathState =
+ | { status: 'loading' }
+ | { status: 'failed' }
+ | {
+ status: 'ready';
+ path: ShoppingPath | null;
+ none: NoPathReason | null;
+ /** A path is kept, but not one this tab reads: built anew, as none would be. */
+ unreadable?: boolean;
+ };
+
+/** Why a draft has no path that a new pick may change: the topic, or a reason not known here. */
+const PICK_AGAIN: readonly (NoPathReason | null)[] = [null, 'no_match', 'other'];
+
+/**
+ * Brief › Shopping path (shopping path, part 3): on an online shop, the
+ * category page and the catalog products this page links, picked by the
+ * API for its topic (in stock, accepted by Merchant Center), with where each
+ * goes. The person locks, swaps, removes or adds a product; Pick again
+ * builds it anew, their choices kept. Shown for a page type that takes one
+ * on an e-commerce brand.
+ */
+export function ShoppingPathSection({
+ draftId,
+ brandId,
+ pageType,
+}: {
+ draftId: string;
+ brandId: string;
+ pageType: string | null;
+}) {
+ const t = useTranslations('contentEditor.editor.shopping');
+ const [state, setState] = useState<PathState>({ status: 'loading' });
+ const [busy, setBusy] = useState<'build' | 'save' | null>(null);
+ const [adding, setAdding] = useState(false);
+ const [query, setQuery] = useState('');
+ // The catalog's products for what's typed; 'failed' when the search failed.
+ const [hits, setHits] = useState<CatalogProductHit[] | 'failed' | null>(null);
+
+ const load = useCallback(async () => {
+ setState({ status: 'loading' });
+ try {
+ const read = await getDraftShoppingPath(draftId);
+ setState(
+ read
+ ? { status: 'ready', path: read.path, none: null, unreadable: read.unreadable }
+ : { status: 'failed' },
+ );
+ } catch (err) {
+ console.error('Failed to read the shopping path:', err);
+ setState({ status: 'failed' });
+ }
+ }, [draftId]);
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ // Add product: the catalog's products whose name holds what's typed.
+ useEffect(() => {
+ if (!adding || query.trim().length < 2) {
+ setHits(null);
+ return;
+ }
+ let cancelled = false;
+ const timer = setTimeout(() => {
+ searchCatalogProducts(brandId, query).then(
+ (found) => {
+ if (!cancelled) setHits(found);
+ },
+ (err) => {
+ console.error('Failed to search the catalog:', err);
+ if (!cancelled) setHits('failed');
+ },
+ );
+ }, 250);
+ return () => {
+ cancelled = true;
+ clearTimeout(timer);
+ };
+ }, [adding, query, brandId]);
+
+ /**
+ * The person's choices in `next`, saved over `from`, the path they were
+ * made on: the path as saved, or null when it changed meanwhile.
+ */
+ const persist = async (from: ShoppingPath, next: ShoppingPath) => {
+ const saved = await saveDraftShoppingPath(
+ draftId,
+ { builtAt: from.builtAt, savedAt: from.savedAt ?? null },
+ choicesOf(next),
+ );
+ if ('error' in saved) {
+ // A build or another change since it was read: shown as it is now, not overwritten.
+ toast.error(t('changed'));
+ void load();
+ return null;
+ }
+ return saved.path;
+ };
+
+ /**
+ * Builds the path again from the catalog, after `change` (made on `from`)
+ * is saved when there's one. The saved change is shown whether the build
+ * then works or not.
+ */
+ const build = async (change?: { from: ShoppingPath; next: ShoppingPath }) => {
+ setBusy('build');
+ try {
+ if (change) {
+ const saved = await persist(change.from, change.next);
+ if (!saved) return;
+ setState({ status: 'ready', path: saved, none: null });
+ }
+ const result = await buildDraftShoppingPath(draftId, brandId);
+ if (!('error' in result)) {
+ setState({ status: 'ready', path: result.path, none: result.path ? null : result.reason });
+ } else if (result.error === 'changed') {
+ toast.error(t('changed'));
+ void load();
+ } else {
+ toast.error(t(result.error === 'rate_limited' ? 'rateLimited' : 'buildFailed'));
+ }
+ } catch (err) {
+ console.error('Failed to build the shopping path:', err);
+ toast.error(t('saveFailed'));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ /** Saves a change made here (a lock, a removal), shown at once; put back when it fails. */
+ const save = async (from: ShoppingPath, next: ShoppingPath) => {
+ const before = state;
+ setState({ status: 'ready', path: next, none: null });
+ setBusy('save');
+ try {
+ const saved = await persist(from, next);
+ if (saved) setState({ status: 'ready', path: saved, none: null });
+ } catch (err) {
+ console.error('Failed to save the shopping path:', err);
+ toast.error(t('saveFailed'));
+ setState(before);
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const header = (path: ShoppingPath | null) => (
+ <div className="flex items-center gap-2">
+ <ShoppingBag className="h-4 w-4 text-muted-foreground" aria-hidden="true" />
+ <h3 className="text-sm font-semibold">{t('title')}</h3>
+ <span className="flex-1" />
+ {path && (
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ className="h-7 gap-1.5 px-2 text-xs"
+ disabled={busy !== null}
+ onClick={() => void build()}
+ >
+ <RefreshCw className="h-3.5 w-3.5" aria-hidden="true" />
+ {busy === 'build' ? t('building') : t('rebuild')}
+ </Button>
+ )}
+ </div>
+ );
+
+ if (state.status === 'loading') {
+ return (
+ <div className="flex justify-center py-4" aria-busy="true">
+ <LoadingDots className="text-muted-foreground" />
+ </div>
+ );
+ }
+ if (state.status === 'failed') {
+ return (
+ <p className="flex items-center gap-2 text-xs text-muted-foreground">
+ {t('loadError')}
+ <button type="button" className="font-medium underline" onClick={() => void load()}>
+ {t('retry')}
+ </button>
+ </p>
+ );
+ }
+
+ const { path, none, unreadable } = state;
+ if (!path) {
+ return (
+ <section className="space-y-2 rounded-lg border p-3" aria-label={t('title')}>
+ {header(null)}
+ <p className="text-xs text-muted-foreground">
+ {none ? t(`noPath.${none}`) : unreadable ? t('unreadable') : t('empty')}
+ </p>
+ {PICK_AGAIN.includes(none) && (
+ <Button size="sm" disabled={busy !== null} onClick={() => void build()}>
+ {busy === 'build' ? t('building') : t('build')}
+ </Button>
+ )}
+ </section>
+ );
+ }
+
+ const locked = new Set(path.locked);
+ return (
+ <section className="space-y-3 rounded-lg border p-3" aria-label={t('title')}>
+ {header(path)}
+ <p className="text-xs text-muted-foreground">{t('description')}</p>
+
+ <div className="space-y-1 rounded-md border p-2.5">
+ <p className="text-xs text-muted-foreground">{t('category')}</p>
+ {path.categories.length ? (
+ path.categories.map((category, index) => (
+ // Two categories may share a page: the place keeps them apart.
+ <div key={`${index}:${category.name}`} className="space-y-0.5">
+ <div className="flex flex-wrap items-baseline gap-x-2">
+ <span className="text-sm font-medium">{category.name}</span>
+ {category.url && (
+ <a
+ href={category.url}
+ target="_blank"
+ rel="noreferrer"
+ className="min-w-0 text-xs text-muted-foreground underline underline-offset-4 [overflow-wrap:anywhere]"
+ >
+ {pagePath(category.url)}
+ </a>
+ )}
+ </div>
+ <p className="text-xs">{t('categoryPlace')}</p>
+ </div>
+ ))
+ ) : (
+ <p className="text-xs text-muted-foreground">{t('noCategory')}</p>
+ )}
+ </div>
+
+ <div className="flex items-center gap-2">
+ <span className="text-xs text-muted-foreground">
+ {t('products', { count: path.products.length })}
+ </span>
+ <span className="flex-1" />
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ className="h-7 gap-1 px-2 text-xs"
+ aria-expanded={adding}
+ disabled={busy !== null}
+ onClick={() => {
+ setAdding(!adding);
+ setQuery('');
+ }}
+ >
+ <Plus className="h-3.5 w-3.5" aria-hidden="true" />
+ {t('add')}
+ </Button>
+ </div>
+
+ {adding && (
+ <div className="space-y-1.5">
+ <Input
+ type="search"
+ value={query}
+ maxLength={100}
+ placeholder={t('searchPlaceholder')}
+ aria-label={t('searchLabel')}
+ onChange={(e) => setQuery(e.target.value)}
+ autoFocus
+ />
+ {hits === 'failed' && (
+ <p className="text-xs text-muted-foreground" role="alert">
+ {t('searchFailed')}
+ </p>
+ )}
+ {Array.isArray(hits) && hits.length === 0 && (
+ <p className="text-xs text-muted-foreground">{t('searchEmpty')}</p>
+ )}
+ {Array.isArray(hits) && hits.length > 0 && (
+ <ul className="divide-y rounded-md border">
+ {hits.map((hit) => (
+ <li key={hit.id}>
+ <button
+ type="button"
+ className="w-full px-2.5 py-2 text-left text-sm hover:bg-muted disabled:opacity-50"
+ disabled={busy !== null}
+ aria-label={t('addThis', { title: hit.title })}
+ onClick={() => {
+ setAdding(false);
+ setQuery('');
+ void build({ from: path, next: withAdded(path, hit.id) });
+ }}
+ >
+ {hit.title}
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
+
+ {path.products.length === 0 ? (
+ <p className="text-xs text-muted-foreground">{t('noProducts')}</p>
+ ) : (
+ <ul className="space-y-2">
+ {path.products.map((product, index) => {
+ // The page type as it is now: it may have changed since the path was built.
+ const place = placementOf(pageType ?? path.pageType, index);
+ const isLocked = locked.has(product.id);
+ const price = priceText(product);
+ return (
+ <li key={product.id} className="flex items-start gap-2.5 rounded-md border p-2.5">
+ {product.image ? (
+ // eslint-disable-next-line @next/next/no-img-element -- a store's own image, any host
+ <img
+ src={product.image}
+ alt=""
+ className="h-11 w-11 shrink-0 rounded-md border object-cover"
+ />
+ ) : (
+ <div className="h-11 w-11 shrink-0 rounded-md bg-muted" aria-hidden="true" />
+ )}
+ <div className="min-w-0 flex-1 space-y-1">
+ <div className="flex flex-wrap items-baseline gap-x-2">
+ {product.url ? (
+ <a
+ href={product.url}
+ target="_blank"
+ rel="noreferrer"
+ className="text-sm font-medium hover:underline"
+ >
+ {product.title}
+ </a>
+ ) : (
+ <span className="text-sm font-medium">{product.title}</span>
+ )}
+ {price && <span className="text-xs text-muted-foreground">{price}</span>}
+ </div>
+ <div className="flex flex-wrap gap-1.5">
+ <span
+ className={
+ product.availability === 'limited_availability'
+ ? 'rounded-full bg-amber-500/10 px-2 py-0.5 text-[11px] text-amber-700 dark:text-amber-400'
+ : 'rounded-full bg-emerald-500/10 px-2 py-0.5 text-[11px] text-emerald-700 dark:text-emerald-400'
+ }
+ >
+ {product.availability === 'limited_availability'
+ ? t('stock.limited_availability')
+ : t('stock.in_stock')}
+ </span>
+ {product.issues.length > 0 && (
+ <span className="rounded-full bg-amber-500/10 px-2 py-0.5 text-[11px] text-amber-700 dark:text-amber-400">
+ {t('issues', {
+ count: product.issues.length,
+ first: product.issues[0].attribute ?? product.issues[0].code,
+ })}
+ </span>
+ )}
+ {isLocked && (
+ <span className="rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground">
+ {t('locked')}
+ </span>
+ )}
+ </div>
+ <p className="text-xs text-muted-foreground">
+ {t(`place.${place.key}`, { n: place.n })}
+ </p>
+ </div>
+ <div className="flex shrink-0 flex-col items-end gap-1">
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ className="h-7 w-7 p-0"
+ // One name, its state pressed or not; the tooltip says what a click does.
+ aria-label={t('lock', { title: product.title })}
+ aria-pressed={isLocked}
+ title={
+ isLocked
+ ? t('unlock', { title: product.title })
+ : t('lock', { title: product.title })
+ }
+ disabled={busy !== null}
+ onClick={() => void save(path, withLocked(path, product.id, !isLocked))}
+ >
+ {isLocked ? (
+ <Lock className="h-3.5 w-3.5" aria-hidden="true" />
+ ) : (
+ <LockOpen className="h-3.5 w-3.5" aria-hidden="true" />
+ )}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ className="h-7 px-2 text-xs"
+ aria-label={t('swapLabel', { title: product.title })}
+ disabled={busy !== null}
+ onClick={() => void build({ from: path, next: withRemoved(path, product.id) })}
+ >
+ {t('swap')}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ className="h-7 px-2 text-xs"
+ aria-label={t('removeLabel', { title: product.title })}
+ disabled={busy !== null}
+ onClick={() => void save(path, withRemoved(path, product.id))}
+ >
+ {t('remove')}
+ </Button>
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+
+ {path.leftOut.length > 0 && (
+ <div className="space-y-1">
+ <p className="text-xs font-medium text-muted-foreground">{t('leftOut')}</p>
+ <ul className="space-y-0.5 text-xs text-muted-foreground">
+ {path.leftOut.map((item, index) => (
+ <li key={`${index}:${item.id}`}>
+ {item.title ?? t('untitled')} · {t(`reason.${leftOutReason(item.reason)}`)}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ <p className="text-xs text-muted-foreground">{t('lockHint')}</p>
+ </section>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx
index e4850bead..7317e2681 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx
@@ -8,11 +8,13 @@ import { rulesForBrief, useRuleDescriber } from '@/lib/content/agent-write';
import { isPageType, type ContentDraft } from '@/lib/content/drafts';
import type { SiteType } from '@/lib/content/page-types';
import { inputsGiven } from '@/lib/content/draft-inputs';
+import { shoppingPathFits } from '@/lib/content/shopping-path';
import { buildSourceGroups, includedCounts, type DraftSourceKind } from '@/lib/content/sources';
import { formatNumber } from '@/lib/format';
import { BAND_CLASSES, qualityBand, qualityPhase } from '@/lib/content/quality';
import type { ClaimMark } from '@/lib/content/quality-checks';
import { cn } from '@/lib/utils';
+import { ShoppingPathSection } from './_shopping-path';
import { BriefTab, type AgentRewrite } from './_brief-tab';
import { DataNote, UsesYourData } from './_data-note';
import { ImpactTab } from './_impact-tab';
@@ -459,6 +461,13 @@ export function EditorSidePanel({
</button>
</p>
)}
+ {shoppingPathFits(siteType, pageType) && (
+ <ShoppingPathSection
+ draftId={draft.id}
+ brandId={draft.brandId}
+ pageType={pageType}
+ />
+ )}
<BriefTab
draftId={draft.id}
state={reads.brief}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx
index 990d5c564..5e33ab5af 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx
@@ -165,6 +165,13 @@ const brandState = vi.hoisted(() => ({
}));
const updateBrand = vi.hoisted(() => vi.fn());
vi.mock('@/lib/actions/brand', () => ({ updateBrand }));
+// Brief › Shopping path (shopping path, part 3) reads its own path: none here.
+vi.mock('@/lib/actions/shopping-path', () => ({
+ getDraftShoppingPath: vi.fn(async () => ({ path: null })),
+ buildDraftShoppingPath: vi.fn(),
+ saveDraftShoppingPath: vi.fn(),
+ searchCatalogProducts: vi.fn(async () => []),
+}));
vi.mock('@/stores/use-brand-store', () => ({
useBrandStore: (selector: (state: typeof brandState) => unknown) => selector(brandState),
}));
@@ -2875,6 +2882,19 @@ describe('the side panel', () => {
expect(rail()).not.toBeNull();
});
+ // Brief › Shopping path (shopping path, part 3): an online shop's page that links products.
+ it.each([
+ [{ siteType: 'ecommerce', pageType: 'buying_guide' }, true],
+ [{ siteType: 'b2b', pageType: 'buying_guide' }, false],
+ [{ siteType: 'ecommerce', pageType: 'product_page' }, false],
+ ] as const)('shows the shopping path in Brief for %o: %s', async (over, shown) => {
+ getContentDraft.mockResolvedValue(draft(over));
+ window.innerWidth = 1440;
+ await renderPage();
+ await pickTab('Brief');
+ expect(panel()!.querySelector('section[aria-label="Shopping path"]') !== null).toBe(shown);
+ });
+
it('points a page without fan-outs to Sources, where its prompts are added', async () => {
getDraftSources.mockResolvedValue({
data: {
diff --git a/web/src/lib/actions/shopping-path.test.ts b/web/src/lib/actions/shopping-path.test.ts
new file mode 100644
index 000000000..39f93c8f3
--- /dev/null
+++ b/web/src/lib/actions/shopping-path.test.ts
@@ -0,0 +1,248 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/** Brief › Shopping path (shopping path, part 3): read, save, build and search. */
+
+const DRAFT = '77777777-7777-7777-7777-777777777777';
+const BRAND = '33333333-3333-3333-3333-333333333333';
+
+interface Call {
+ table: string;
+ op: string;
+ value?: unknown;
+ filters: [string, string, unknown][];
+}
+let calls: Call[];
+let read: { data: unknown; error: { message: string } | null };
+let written: { data: unknown; error: { message: string } | null };
+let session: { access_token: string } | null;
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => ({
+ auth: { getSession: async () => ({ data: { session } }) },
+ from: (table: string) => {
+ const call: Call = { table, op: 'select', filters: [] };
+ calls.push(call);
+ const result = () => (call.op === 'update' ? written : read);
+ const filter = (kind: string) => (col: string, v: unknown) => (
+ call.filters.push([kind, col, v]),
+ chain
+ );
+ const chain: Record<string, unknown> = {
+ select: () => chain,
+ eq: filter('eq'),
+ is: filter('is'),
+ ilike: filter('ilike'),
+ order: () => chain,
+ limit: () => chain,
+ update: (value: unknown) => ((call.op = 'update'), (call.value = value), chain),
+ maybeSingle: async () => result(),
+ then: (resolve: (r: unknown) => void) => resolve(result()),
+ };
+ return chain;
+ },
+ })),
+}));
+
+const {
+ buildDraftShoppingPath,
+ getDraftShoppingPath,
+ saveDraftShoppingPath,
+ searchCatalogProducts,
+} = await import('./shopping-path');
+
+const product = (id: string) => ({
+ id,
+ title: `Boot ${id}`,
+ url: `https://s.example/p/${id}`,
+ price: 129,
+ salePrice: null,
+ currency: 'USD',
+ availability: 'in_stock',
+ image: null,
+ issues: [],
+ score: 5,
+});
+
+const STORED = {
+ version: 1,
+ builtAt: '2026-10-27T12:00:00.000Z',
+ pageType: 'buying_guide',
+ categories: [],
+ // As the API wrote it: the tab reads it as "limited_availability".
+ products: [{ ...product('a'), availability: 'Limited Availability' }, product('b')],
+ leftOut: [],
+ locked: ['a'],
+ removed: [],
+ added: [],
+};
+
+const fetchMock = vi.fn();
+const respond = (status: number, body: unknown) =>
+ fetchMock.mockResolvedValueOnce(new Response(JSON.stringify(body), { status }));
+
+beforeEach(() => {
+ calls = [];
+ read = { data: null, error: null };
+ written = { data: [{ id: DRAFT }], error: null };
+ session = { access_token: 'jwt' };
+ fetchMock.mockReset();
+ vi.stubGlobal('fetch', fetchMock);
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+});
+
+describe('getDraftShoppingPath', () => {
+ it('reads the path, none until built, and none for a draft it can’t see', async () => {
+ read.data = { shopping_path: STORED };
+ expect(await getDraftShoppingPath(DRAFT)).toMatchObject({
+ path: { builtAt: STORED.builtAt, products: [{ availability: 'limited_availability' }, {}] },
+ });
+ read.data = { shopping_path: null };
+ expect(await getDraftShoppingPath(DRAFT)).toEqual({ path: null });
+ read.data = null;
+ expect(await getDraftShoppingPath(DRAFT)).toBeNull();
+ });
+
+ it('says a kept path it can’t read is unreadable, and a failed read fails', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ read.data = { shopping_path: { ...STORED, version: 2 } };
+ expect(await getDraftShoppingPath(DRAFT)).toEqual({ path: null, unreadable: true });
+ } finally {
+ error.mockRestore();
+ }
+ read = { data: null, error: { message: 'boom' } };
+ await expect(getDraftShoppingPath(DRAFT)).rejects.toThrow('boom');
+ await expect(getDraftShoppingPath('nope')).rejects.toThrow('invalid');
+ });
+});
+
+describe('saveDraftShoppingPath', () => {
+ const choices = { locked: [], removed: ['a'], added: ['c'] };
+
+ it('saves the choices alone, over the path read, its removed products out', async () => {
+ vi.useFakeTimers({ now: new Date('2026-10-27T13:00:00.000Z') });
+ read.data = { shopping_path: STORED };
+ const saved = await saveDraftShoppingPath(DRAFT, { builtAt: STORED.builtAt }, choices);
+
+ const update = calls.find((c) => c.op === 'update')!;
+ // The rest as the API wrote it, not as the tab reads it.
+ expect(update.value).toEqual({
+ shopping_path: {
+ ...STORED,
+ products: [product('b')],
+ locked: [],
+ removed: ['a'],
+ added: ['c'],
+ savedAt: '2026-10-27T13:00:00.000Z',
+ },
+ });
+ expect(update.filters).toEqual([
+ ['eq', 'id', DRAFT],
+ ['eq', 'shopping_path->>builtAt', STORED.builtAt],
+ ['is', 'shopping_path->>savedAt', null],
+ ]);
+ expect(saved).toMatchObject({
+ path: { savedAt: '2026-10-27T13:00:00.000Z', products: [{ id: 'b' }], added: ['c'] },
+ });
+ });
+
+ it('writes only over the last change read', async () => {
+ const savedAt = '2026-10-27T12:30:00.000Z';
+ read.data = { shopping_path: { ...STORED, savedAt } };
+ await saveDraftShoppingPath(DRAFT, { builtAt: STORED.builtAt, savedAt }, choices);
+ expect(calls.find((c) => c.op === 'update')!.filters).toContainEqual([
+ 'eq',
+ 'shopping_path->>savedAt',
+ savedAt,
+ ]);
+ });
+
+ it('says the path changed when it was built or changed since it was read', async () => {
+ read.data = { shopping_path: { ...STORED, builtAt: '2026-10-27T12:45:00.000Z' } };
+ expect(await saveDraftShoppingPath(DRAFT, { builtAt: STORED.builtAt }, choices)).toEqual({
+ error: 'changed',
+ });
+ read.data = { shopping_path: { ...STORED, savedAt: '2026-10-27T12:50:00.000Z' } };
+ expect(await saveDraftShoppingPath(DRAFT, { builtAt: STORED.builtAt }, choices)).toEqual({
+ error: 'changed',
+ });
+ expect(calls.some((c) => c.op === 'update')).toBe(false);
+
+ // Between the read and the write: no row matched.
+ read.data = { shopping_path: STORED };
+ written = { data: [], error: null };
+ expect(await saveDraftShoppingPath(DRAFT, { builtAt: STORED.builtAt }, choices)).toEqual({
+ error: 'changed',
+ });
+ });
+
+ it('refuses choices past the caps, and fails on a failed write', async () => {
+ const ids = Array.from({ length: 41 }, (_, i) => `i${i}`);
+ await expect(
+ saveDraftShoppingPath(DRAFT, { builtAt: STORED.builtAt }, { ...choices, locked: ids }),
+ ).rejects.toThrow('invalid');
+ read.data = { shopping_path: STORED };
+ written = { data: null, error: { message: 'denied' } };
+ await expect(
+ saveDraftShoppingPath(DRAFT, { builtAt: STORED.builtAt }, choices),
+ ).rejects.toThrow('denied');
+ });
+});
+
+describe('buildDraftShoppingPath', () => {
+ it('builds through the API and reads the path it answers', async () => {
+ respond(200, { path: STORED });
+ expect(await buildDraftShoppingPath(DRAFT, BRAND)).toMatchObject({
+ path: { builtAt: STORED.builtAt },
+ });
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toMatch(new RegExp(`/api/content-drafts/${DRAFT}/shopping-path$`));
+ expect(init).toMatchObject({ method: 'POST', body: JSON.stringify({ brandId: BRAND }) });
+ });
+
+ it('says why a draft takes none, a reason added since in general words', async () => {
+ respond(200, { path: null, reason: 'no_match' });
+ expect(await buildDraftShoppingPath(DRAFT, BRAND)).toEqual({ path: null, reason: 'no_match' });
+ respond(200, { path: null, reason: 'paused' });
+ expect(await buildDraftShoppingPath(DRAFT, BRAND)).toEqual({ path: null, reason: 'other' });
+ });
+
+ it('tells a change meanwhile and too many picks from a failure', async () => {
+ respond(409, { error: 'The shopping path changed while it was built', code: 'changed' });
+ expect(await buildDraftShoppingPath(DRAFT, BRAND)).toEqual({ error: 'changed' });
+ respond(429, { success: false, message: 'Too many requests, please try again later.' });
+ expect(await buildDraftShoppingPath(DRAFT, BRAND)).toEqual({ error: 'rate_limited' });
+ respond(502, { code: 'failed' });
+ expect(await buildDraftShoppingPath(DRAFT, BRAND)).toEqual({ error: 'failed' });
+ respond(200, { path: { ...STORED, version: 2 } });
+ expect(await buildDraftShoppingPath(DRAFT, BRAND)).toEqual({ error: 'failed' });
+ session = null;
+ expect(await buildDraftShoppingPath(DRAFT, BRAND)).toEqual({ error: 'failed' });
+ expect(fetchMock).toHaveBeenCalledTimes(4);
+ });
+});
+
+describe('searchCatalogProducts', () => {
+ it('searches the live catalog for the words as typed, wildcards and all', async () => {
+ read.data = [{ id: 'p9', title: '50% off boots', url: null }];
+ expect(await searchCatalogProducts(BRAND, ' 50%_off\\ ')).toEqual([
+ { id: 'p9', title: '50% off boots', url: null },
+ ]);
+ expect(calls[0].filters).toEqual([
+ ['eq', 'brand_id', BRAND],
+ ['is', 'removed_at', null],
+ ['ilike', 'title', '%50\\%\\_off\\\\%'],
+ ]);
+ });
+
+ it('waits for two letters, and fails on a failed read', async () => {
+ expect(await searchCatalogProducts(BRAND, 'a')).toEqual([]);
+ expect(calls).toHaveLength(0);
+ read = { data: null, error: { message: 'boom' } };
+ await expect(searchCatalogProducts(BRAND, 'boots')).rejects.toThrow('boom');
+ });
+});
diff --git a/web/src/lib/actions/shopping-path.ts b/web/src/lib/actions/shopping-path.ts
new file mode 100644
index 000000000..c7ae5abf9
--- /dev/null
+++ b/web/src/lib/actions/shopping-path.ts
@@ -0,0 +1,191 @@
+'use server';
+
+import { z } from 'zod';
+import { API_BASE_URL } from '@/config/api';
+import { createClient } from '@/lib/supabase/server';
+import { jsonbBytes } from '@/lib/content/draft-inputs';
+import {
+ NO_PATH_REASONS,
+ shoppingChoicesSchema,
+ shoppingPathSchema,
+ type NoPathReason,
+ type ShoppingChoices,
+ type ShoppingPath,
+} from '@/lib/content/shopping-path';
+import type { Json } from '@/types/supabase';
+
+/**
+ * A draft's shopping path (shopping path, 00351): read and changed by the
+ * member through RLS, like the brief; built by the API from the brand's
+ * catalog.
+ */
+
+const guid = z.guid();
+/** The column's 64 KB (00351). */
+const MAX_PATH_BYTES = 65_536;
+/** The path a change was made on, by when it was built and last changed. */
+const readAt = shoppingPathSchema.pick({ builtAt: true, savedAt: true });
+
+/**
+ * The draft's shopping path, null until built; `unreadable` when the one
+ * kept isn't a path this tab reads (the API builds over it, as over none).
+ * Null for the whole answer when the draft can't be read.
+ */
+export async function getDraftShoppingPath(
+ draftId: string,
+): Promise<{ path: ShoppingPath | null; unreadable?: true } | null> {
+ if (!guid.safeParse(draftId).success) throw new Error('invalid');
+ const supabase = await createClient();
+ const { data, error } = await supabase
+ .from('content_drafts')
+ .select('shopping_path')
+ .eq('id', draftId)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!data) return null;
+ if (data.shopping_path == null) return { path: null };
+ const parsed = shoppingPathSchema.safeParse(data.shopping_path);
+ if (!parsed.success) {
+ console.error('The shopping path can’t be read:', parsed.error.issues.slice(0, 3));
+ return { path: null, unreadable: true };
+ }
+ return { path: parsed.data };
+}
+
+/**
+ * Saves the person's choices (locks, removals, additions) on the path they
+ * were made on, its removed products out of the page; the rest of the path
+ * stays as the API wrote it. Written only over the path read (its `builtAt`
+ * and `savedAt`), so a build or another change since is never overwritten:
+ * returned, not thrown, as 'changed', for the tab to read it again.
+ */
+export async function saveDraftShoppingPath(
+ draftId: string,
+ read: { builtAt: string; savedAt?: string | null },
+ choices: ShoppingChoices,
+): Promise<{ path: ShoppingPath } | { error: 'changed' }> {
+ const at = readAt.safeParse(read);
+ const chosen = shoppingChoicesSchema.safeParse(choices);
+ if (!guid.safeParse(draftId).success || !at.success || !chosen.success) {
+ throw new Error('invalid');
+ }
+ const savedAt = at.data.savedAt ?? null;
+ const supabase = await createClient();
+ const { data, error } = await supabase
+ .from('content_drafts')
+ .select('shopping_path')
+ .eq('id', draftId)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!data) throw new Error('not_found');
+ const stored = shoppingPathSchema.safeParse(data.shopping_path);
+ if (
+ !stored.success ||
+ stored.data.builtAt !== at.data.builtAt ||
+ (stored.data.savedAt ?? null) !== savedAt
+ ) {
+ return { error: 'changed' };
+ }
+ // The path as kept, not as read: its links and stock as the API wrote them.
+ const kept = data.shopping_path as { products: { id: string }[] } & Record<string, Json>;
+ const removed = new Set(chosen.data.removed);
+ const next = {
+ ...kept,
+ ...chosen.data,
+ products: kept.products.filter((p) => !removed.has(p.id)),
+ savedAt: new Date().toISOString(),
+ };
+ if (jsonbBytes(next) > MAX_PATH_BYTES) throw new Error('too_long');
+ let write = supabase
+ .from('content_drafts')
+ .update({ shopping_path: next as unknown as Json })
+ .eq('id', draftId)
+ .eq('shopping_path->>builtAt', at.data.builtAt);
+ write = savedAt
+ ? write.eq('shopping_path->>savedAt', savedAt)
+ : write.is('shopping_path->>savedAt', null);
+ const { data: written, error: writeError } = await write.select('id');
+ if (writeError) throw new Error(writeError.message);
+ if (!written?.length) return { error: 'changed' };
+ return { path: shoppingPathSchema.parse(next) };
+}
+
+/**
+ * Why a build gave no path: 'changed' when the path changed while it was
+ * built (read it again), 'rate_limited' past the API's bucket, else 'failed'.
+ */
+export type BuildShoppingPathError = 'failed' | 'changed' | 'rate_limited';
+
+export type BuildShoppingPathResult =
+ | { path: ShoppingPath }
+ | { path: null; reason: NoPathReason }
+ | { error: BuildShoppingPathError };
+
+/** Builds the draft's shopping path again from the catalog, the person's choices kept. */
+export async function buildDraftShoppingPath(
+ draftId: string,
+ brandId: string,
+): Promise<BuildShoppingPathResult> {
+ if (!guid.safeParse(draftId).success || !guid.safeParse(brandId).success) {
+ return { error: 'failed' };
+ }
+ const supabase = await createClient();
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
+ if (!session) return { error: 'failed' };
+ try {
+ const res = await fetch(`${API_BASE_URL}/api/content-drafts/${draftId}/shopping-path`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${session.access_token}`,
+ },
+ body: JSON.stringify({ brandId }),
+ });
+ const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
+ if (res.status === 429) return { error: 'rate_limited' };
+ if (res.status === 409 && body.code === 'changed') return { error: 'changed' };
+ if (!res.ok) return { error: 'failed' };
+ if (body.path === null) {
+ const known: readonly unknown[] = NO_PATH_REASONS;
+ // A reason the API added since is said in general words.
+ const reason = known.includes(body.reason) ? (body.reason as NoPathReason) : 'other';
+ return { path: null, reason };
+ }
+ const path = shoppingPathSchema.safeParse(body.path);
+ return path.success ? { path: path.data } : { error: 'failed' };
+ } catch (err) {
+ console.error('Failed to build the shopping path:', err);
+ return { error: 'failed' };
+ }
+}
+
+/** A catalog product as Add product finds it. */
+export interface CatalogProductHit {
+ id: string;
+ title: string;
+ url: string | null;
+}
+
+/** The brand's live catalog products whose title holds `query`, a few at a time. */
+export async function searchCatalogProducts(
+ brandId: string,
+ query: string,
+): Promise<CatalogProductHit[]> {
+ const text = query.trim().slice(0, 100);
+ if (!guid.safeParse(brandId).success || text.length < 2) return [];
+ // The pattern's own characters as text: a search for "50%" isn't a wildcard.
+ const pattern = `%${text.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
+ const supabase = await createClient();
+ const { data, error } = await supabase
+ .from('catalog_products')
+ .select('id, title, url')
+ .eq('brand_id', brandId)
+ .is('removed_at', null)
+ .ilike('title', pattern)
+ .order('title')
+ .limit(8);
+ if (error) throw new Error(error.message);
+ return (data ?? []).map((p) => ({ id: p.id, title: p.title, url: p.url ?? null }));
+}
diff --git a/web/src/lib/content/shopping-path.test.ts b/web/src/lib/content/shopping-path.test.ts
new file mode 100644
index 000000000..4664c5b6b
--- /dev/null
+++ b/web/src/lib/content/shopping-path.test.ts
@@ -0,0 +1,142 @@
+import { describe, expect, it } from 'vitest';
+import {
+ MAX_REMOVED,
+ leftOutReason,
+ placementOf,
+ shoppingPathFits,
+ shoppingPathSchema,
+ withAdded,
+ withLocked,
+ withRemoved,
+ type ShoppingPath,
+} from './shopping-path';
+
+/** A draft's shopping path as the Brief tab holds it (shopping path, 00351). */
+
+const product = (id: string) => ({
+ id,
+ title: `Boot ${id}`,
+ url: `https://s.example/p/${id}`,
+ price: 129,
+ salePrice: null,
+ currency: 'USD',
+ availability: 'in_stock',
+ image: null,
+ issues: [],
+ score: 5,
+});
+
+const PATH: ShoppingPath = {
+ version: 1,
+ builtAt: '2026-10-27T12:00:00.000Z',
+ pageType: 'buying_guide',
+ categories: [{ name: 'Hiking Boots', url: 'https://s.example/c/hiking-boots', title: null }],
+ products: [product('a'), product('b')],
+ leftOut: [{ id: 'c', title: 'Boot c', reason: 'sold_out' }],
+ locked: ['a'],
+ removed: [],
+ added: ['b'],
+};
+
+describe('shoppingPathFits', () => {
+ it('fits the page types that link products, on an online shop only', () => {
+ expect(shoppingPathFits('ecommerce', 'buying_guide')).toBe(true);
+ expect(shoppingPathFits('ecommerce', 'blog_post')).toBe(true);
+ expect(shoppingPathFits('ecommerce', 'product_page')).toBe(false);
+ expect(shoppingPathFits('ecommerce', null)).toBe(false);
+ expect(shoppingPathFits('b2b', 'buying_guide')).toBe(false);
+ });
+});
+
+describe('placementOf', () => {
+ it("names a product's place by page type", () => {
+ expect(placementOf('best_of', 0)).toEqual({ key: 'pick', n: 1 });
+ expect(placementOf('comparison', 2)).toEqual({ key: 'compared', n: 3 });
+ expect(placementOf('blog_post', 1)).toEqual({ key: 'linked', n: 2 });
+ });
+});
+
+describe('changes', () => {
+ it('removes a product for good, locks and unlocks one, and adds one', () => {
+ const removed = withRemoved(PATH, 'a');
+ expect(removed.products.map((p) => p.id)).toEqual(['b']);
+ expect(removed.locked).toEqual([]);
+ expect(removed.removed).toEqual(['a']);
+
+ expect(withLocked(PATH, 'b', true).locked).toEqual(['a', 'b']);
+ expect(withLocked(PATH, 'a', false).locked).toEqual([]);
+
+ const added = withAdded(removed, 'a');
+ expect(added.added).toEqual(['b', 'a']);
+ expect(added.removed).toEqual([]);
+ });
+
+ it("keeps to the API's caps: past them, the oldest removal is forgotten", () => {
+ const full = { ...PATH, removed: Array.from({ length: MAX_REMOVED }, (_, i) => `r${i}`) };
+ const removed = withRemoved(full, 'a').removed;
+ expect(removed).toHaveLength(MAX_REMOVED);
+ expect(removed[0]).toBe('r1');
+ expect(removed.at(-1)).toBe('a');
+ });
+});
+
+describe('shoppingPathSchema', () => {
+ it("reads the API's path, and refuses another shape", () => {
+ expect(shoppingPathSchema.safeParse(PATH).success).toBe(true);
+ expect(shoppingPathSchema.safeParse({ ...PATH, version: 2 }).success).toBe(false);
+ });
+
+ it('keeps the time of the last change, which a save and a build write over', () => {
+ const saved = { ...PATH, savedAt: '2026-10-27T13:00:00.000Z' };
+ expect(shoppingPathSchema.parse(saved).savedAt).toBe('2026-10-27T13:00:00.000Z');
+ expect(shoppingPathSchema.parse(PATH).savedAt).toBeUndefined();
+ });
+
+ it('reads a product gone from the catalog, with no title, and a reason added since', () => {
+ const leftOut = [
+ { id: 'x', title: null, reason: 'gone' },
+ { id: 'y', title: 'Boot y', reason: 'recalled' },
+ ];
+ expect(shoppingPathSchema.parse({ ...PATH, leftOut }).leftOut).toEqual(leftOut);
+ expect(leftOutReason('gone')).toBe('gone');
+ expect(leftOutReason('recalled')).toBe('other');
+ });
+
+ it("refuses a path past the API's caps", () => {
+ const products = Array.from({ length: 41 }, (_, i) => product(`p${i}`));
+ expect(shoppingPathSchema.safeParse({ ...PATH, products }).success).toBe(false);
+ const issues = Array.from({ length: 21 }, (_, i) => ({ code: `c${i}`, attribute: null }));
+ expect(
+ shoppingPathSchema.safeParse({ ...PATH, products: [{ ...product('a'), issues }] }).success,
+ ).toBe(false);
+ const leftOut = Array.from({ length: 11 }, (_, i) => ({
+ id: `l${i}`,
+ title: null,
+ reason: 'gone',
+ }));
+ expect(shoppingPathSchema.safeParse({ ...PATH, leftOut }).success).toBe(false);
+ const ids = (n: number) => Array.from({ length: n }, (_, i) => `i${i}`);
+ expect(shoppingPathSchema.safeParse({ ...PATH, locked: ids(41) }).success).toBe(false);
+ expect(shoppingPathSchema.safeParse({ ...PATH, added: ids(41) }).success).toBe(false);
+ expect(shoppingPathSchema.safeParse({ ...PATH, removed: ids(200) }).success).toBe(true);
+ expect(shoppingPathSchema.safeParse({ ...PATH, removed: ids(201) }).success).toBe(false);
+ const long = { ...product('a'), title: 'x'.repeat(201) };
+ expect(shoppingPathSchema.safeParse({ ...PATH, products: [long] }).success).toBe(false);
+ });
+
+ it('reads stock as the API spells it, and only http(s) links', () => {
+ const read = shoppingPathSchema.parse({
+ ...PATH,
+ categories: [{ name: 'Boots', url: 'javascript:alert(1)', title: null }],
+ products: [
+ { ...product('a'), availability: 'Limited Availability', image: 'data:image/png;base64,x' },
+ { ...product('b'), url: '/p/b', availability: 'IN-STOCK', image: 'http://s.example/b.jpg' },
+ ],
+ });
+ expect(read.categories[0].url).toBeNull();
+ expect(read.products.map((p) => [p.url, p.availability, p.image])).toEqual([
+ ['https://s.example/p/a', 'limited_availability', null],
+ [null, 'in_stock', 'http://s.example/b.jpg'],
+ ]);
+ });
+});
diff --git a/web/src/lib/content/shopping-path.ts b/web/src/lib/content/shopping-path.ts
new file mode 100644
index 000000000..185f59e4a
--- /dev/null
+++ b/web/src/lib/content/shopping-path.ts
@@ -0,0 +1,178 @@
+import { z } from 'zod';
+import type { SiteType } from '@/lib/content/page-types';
+
+/**
+ * A draft's shopping path (shopping path, 00351), as the Brief tab shows it:
+ * the category pages and catalog products the page links on an online shop,
+ * the products left out and why, and the person's locks, removals and
+ * additions. The API picks them (server/src/lib/shopping-path.js); the
+ * person changes them here.
+ */
+
+/**
+ * The page types a shopping path fits, and how many products each links: a
+ * copy of the API's PRODUCTS_FOR (server/src/lib/shopping-path.js), which
+ * decides; change both together.
+ */
+export const PRODUCTS_FOR: Record<string, number> = {
+ best_of: 8,
+ buying_guide: 5,
+ comparison: 4,
+ alternatives: 4,
+ guide: 4,
+ blog_post: 3,
+};
+
+/**
+ * The path's caps, the API's (server/src/lib/shopping-path.js): products,
+ * issues a product, left out, the person's locks and additions (each), and
+ * removals; a product's or a page's title in characters.
+ */
+export const MAX_PRODUCTS = 40;
+export const MAX_ISSUES = 20;
+export const MAX_LEFT_OUT = 10;
+export const MAX_KEPT = 40;
+export const MAX_REMOVED = 200;
+export const TITLE_CHARS = 200;
+
+/** Whether a page of this type on this kind of site takes a shopping path. */
+export function shoppingPathFits(siteType: SiteType, pageType: string | null): boolean {
+ return siteType === 'ecommerce' && pageType != null && Object.hasOwn(PRODUCTS_FOR, pageType);
+}
+
+/** Why a product is left out, as the API says it: sold out, refused, no link, gone from the catalog. */
+export const LEFT_OUT_REASONS = ['sold_out', 'refused', 'no_link', 'gone'] as const;
+export type LeftOutReason = (typeof LEFT_OUT_REASONS)[number];
+
+/** A left-out reason as the Brief tab words it: 'other' for one the API added since. */
+export function leftOutReason(reason: string): LeftOutReason | 'other' {
+ return (LEFT_OUT_REASONS as readonly string[]).includes(reason)
+ ? (reason as LeftOutReason)
+ : 'other';
+}
+
+/**
+ * Why a draft has no shopping path, as the API says it: not a shop, a page
+ * type that takes none, no catalog, nothing in it for the topic; 'other'
+ * for one the API added since.
+ */
+export const NO_PATH_REASONS = ['not_a_shop', 'page_type', 'no_catalog', 'no_match'] as const;
+export type NoPathReason = (typeof NO_PATH_REASONS)[number] | 'other';
+
+const id = z.string().min(1).max(100);
+const title = z.string().max(TITLE_CHARS);
+/** A link the tab follows: http(s) only; any other (javascript:, a relative path) is read as none. */
+const link = z
+ .string()
+ .max(2048)
+ .transform((url) => (/^https?:\/\//i.test(url) ? url : null));
+/** As the API's stock.js spells it: lowercased, spaces and hyphens as "_". */
+const stock = z.string().transform((s) => s.toLowerCase().replace(/[\s-]+/g, '_'));
+const time = z.string().min(1).max(40);
+
+/**
+ * The path as content_drafts.shopping_path keeps it, read for the tab only:
+ * links and stock are cleaned on the way in, so a change is never saved
+ * from it (saveDraftShoppingPath saves the person's choices alone).
+ * `savedAt` is the person's last change: a save, and a build, write only
+ * over the path they read.
+ */
+export const shoppingPathSchema = z.object({
+ version: z.literal(1),
+ builtAt: time,
+ savedAt: time.nullish(),
+ pageType: z.string().nullable(),
+ categories: z.array(z.object({ name: z.string(), url: link, title: title.nullable() })).max(5),
+ products: z
+ .array(
+ z.object({
+ id,
+ title,
+ url: link,
+ price: z.number().nullable(),
+ salePrice: z.number().nullable(),
+ currency: z.string().nullable(),
+ availability: stock,
+ image: link.nullable(),
+ issues: z
+ .array(z.object({ code: z.string(), attribute: z.string().nullable() }))
+ .max(MAX_ISSUES),
+ score: z.number(),
+ }),
+ )
+ .max(MAX_PRODUCTS),
+ leftOut: z
+ .array(
+ z.object({
+ id,
+ // Null for a kept product the catalog no longer has, and no path named.
+ title: title.nullable(),
+ // Any reason: one the API added since is worded as 'other' (leftOutReason).
+ reason: z.string().min(1).max(40),
+ }),
+ )
+ .max(MAX_LEFT_OUT),
+ locked: z.array(id).max(MAX_KEPT),
+ removed: z.array(id).max(MAX_REMOVED),
+ added: z.array(id).max(MAX_KEPT),
+});
+
+/** The person's choices, all a save writes. */
+export const shoppingChoicesSchema = shoppingPathSchema.pick({
+ locked: true,
+ removed: true,
+ added: true,
+});
+
+export type ShoppingPath = z.infer<typeof shoppingPathSchema>;
+export type ShoppingProduct = ShoppingPath['products'][number];
+export type ShoppingChoices = z.infer<typeof shoppingChoicesSchema>;
+
+/** The person's choices in a path. */
+export function choicesOf(path: ShoppingPath): ShoppingChoices {
+ return { locked: path.locked, removed: path.removed, added: path.added };
+}
+
+/**
+ * Where a product goes on the page, by page type: a list's picks, a
+ * comparison's options, or a link in the text. `index` counts from 0.
+ */
+export function placementOf(
+ pageType: string | null,
+ index: number,
+): { key: 'pick' | 'compared' | 'linked'; n: number } {
+ if (pageType === 'best_of' || pageType === 'buying_guide') return { key: 'pick', n: index + 1 };
+ if (pageType === 'comparison' || pageType === 'alternatives') {
+ return { key: 'compared', n: index + 1 };
+ }
+ return { key: 'linked', n: index + 1 };
+}
+
+/**
+ * The path with a product removed: out of the page, and never picked again.
+ * Past MAX_REMOVED, the oldest removal is forgotten.
+ */
+export function withRemoved(path: ShoppingPath, productId: string): ShoppingPath {
+ return {
+ ...path,
+ products: path.products.filter((p) => p.id !== productId),
+ locked: path.locked.filter((p) => p !== productId),
+ added: path.added.filter((p) => p !== productId),
+ removed: [...new Set([...path.removed, productId])].slice(-MAX_REMOVED),
+ };
+}
+
+/** The path with a product locked, or unlocked: a locked one stays when the path is built again. */
+export function withLocked(path: ShoppingPath, productId: string, locked: boolean): ShoppingPath {
+ const rest = path.locked.filter((p) => p !== productId);
+ return { ...path, locked: locked ? [...rest, productId].slice(-MAX_KEPT) : rest };
+}
+
+/** The path with a product added by the person: kept, and no longer removed. */
+export function withAdded(path: ShoppingPath, productId: string): ShoppingPath {
+ return {
+ ...path,
+ added: [...new Set([...path.added, productId])].slice(-MAX_KEPT),
+ removed: path.removed.filter((p) => p !== productId),
+ };
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 152aa3c30..39136b1f1 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -1305,6 +1305,7 @@ export type Database = {
source_url: string | null
score_after: number | null
score_before: number | null
+ shopping_path: Json | null
slug: string | null
status: string
title: string
@@ -1346,6 +1347,7 @@ export type Database = {
source_url?: string | null
score_after?: number | null
score_before?: number | null
+ shopping_path?: Json | null
slug?: string | null
status?: string
title?: string
@@ -1387,6 +1389,7 @@ export type Database = {
source_url?: string | null
score_after?: number | null
score_before?: number | null
+ shopping_path?: Json | null
slug?: string | null
status?: string
title?: string