Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(content): check a page's shopping links in Rules and Before you publish (shopping path, part 6) (#1610)
Cihan3f6a4d4bdc52
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 6a56904ae..888a6e869 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -4080,6 +4080,7 @@"nothingToFixLocked": "Content Agent's changes were all in passages AI answers quote, which it keeps. Unlock the ones you're fine to change (Edit anyway), or change them yourself.","notForAgent": "Content Agent doesn't change heading levels: make the extra H1s H2s in the toolbar.","notForAgentFeed": "Content Agent doesn't change a price, GTIN or stock: check which is right, the page or your product feed, and fix that one.",+ "notForAgentShopping": "Content Agent doesn't change which products the page links: remove or replace the links to sold-out, refused or gone products yourself.","decideFirst": "{count, plural, one {Review the open suggestion first, then run the agent.} other {Review the open suggestions first, then run the agent.}}","citedLoading": "Reading which passages AI quotes, so the agent leaves them as they are…","agentBusy": "Content Agent is already working on this page. Wait for it to finish.",@@ -5053,6 +5054,20 @@"otherDetail": "Check what your CMS adds for it (Product, ItemList…). The code Ansvisor gives here is for articles.","otherDetailTyped": "Check what your CMS adds for it. The code Ansvisor gives here is for articles, product pages and category pages."},+ "shopping": {+ "title": "Shopping links",+ "reading": "Reading your catalog for the linked products' stock…",+ "failed": "Couldn't read your catalog: check the products the page links are in stock before you publish.",+ "ok": "Shopping links work",+ "okDetail": "{count, plural, =0 {{category, select, yes {No product linked yet; the category page is.} other {No product linked yet.}}} one {# product linked, in stock and accepted by Merchant Center.} other {# products linked, in stock and accepted by Merchant Center.}}",+ "bad": "{count, plural, one {# product link to remove or replace} other {# product links to remove or replace}}",+ "badDetail": "{list}{more, plural, =0 {} other { +# more}}. Remove or replace these links on the page: Brief › Shopping path lists products that sell.",+ "item": "{title} ({state, select, sold_out {sold out} refused {Merchant Center refuses it} gone {no longer in the catalog} other {check it}})",+ "noCategory": "No link to the category page",+ "noCategoryDetail": "Link the category page in Brief › Shopping path, so readers reach the products.",+ "few": "{count} of {want} products linked",+ "fewDetail": "Link more of the products in Brief › Shopping path that are in stock: a product card or grid counts."+ },"disclosure": {"ok": "Disclosure","okDetail": "The page says so: \"{line}\"",@@ -5520,6 +5535,9 @@"fairness": "Fair: name where the competitor wins","specsTable": "Specs table","feedMatch": "Price, GTIN and stock match the feed",+ "shopCategoryLink": "Links its category page",+ "shopProductLinks": "Links the shopping path's products",+ "shopLinksLive": "No sold-out or refused product linked","fitQuestions": "Answer fit and sizing questions","first40Words": "Type + key attributes in the first 40 words","introText": "Intro text above products",@@ -5543,6 +5561,9 @@"whoFor": "Who the page is for, in one sentence, e.g. \"Sales leaders at 20–200 person B2B teams\".","first40Words": "ChatGPT reads about the first 50 tokens (~40 words) of a product description. The rest is ignored.","feedMatch": "Checked against the product in your product feed with this page's URL, or else its name: the price, any GTIN the page gives, and the stock, where both say them.",+ "shopCategoryLink": "A link to the category page in Brief › Shopping path, so readers and AI answers reach the products.",+ "shopProductLinks": "Links to the products in Brief › Shopping path that are in stock and accepted by Merchant Center: this many, or all of them when fewer are. A product card or grid counts.",+ "shopLinksLive": "Every product the page links from its shopping path, or removed from it, is in stock, accepted by Merchant Center for free listings, and still in the catalog. Remove or replace a link to one that isn't, on the page.","definitionFirst": "The paragraph under the H1 says what the term is (\"X is …\") in a few words: what answer engines quote for \"what is\" prompts.","measureSteps": "The longest numbered list on the page counts as the steps."},@@ -5591,6 +5612,9 @@"notHowTo": "Not a how-to","englishOnly": "English only","noSizes": "No sizes",+ "noShoppingPath": "Pick in Brief",+ "shoppingReading": "Reading catalog",+ "shoppingFailed": "Couldn't read","numberCheck": "Number check"},"mineName": "My rules · {type}",@@ -5631,6 +5655,8 @@"heldAll": "What's left open is kept by AI citations, and yours to decide: the agent leaves passages AI answers quote as they are.","heldLength": "Only the Length is left open, and a rewrite can't reach it. Raise the Length, or leave it.","heldSentence": "Kept by AI citations · yours to decide: the long sentences are in passages AI answers quote, which the agent keeps. Shorten them yourself (Edit anyway), or leave them quoted.",+ "shopLinksLiveNote": "{list}{more, plural, =0 {} other { +# more}}: remove or replace these links on the page.",+ "shopItem": "{title} ({state, select, sold_out {sold out} refused {Merchant Center refuses it} gone {no longer in the catalog} other {check it}})","fixTrace": "Fix","fixTraceHint": "Content Agent rewrites only these phrases, for you to review","agent": {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsxindex 6e94f9144..6afd18ef4 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsx@@ -6,6 +6,7 @@ import messages from '../../../../../../../../messages/en.json';import type { ContentAuthor } from '@/lib/content/authors';import { eeat, trust, trustBlocks, type TrustRead } from '@/lib/content/quality-checks';import { qualityTodos } from '@/lib/content/quality-todos';+import type { ShoppingLinks } from '@/lib/content/shopping-check';import type { SiteTrust } from '@/lib/content/site-trust';const toast = vi.hoisted(() => Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }));@@ -106,6 +107,7 @@ async function render(disclosureAdded = false,product = null as Parameters<typeof BeforePublish>[0]['product'],category = null as Parameters<typeof BeforePublish>[0]['category'],+ shopping = null as Parameters<typeof BeforePublish>[0]['shopping'],} = {},) {await act(async () => {@@ -126,6 +128,7 @@ async function render(linksPending={linksPending}product={product}category={category}+ shopping={shopping}onMarkReady={onMarkReady}onFixFirst={onFixFirst}disclosureLine={disclosureLine}@@ -182,6 +185,82 @@ afterEach(() => {});describe('BeforePublish', () => {+ describe('shopping links (shopping path)', () => {+ const product = (title: string, state: 'ok' | 'sold_out' | 'refused' | 'gone') => ({+ key: `shop.example/products/${title}`,+ title,+ state,+ inPath: true,+ });+ const links = (over: Partial<ShoppingLinks> = {}): ShoppingLinks => ({+ categoryLinked: true,+ linked: [],+ bad: [],+ products: 4,+ want: 0,+ categories: 1,+ ...over,+ });+ const shoppingRow = () => rows().find((r) => r?.startsWith('Shopping links'));++ it('names the links to remove or replace, the first three and how many more', async () => {+ await render(quality(), {+ shopping: links({ bad: [product('Canyon', 'sold_out'), product('Ridge', 'refused')] }),+ });+ const bad = rows().find((r) => r?.startsWith('2 product links to remove or replace'));+ expect(bad).toContain(+ 'Canyon (sold out), Ridge (Merchant Center refuses it). Remove or replace these links on the page',+ );++ const five = ['A', 'B', 'C', 'D', 'E'].map((t) => product(t, 'gone'));+ await render(quality(), { shopping: links({ bad: five }) });+ expect(rows().find((r) => r?.startsWith('5 product links'))).toContain(+ 'A (no longer in the catalog), B (no longer in the catalog), C (no longer in the catalog) +2 more.',+ );+ });++ it('asks for the category page, then the products the rule wants', async () => {+ await render(quality(), { shopping: links({ categoryLinked: false, want: 3 }) });+ expect(rows().join('|')).toContain('No link to the category page');++ await render(quality(), {+ shopping: links({ linked: [product('Summit', 'ok')], want: 3 }),+ });+ expect(rows().join('|')).toContain('1 of 3 products linked');+ expect(rows().join('|')).not.toContain('Shopping links work');+ });++ it('says they work, with the words for no product linked by whether the category page is', async () => {+ await render(quality(), {+ shopping: links({ linked: [product('Summit', 'ok')], want: 1 }),+ });+ expect(rows().find((r) => r?.startsWith('Shopping links work'))).toContain(+ '1 product linked, in stock and accepted by Merchant Center.',+ );++ await render(quality(), { shopping: links() });+ expect(rows().find((r) => r?.startsWith('Shopping links work'))).toContain(+ 'No product linked yet; the category page is.',+ );+ await render(quality(), { shopping: links({ categories: 0, categoryLinked: false }) });+ const none = rows().find((r) => r?.startsWith('Shopping links work'));+ expect(none).toContain('No product linked yet.');+ expect(none).not.toContain('category page');+ });++ it('says the catalog is being read, or couldn’t be, and shows no row without a path', async () => {+ await render(quality(), { shopping: 'reading' });+ expect(shoppingRow()).toBe(+ "Shopping links · check itReading your catalog for the linked products' stock…",+ );+ await render(quality(), { shopping: 'failed' });+ expect(rows().join('|')).toContain("Couldn't read your catalog");++ await render(quality());+ expect(rows().join('|')).not.toContain('Shopping links');+ });+ });+it('warns under Trust 60 with the biggest reason, and logs Mark ready anyway', async () => {expect(lowTrust.score).toBe(37);await render(quality());diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsxindex 886324746..109c109a1 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx@@ -27,6 +27,7 @@ import {} from '@/lib/content/page-schema';import { qualityPhase } from '@/lib/content/quality';import { checksOff } from '@/lib/content/quality-profiles';+import { listed, type ShoppingLinks } from '@/lib/content/shopping-check';import { cn } from '@/lib/utils';import { copyToClipboard } from './_html-block';import { trustSuggestions, type QualityRead } from './_quality-tab';@@ -100,7 +101,15 @@ export function BeforePublish({onAddDisclosure,product = null,category = null,+ shopping = null,}: {+ /**+ * The page's shopping links against the catalog now (shopping path, part+ * 6): the products that no longer sell, the category page, the products+ * linked; 'reading' while it's read again, 'failed' when it couldn't be;+ * null on a page without a shopping path.+ */+ shopping?: ShoppingLinks | 'reading' | 'failed' | null;/*** Phase 3 (CE-053): a product page's Product schema, from its opening* paragraph, its images and the price it states (pageOffer); null on@@ -352,6 +361,7 @@ export function BeforePublish({},]: []),+ ...(shopping ? [shoppingRow(t, shopping)] : []),{ ...readyRow(t, paste, linksPending), fill: paste.placeholders > 0 },];@@ -571,3 +581,49 @@ function readyRow(t: T, paste: ReadyToPaste, linksPending: number): Row {}return { state: 'ok', title: t('paste.title'), detail: t('paste.ok') };}++/**+ * The shopping links' row (shopping path, part 6): the products the page+ * links that no longer sell, by name, to remove or replace on the page;+ * else a missing link to the category page; else too few products linked;+ * else how many work. While the catalog is read, or when it can't be, a+ * check of its own.+ */+function shoppingRow(t: T, shopping: ShoppingLinks | 'reading' | 'failed'): Row {+ if (shopping === 'reading' || shopping === 'failed') {+ return { state: 'check', title: t('shopping.title'), detail: t(`shopping.${shopping}`) };+ }+ if (shopping.bad.length) {+ const { shown, more } = listed(shopping.bad);+ return {+ state: 'missing',+ title: t('shopping.bad', { count: shopping.bad.length }),+ detail: t('shopping.badDetail', {+ list: shown.map((p) => t('shopping.item', { title: p.title, state: p.state })).join(', '),+ more,+ }),+ };+ }+ if (shopping.categories > 0 && !shopping.categoryLinked) {+ return {+ state: 'missing',+ title: t('shopping.noCategory'),+ detail: t('shopping.noCategoryDetail'),+ };+ }+ if (shopping.linked.length < shopping.want) {+ return {+ state: 'missing',+ title: t('shopping.few', { count: shopping.linked.length, want: shopping.want }),+ detail: t('shopping.fewDetail'),+ };+ }+ return {+ state: 'ok',+ title: t('shopping.ok'),+ detail: t('shopping.okDetail', {+ count: shopping.linked.length,+ category: shopping.categoryLinked ? 'yes' : 'no',+ }),+ };+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsxindex 512699e62..1c54e38a2 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx@@ -184,12 +184,14 @@ import {lengthOutOfReach,readPage,pageTextLength,+ ruleNumber,rulesMet,type ActiveRule,type LastRewrite,type RewriteReach,type RuleStatus,} from '@/lib/content/rules';+import { shoppingLinks, type ShoppingLinks } from '@/lib/content/shopping-check';import { aiUsageTone } from '@/lib/billing/ai-usage';import { saveBlob } from '@/lib/download';import { formatMonthDay } from '@/lib/format';@@ -273,6 +275,7 @@ import { useDraftInputs } from './_use-draft-inputs';import { useDraftReads } from './_use-draft-reads';import { useDraftRules } from './_use-draft-rules';import { EditorToolbar } from './_toolbar';+import { useShoppingCheck } from './_use-shopping-check';import { useDraftAutosave, type SaveState } from './_use-autosave';/**@@ -706,6 +709,9 @@ export function DraftEditor({catalogRead.title.trim().toLowerCase() === title.trim().toLowerCase())? catalogRead.read: undefined;+ // The shopping path against the catalog now, for the Shopping rules and+ // Before you publish (shopping path, part 6).+ const shoppingCheck = useShoppingCheck({ draftId: draft.id, siteType, pageType });const rules = useDraftRules({draft,siteType,@@ -714,6 +720,7 @@ export function DraftEditor({pageType,reads,catalog: feedOn ? (catalog === undefined ? 'reading' : catalog) : null,+ shopping: shoppingCheck.check,});// What a page rewrite keeps as it is (the passages AI answers quote, tables,// images…), read as the characters are, and the least it comes to with the@@ -2062,9 +2069,11 @@ export function DraftEditor({const rulesSettled =rules.ready &&reads.sources !== null &&- // The keywords rule reads the brief, the feed rule the catalog.+ // The keywords rule reads the brief, the feed rule the catalog, the+ // Shopping rules the shopping path.reads.brief.status !== 'loading' &&- (!feedOn || catalog !== undefined);+ (!feedOn || catalog !== undefined) &&+ shoppingCheck.check !== 'reading';// Open rules no run can close on this page (editor test 2026-10-25): every// long sentence inside a passage AI answers quote, a Length out of a// rewrite's reach. They leave the agent's work and Next step; the Rules tab@@ -3157,7 +3166,23 @@ export function DraftEditor({) => {setPublishOpen({ mode, html: pageToPublish(), returnTo });if (mode === 'markReady') nudgeAt('markReady');+ // A product may have sold out since the check was read.+ shoppingCheck.reload();};+ // The page to publish's shopping links against the catalog (shopping path,+ // part 6), as the Shopping rules read them: every link, a product grid's+ // too, and the products the rule asks for (none with it off). Read fresh:+ // 'reading' meanwhile, for a draft known to have a path. No row while+ // none is known to, so a draft without one never shows it.+ const shopRule = rules.rules.find(({ rule }) => rule.key === 'shopProductLinks')?.rule;+ const shopWant = shopRule?.on ? ruleNumber(shopRule) : 0;+ const { check: shopping, refreshing: shoppingRefreshing } = shoppingCheck;+ const shoppingRead = useMemo((): ShoppingLinks | 'reading' | 'failed' | null => {+ if (!publishOpen || shopping === null || shopping === 'reading') return null;+ if (shoppingRefreshing) return 'reading';+ if (shopping === 'failed') return 'failed';+ return shoppingLinks(readPage(publishOpen.html, 0).links ?? [], shopping, shopWant);+ }, [publishOpen, shopping, shoppingRefreshing, shopWant]);// Read once per change (a link read landing, the title), not on every render.const readyToPaste = useMemo((): ReadyToPaste | null => {if (!publishOpen) return null;@@ -4208,6 +4233,7 @@ export function DraftEditor({onRemoveClaim={sourcesOn ? removeClaim : undefined}onConfirmImages={() => setConfirmingImages(true)}onAddImage={addImage}+ onShoppingPathChange={shoppingCheck.reload}/>) : (<EditorPanelRail onOpen={openPanelTab} />@@ -4335,6 +4361,7 @@ export function DraftEditor({onAddDisclosure={addLineUnderAnswer}product={productSchema}category={categorySchema}+ shopping={shoppingRead}onMarkReady={(anyway) => {setPublishOpen(null);void markReady(anyway ?? undefined);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsxindex 4944075f4..2d89b21ab 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsx@@ -503,6 +503,43 @@ describe('the Rules tab', () => {expect(row('Length').textContent).not.toContain('Raise Length');});+ it('names the linked products that no longer sell under their Shopping rule, the first three', async () => {+ const titles = ['a', 'b', 'c', 'd'];+ const shopping = {+ categories: [],+ site: null,+ products: titles.map((t, i) => ({+ key: `shop.example/products/${t}`,+ title: t.toUpperCase(),+ state: i === 1 ? ('refused' as const) : ('sold_out' as const),+ inPath: true,+ })),+ };+ const page = readPage(+ titles.map((t) => `<p><a href="https://shop.example/products/${t}">x</a></p>`).join(''),+ 100,+ );+ const checked = activeRules(ruleSet('buying_guide', { shopping: true }), {+ overrides: {},+ }).map((rule) => ({+ rule,+ status: checkRule(rule, page, {+ brandDomains: [],+ competitorDomains: [],+ fanouts: [],+ shopping,+ }),+ }));+ await render(state(undefined, { rules: checked, ...rulesMet(checked) }));+ const live = [...container.querySelectorAll('li')].find((li) =>+ li.textContent?.startsWith('No sold-out or refused product linked'),+ )!;+ expect(live.textContent).toContain('4 found');+ expect(live.textContent).toContain(+ 'A (sold out), B (Merchant Center refuses it), C (sold out) +1 more: remove or replace these links on the page.',+ );+ });+it('shows Ansvisor’s set when a draft on My rules has none for its type', async () => {await render(state(undefined, { source: 'mine', mineTypes: [] }));const trigger = container.querySelector('[aria-label="Rule set"]')!;diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsxindex faf8b91e0..b8412aa20 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx@@ -46,6 +46,7 @@ import {type RuleStatus,type TextRule,} from '@/lib/content/rules';+import { listed } from '@/lib/content/shopping-check';import { formatNumber } from '@/lib/format';import { cn } from '@/lib/utils';import { useUserRole } from '@/hooks/use-user-role';@@ -462,7 +463,9 @@ export function RulesTab({? t('lengthConflict', state.lengthConflict): rule.key === 'sentence' && held.has('sentence') && status.state === 'bad'? t('heldSentence')- : undefined+ : rule.key === 'shopLinksLive'+ ? shoppingNote(t, status)+ : undefined}/>))}@@ -559,6 +562,22 @@ function TextRuleRow({);}+/**+ * The linked products that no longer sell, by name and why, the first few+ * (No sold-out or refused product linked, shopping path); none while it's met.+ */+function shoppingNote(+ t: (key: string, values?: Record<string, string | number>) => string,+ status: RuleStatus,+): string | undefined {+ if (status.state !== 'bad' || status.code !== 'found' || !status.items?.length) return undefined;+ const { shown, more } = listed(status.items);+ return t('shopLinksLiveNote', {+ list: shown.map((item) => t('shopItem', { title: item.title, state: item.state })).join(', '),+ more,+ });+}+/** Write a rule, or paste many: each line becomes a rule (bullets and numbering taken off). */function AddTextRules({ onAdd }: { onAdd: (lines: string[]) => void }) {const t = useTranslations('contentEditor.editor.rules.text');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.tsxindex 323f795a0..dfc1f1cae 100644--- 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@@ -75,11 +75,16 @@ let root: Root;let stored: ShoppingPath;let saves: number;-async function render() {+async function render(onPathChange?: () => void) {await act(async () => {root.render(<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">- <ShoppingPathSection draftId="d1" brandId="b1" pageType="buying_guide" />+ <ShoppingPathSection+ draftId="d1"+ brandId="b1"+ pageType="buying_guide"+ onPathChange={onPathChange}+ /></NextIntlClientProvider>,);});@@ -201,6 +206,31 @@ describe('ShoppingPathSection', () => {expect(buildDraftShoppingPath).toHaveBeenCalledWith('d1', 'b1');});+ it('tells the editor of each change saved or picked, and one made meanwhile; not of one that failed', async () => {+ const onPathChange = vi.fn();+ await render(onPathChange);+ expect(onPathChange).not.toHaveBeenCalled();+ await act(async () => button('Remove Ridge Light Hiker from the page')!.click());+ expect(onPathChange).toHaveBeenCalledTimes(1);+ await act(async () => button('Pick again')!.click());+ expect(onPathChange).toHaveBeenCalledTimes(2);++ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ saveDraftShoppingPath.mockRejectedValueOnce(new Error('denied'));+ await act(async () => button('Lock Summit GTX Boot')!.click());+ buildDraftShoppingPath.mockResolvedValueOnce({ error: 'failed' });+ await act(async () => button('Pick again')!.click());+ expect(onPathChange).toHaveBeenCalledTimes(2);+ } finally {+ error.mockRestore();+ }++ saveDraftShoppingPath.mockResolvedValueOnce({ error: 'changed' });+ await act(async () => button('Lock Summit GTX Boot')!.click());+ expect(onPathChange).toHaveBeenCalledTimes(3);+ });+it('puts a change back when it can’t be saved', async () => {const error = vi.spyOn(console, 'error').mockImplementation(() => {});try {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.tsxindex f0bd24624..53f5892d2 100644--- 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@@ -71,16 +71,19 @@ const PICK_AGAIN: readonly (NoPathReason | null)[] = [null, 'no_match', 'other']* 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.+ * on an e-commerce brand. `onPathChange` follows each change saved or+ * built, and one found made meanwhile: the Shopping rules read it again.*/export function ShoppingPathSection({draftId,brandId,pageType,+ onPathChange,}: {draftId: string;brandId: string;pageType: string | null;+ onPathChange?: () => void;}) {const t = useTranslations('contentEditor.editor.shopping');const [state, setState] = useState<PathState>({ status: 'loading' });@@ -143,6 +146,8 @@ export function ShoppingPathSection({{ builtAt: from.builtAt, savedAt: from.savedAt ?? null },choicesOf(next),);+ // Saved, or changed meanwhile: the path kept isn't the one read either way.+ onPathChange?.();if ('error' in saved) {// A build or another change since it was read: shown as it is now, not overwritten.toast.error(t('changed'));@@ -168,9 +173,11 @@ export function ShoppingPathSection({const result = await buildDraftShoppingPath(draftId, brandId);if (!('error' in result)) {setState({ status: 'ready', path: result.path, none: result.path ? null : result.reason });+ onPathChange?.();} else if (result.error === 'changed') {toast.error(t('changed'));void load();+ onPathChange?.();} else {toast.error(t(result.error === 'rate_limited' ? 'rateLimited' : 'buildFailed'));}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.tsxindex 7317e2681..2a46982ec 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@@ -150,6 +150,7 @@ export function EditorSidePanel({onConfirmIntro,onChangeType,handOff = null,+ onShoppingPathChange,}: {draft: ContentDraft;/**@@ -235,6 +236,8 @@ export function EditorSidePanel({onChangeType?: () => void;/** Hand it off to Content Agent, Quality's (CE-051). */handOff?: HandOff | null;+ /** Brief › Shopping path changed: the Shopping rules read it again (shopping path, part 6). */+ onShoppingPathChange?: () => void;}) {const t = useTranslations('contentEditor.editor.panel');const tEditor = useTranslations('contentEditor.editor');@@ -466,6 +469,7 @@ export function EditorSidePanel({draftId={draft.id}brandId={draft.brandId}pageType={pageType}+ onPathChange={onShoppingPathChange}/>)}<BriefTabdiff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.tsindex f65194eeb..d2699a4e2 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.ts+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.ts@@ -7,6 +7,7 @@ import { getMyRuleSets, saveDraftRules, saveMyRuleSet } from '@/lib/actions/contimport { isPageType, type ContentDraft, type PageType } from '@/lib/content/drafts';import type { CatalogMatch } from '@/lib/content/feed-match';import type { SiteType } from '@/lib/content/page-types';+import type { ShoppingCheck } from '@/lib/content/shopping-check';import {MAX_TEXT_RULES,activeRules,@@ -102,6 +103,7 @@ export function useDraftRules({pageType,reads,catalog = null,+ shopping = null,}: {draft: ContentDraft;/** The brand's business type as the editor holds it: My rules are kept per type (00227). */@@ -112,6 +114,13 @@ export function useDraftRules({reads: Pick<DraftReads, 'brief' | 'sources'>;/** The page's product in the brand's catalog (CE-053), for the feed rule (RuleContext's). */catalog?: CatalogMatch | 'reading' | null;+ /**+ * The draft's shopping path against the catalog (useShoppingCheck), for the+ * Shopping rules (shopping path, part 6): shown once it's read and has one,+ * or couldn't be read; not while it's first read, so a draft without a+ * path never shows them.+ */+ shopping?: ShoppingCheck | 'reading' | 'failed' | null;}): DraftRulesState {const t = useTranslations('contentEditor.editor.rules');const tTypes = useTranslations('contentEditor.pageTypes');@@ -146,7 +155,7 @@ export function useDraftRules({const sources = reads.sources;const ctx = useMemo<RuleContext>(() => {if (!sources || sources.failed) {- return { brandDomains: [], competitorDomains: [], fanouts: [], language, catalog };+ return { brandDomains: [], competitorDomains: [], fanouts: [], language, catalog, shopping };}const fanouts = buildSourceGroups(sources.data, sources.choices, {title: draft.title,@@ -161,8 +170,9 @@ export function useDraftRules({fanouts: fanouts ?? [],language,catalog,+ shopping,};- }, [sources, draft.title, draft.sourceUrl, language, catalog]);+ }, [sources, draft.title, draft.sourceUrl, language, catalog, shopping]);const brief = reads.brief;const keywords = useMemo(() => (brief.status === 'ready' ? (brief.brief?.keywords ?? []) : []),@@ -178,10 +188,15 @@ export function useDraftRules({const rules = useMemo(() =>activeRules(- ruleSet(setType, { keywords, language, length: effective.importLength }),+ ruleSet(setType, {+ keywords,+ language,+ length: effective.importLength,+ shopping: shopping !== null && shopping !== 'reading',+ }),effective,),- [setType, keywords, language, effective],+ [setType, keywords, language, effective, shopping],);// The checks follow the page a beat behind typing.const deferredHtml = useDeferredValue(html);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-shopping-check.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-shopping-check.test.tsxnew file mode 100644index 000000000..d46ea30d7--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-shopping-check.test.tsx@@ -0,0 +1,169 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { ShoppingCheck } from '@/lib/content/shopping-check';++const getShoppingCheck = vi.fn();+vi.mock('@/lib/actions/shopping-path', () => ({+ getShoppingCheck: (...args: unknown[]) => getShoppingCheck(...args),+}));++const { useShoppingCheck } = await import('./_use-shopping-check');++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++/**+ * The draft's shopping path against the catalog (shopping path, part 6):+ * read on a page that takes one, again on reload, the last read kept+ * meanwhile.+ */++const check = (title: string): ShoppingCheck => ({+ categories: [],+ products: [{ key: `shop.example/products/${title}`, title, state: 'ok', inPath: true }],+ site: null,+});++let container: HTMLDivElement;+let root: Root;++function Probe(props: {+ draftId?: string;+ pageType?: string | null;+ siteType?: 'ecommerce' | 'b2b';+}) {+ const state = useShoppingCheck({+ draftId: props.draftId ?? 'd1',+ siteType: props.siteType ?? 'ecommerce',+ pageType: props.pageType === undefined ? 'buying_guide' : props.pageType,+ });+ return (+ <button+ type="button"+ data-check={JSON.stringify(state.check)}+ data-refreshing={String(state.refreshing)}+ onClick={state.reload}+ />+ );+}+const render = (props: Parameters<typeof Probe>[0] = {}) =>+ act(async () => root.render(<Probe {...props} />));+const probe = () => container.querySelector('button')!;+/** The hook's answer as the probe shows it; `reload` is its button. */+const read = {+ get check(): unknown {+ return JSON.parse(probe().dataset.check!);+ },+ get refreshing() {+ return probe().dataset.refreshing === 'true';+ },+ reload: () => probe().click(),+};++/** A read that lands when `resolve` is called. */+function pending() {+ let resolve!: (value: ShoppingCheck | null) => void;+ let reject!: (err: Error) => void;+ getShoppingCheck.mockImplementationOnce(+ () =>+ new Promise<ShoppingCheck | null>((res, rej) => {+ resolve = res;+ reject = rej;+ }),+ );+ return {+ resolve: (value: ShoppingCheck | null) => act(async () => resolve(value)),+ reject: (err: Error) => act(async () => reject(err)),+ };+}++beforeEach(() => {+ getShoppingCheck.mockReset().mockResolvedValue(null);+ container = document.createElement('div');+ root = createRoot(container);+});+afterEach(() => act(() => root.unmount()));++describe('useShoppingCheck', () => {+ it("reads the draft's check, by the draft alone, 'reading' until it lands", async () => {+ const first = pending();+ await render();+ expect(read.check).toBe('reading');+ expect(read.refreshing).toBe(false);+ await first.resolve(check('Summit'));+ expect(read.check).toEqual(check('Summit'));+ expect(getShoppingCheck).toHaveBeenCalledWith('d1');+ });++ it('keeps the last read while it reads again, then shows the new one', async () => {+ getShoppingCheck.mockResolvedValueOnce(check('Summit'));+ await render();+ const again = pending();+ await act(async () => read.reload());+ expect(read.check).toEqual(check('Summit'));+ expect(read.refreshing).toBe(true);+ await again.resolve(check('Ridge'));+ expect(read.check).toEqual(check('Ridge'));+ expect(read.refreshing).toBe(false);++ // None kept as none: a draft without a path never shows 'reading' again.+ getShoppingCheck.mockResolvedValueOnce(null);+ await act(async () => read.reload());+ expect(read.check).toBeNull();+ const next = pending();+ await act(async () => read.reload());+ expect(read.check).toBeNull();+ expect(read.refreshing).toBe(true);+ await next.resolve(null);+ expect(read.refreshing).toBe(false);+ });++ it("says 'failed' when it can't be read, and reads again on reload", async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ const first = pending();+ await render();+ await first.reject(new Error('catalog down'));+ expect(read.check).toBe('failed');+ getShoppingCheck.mockResolvedValueOnce(check('Summit'));+ await act(async () => read.reload());+ expect(read.check).toEqual(check('Summit'));+ } finally {+ error.mockRestore();+ }+ });++ it("drops a read for another draft, and starts the new draft's from 'reading'", async () => {+ const old = pending();+ await render({ draftId: 'd1' });+ const now = pending();+ await render({ draftId: 'd2' });+ await old.resolve(check('Old'));+ expect(read.check).toBe('reading');+ await now.resolve(check('New'));+ expect(read.check).toEqual(check('New'));+ expect(getShoppingCheck.mock.calls).toEqual([['d1'], ['d2']]);+ });++ it('drops an earlier read that lands after a later one', async () => {+ const first = pending();+ await render();+ const second = pending();+ await act(async () => read.reload());+ await second.resolve(check('New'));+ await first.resolve(check('Old'));+ expect(read.check).toEqual(check('New'));+ expect(read.refreshing).toBe(false);+ });++ it('reads nothing on a page that takes no shopping path', async () => {+ await render({ siteType: 'b2b' });+ expect(read.check).toBeNull();+ await render({ pageType: 'product_page' });+ expect(read.check).toBeNull();+ await render({ pageType: null });+ expect(read.check).toBeNull();+ expect(getShoppingCheck).not.toHaveBeenCalled();+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-shopping-check.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-shopping-check.tsnew file mode 100644index 000000000..6efb4a259--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-shopping-check.ts@@ -0,0 +1,69 @@+'use client';++import { useCallback, useEffect, useState } from 'react';+import { getShoppingCheck } from '@/lib/actions/shopping-path';+import type { SiteType } from '@/lib/content/page-types';+import type { ShoppingCheck } from '@/lib/content/shopping-check';+import { shoppingPathFits } from '@/lib/content/shopping-path';++export interface ShoppingCheckRead {+ /**+ * The draft's shopping path against the catalog: 'reading' until it's+ * first read, 'failed' when it couldn't be, null without a path or on a+ * page that takes none.+ */+ check: ShoppingCheck | 'reading' | 'failed' | null;+ /** Read again (`reload`) and not back yet: `check` is the last read until then. */+ refreshing: boolean;+ /** Reads it again: Before you publish asks for it fresh, Brief › Shopping path after a change. */+ reload: () => void;+}++/**+ * The draft's shopping path read against the catalog now (shopping path,+ * part 6), for the Shopping rules and Before you publish. A read again+ * keeps the last one meanwhile, so the rules don't come and go with it.+ */+export function useShoppingCheck({+ draftId,+ siteType,+ pageType,+}: {+ draftId: string;+ siteType: SiteType;+ pageType: string | null;+}): ShoppingCheckRead {+ const fits = shoppingPathFits(siteType, pageType);+ // The draft read, and each read of it: a new draft starts from 'reading'.+ const draftKey = `${draftId}|${fits}`;+ const [reads, setReads] = useState(0);+ const key = `${draftKey}|${reads}`;+ const [state, setState] = useState<{+ draftKey: string;+ key: string;+ check: ShoppingCheck | 'failed' | null;+ } | null>(null);++ useEffect(() => {+ if (!fits) return;+ let cancelled = false;+ getShoppingCheck(draftId).then(+ (check) => {+ if (!cancelled) setState({ draftKey, key, check });+ },+ (err) => {+ console.error('Failed to read the shopping links:', err);+ if (!cancelled) setState({ draftKey, key, check: 'failed' });+ },+ );+ return () => {+ cancelled = true;+ };+ }, [draftId, fits, draftKey, key]);++ const reload = useCallback(() => setReads((n) => n + 1), []);+ if (!fits) return { check: null, refreshing: false, reload };+ const last = state?.draftKey === draftKey ? state : null;+ if (!last) return { check: 'reading', refreshing: false, reload };+ return { check: last.check, refreshing: last.key !== key, reload };+}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.tsxindex 5e33ab5af..70e0afe0c 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@@ -166,11 +166,14 @@ 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.+const getShoppingCheck = vi.hoisted(() => vi.fn(async (): Promise<unknown> => null));vi.mock('@/lib/actions/shopping-path', () => ({getDraftShoppingPath: vi.fn(async () => ({ path: null })),buildDraftShoppingPath: vi.fn(),saveDraftShoppingPath: vi.fn(),searchCatalogProducts: vi.fn(async () => []),+ getProductsForBlock: vi.fn(async () => []),+ getShoppingCheck,}));vi.mock('@/stores/use-brand-store', () => ({useBrandStore: (selector: (state: typeof brandState) => unknown) => selector(brandState),@@ -2895,6 +2898,40 @@ describe('the side panel', () => {expect(panel()!.querySelector('section[aria-label="Shopping path"]') !== null).toBe(shown);});+ it('shows the Shopping rules once the path is read, and reads it again after a change in Brief', async () => {+ let land!: (value: unknown) => void;+ getShoppingCheck.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ land = resolve;+ }),+ );+ try {+ getContentDraft.mockResolvedValue(draft({ siteType: 'ecommerce', pageType: 'buying_guide' }));+ window.innerWidth = 1440;+ await renderPage();+ await pickTab('Rules');+ // While it's first read: no Shopping rules, and no count that would change.+ expect(panel()!.textContent).not.toContain('Links its category page');+ expect(panel()!.textContent).toContain('Reading the rules…');+ await act(async () =>+ land({ categories: ['shop.example/collections/boots'], products: [], site: null }),+ );+ expect(panel()!.textContent).toContain('Links its category page');+ expect(panel()!.textContent).toMatch(/\d+ of \d+ rules met/);++ // Brief › Shopping path picks again: the rules read the path again.+ const { buildDraftShoppingPath } = await import('@/lib/actions/shopping-path');+ vi.mocked(buildDraftShoppingPath).mockResolvedValueOnce({ path: null, reason: 'no_match' });+ await pickTab('Brief');+ const reads = getShoppingCheck.mock.calls.length;+ await act(async () => button('Pick from the catalog')!.click());+ expect(getShoppingCheck.mock.calls.length).toBe(reads + 1);+ } finally {+ getShoppingCheck.mockReset().mockResolvedValue(null);+ }+ });+it('points a page without fan-outs to Sources, where its prompts are added', async () => {getDraftSources.mockResolvedValue({data: {@@ -5727,6 +5764,78 @@ describe('the side panel', () => {expect(scrolled).toHaveBeenCalled();});+ it("names the shopping links to remove from the page as published, a product grid's too (shopping path)", async () => {+ const { htmlBlockElement } = await import('@/lib/content/html-allowlist');+ const { productBlockHtml } = await import('@/lib/content/product-block');+ const product = (n: number, title: string, state: string) => ({+ key: `shop.example/products/${n}`,+ title,+ state,+ inPath: true,+ });+ const check = (trail: string) => ({+ categories: ['shop.example/collections/boots'],+ products: [+ product(1, 'Summit', 'ok'),+ product(2, 'Trail', trail),+ product(3, 'Ridge', 'ok'),+ ],+ site: 'https://shop.example/blog/boots',+ });+ getShoppingCheck.mockResolvedValue(check('ok'));+ try {+ getContentDraft.mockResolvedValue(+ draft({+ siteType: 'ecommerce',+ pageType: 'buying_guide',+ bodyHtml:+ '<h1>Hiking boots</h1>' ++ '<h2>Our <a href="/collections/boots">boots</a></h2>' ++ htmlBlockElement(+ productBlockHtml([+ {+ title: 'Summit',+ url: 'https://shop.example/products/1',+ image: null,+ price: null,+ },+ {+ title: 'Trail',+ url: 'https://shop.example/products/2',+ image: null,+ price: null,+ },+ ]),+ ),+ }),+ );+ await renderPage();+ const reads = getShoppingCheck.mock.calls.length;+ // Read fresh when it opens: Trail sold out since.+ let land!: (value: unknown) => void;+ getShoppingCheck.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ land = resolve;+ }),+ );+ await act(async () => button('Mark ready')!.click());+ expect(getShoppingCheck.mock.calls.length).toBe(reads + 1);+ expect(getShoppingCheck).toHaveBeenLastCalledWith('d1');+ expect(dialogText()).toContain("Reading your catalog for the linked products' stock…");+ expect(dialogText()).not.toContain('Trail');+ await act(async () => land(check('sold_out')));+ expect(dialogText()).not.toContain('Reading your catalog');+ expect(dialogText()).toContain('1 product link to remove or replace');+ expect(dialogText()).toContain(+ 'Trail (sold out). Remove or replace these links on the page',+ );+ expect(dialogText()).not.toContain('No link to the category page');+ } finally {+ getShoppingCheck.mockReset().mockResolvedValue(null);+ }+ });+it('marks it ready at once while Quality is off', async () => {delete process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE;getContentDraft.mockResolvedValue(draft());diff --git a/web/src/lib/actions/shopping-path.test.ts b/web/src/lib/actions/shopping-path.test.tsindex 99e7f0e68..42c5e8c5b 100644--- a/web/src/lib/actions/shopping-path.test.ts+++ b/web/src/lib/actions/shopping-path.test.ts@@ -12,6 +12,7 @@ interface Call {filters: [string, string, unknown][];orders: [string, unknown][];limit?: number;+ range?: [number, number];}type Answer = { data: unknown; error: { message: string } | null };let calls: Call[];@@ -40,6 +41,7 @@ vi.mock('@/lib/supabase/server', () => ({in: filter('in'),order: (col: string, opts: unknown) => (call.orders.push([col, opts]), chain),limit: (n: number) => ((call.limit = n), chain),+ range: (from: number, to: number) => ((call.range = [from, to]), chain),update: (value: unknown) => ((call.op = 'update'), (call.value = value), chain),maybeSingle: async () => result(),then: (resolve: (r: unknown) => void) => resolve(result()),@@ -53,6 +55,7 @@ const {buildDraftShoppingPath,getDraftShoppingPath,getProductsForBlock,+ getShoppingCheck,saveDraftShoppingPath,searchCatalogProducts,searchProductsForBlock,@@ -450,3 +453,299 @@ describe('searchProductsForBlock', () => {await expect(searchProductsForBlock(BRAND, 'boots')).rejects.toThrow('boom');});});++describe('getShoppingCheck', () => {+ const SHOP = '44444444-4444-4444-8444-444444444444';+ const P = (n: number) => `bbbbbbbb-0000-4000-8000-${String(n).padStart(12, '0')}`;+ const inPath = (n: number, url = `https://shop.example/products/${n}`) => ({+ ...product(P(n)),+ title: `Boot ${n}`,+ url,+ });+ const pathOf = (over: Record<string, unknown> = {}) => ({+ ...STORED,+ categories: [+ { name: 'Boots', url: 'https://shop.example/collections/boots', title: null },+ // A link the path can't keep: nothing to check.+ { name: 'Odd', url: 'javascript:alert(1)', title: null },+ ],+ products: [],+ leftOut: [],+ locked: [],+ removed: [],+ added: [],+ ...over,+ });+ const row = (n: number, extra: Record<string, unknown> = {}) => ({+ id: P(n),+ brand_id: SHOP,+ title: `Catalog ${n}`,+ url: `https://shop.example/products/${n}`,+ removed_at: null,+ ...extra,+ });+ let variants = 0;+ const variant = (n: number, availability: string, extra: Record<string, unknown> = {}) => {+ variants += 1;+ return {+ id: `v${String(variants).padStart(6, '0')}`,+ brand_id: SHOP,+ product_id: P(n),+ external_id: `ext-${variants}`,+ url: null,+ availability,+ removed_at: null,+ ...extra,+ };+ };+ const issue = (v: { external_id: string }, context: string | null, severity = 'disapproved') => ({+ id: `i-${v.external_id}-${context}-${severity}`,+ brand_id: SHOP,+ external_id: v.external_id,+ severity,+ reporting_context: context,+ });++ /** The tables, read as PostgREST would: by their filters, a page at a time. */+ let db: Record<string, Record<string, unknown>[]>;+ let down: Record<string, string>;+ const draftRow = () => db.content_drafts[0];+ const of = (table: string) => calls.filter((c) => c.table === table);+ const inList = (call: Call) => call.filters.find(([kind]) => kind === 'in')?.[2] as string[];++ beforeEach(() => {+ variants = 0;+ down = {};+ db = {+ content_drafts: [+ {+ id: DRAFT,+ brand_id: SHOP,+ shopping_path: pathOf(),+ published_url: null,+ source_url: null,+ },+ ],+ brand_domains: [+ { brand_id: SHOP, domain: 'shop.example', is_primary: false },+ { brand_id: SHOP, domain: 'https://www.shop.example/', is_primary: true },+ ],+ catalog_products: [],+ catalog_variants: [],+ catalog_item_issues: [],+ };+ answer = (call) => {+ if (down[call.table]) return { data: null, error: { message: down[call.table] } };+ let rows = (db[call.table] ?? []).filter((r) =>+ call.filters.every(([kind, col, v]) =>+ kind === 'eq'+ ? r[col] === v+ : kind === 'in'+ ? (v as unknown[]).includes(r[col])+ : kind === 'is'+ ? r[col] == null+ : true,+ ),+ );+ if (call.range) rows = rows.slice(call.range[0], call.range[1] + 1);+ const single = call.table === 'content_drafts' || call.table === 'brand_domains';+ return { data: single ? (rows[0] ?? null) : rows, error: null };+ };+ });++ it('reads each product now: gone, sold out, refused only when every variant in stock is', async () => {+ const v1 = variant(1, 'In Stock');+ const v3a = variant(3, 'in_stock');+ const v3b = variant(3, 'LIMITED AVAILABILITY');+ const v3c = variant(3, 'sold out');+ const v4a = variant(4, 'in_stock');+ const v4b = variant(4, 'in_stock');+ db.catalog_variants = [+ v1,+ variant(2, 'out_of_stock'),+ variant(2, 'preorder'),+ v3a,+ v3b,+ v3c,+ v4a,+ v4b,+ variant(7, 'in_stock'),+ ];+ db.catalog_item_issues = [+ // An ads refusal, and a warning for free listings: neither keeps it out.+ issue(v1, 'SHOPPING_ADS'),+ issue(v1, 'FREE_LISTINGS', 'warning'),+ // The free listings however written, or no destination: refused.+ issue(v3a, ' free_listings '),+ issue(v3b, null),+ // One variant refused, another in stock that isn't: it still sells.+ issue(v4a, 'FREE_LISTINGS'),+ ];+ db.catalog_products = [+ row(1),+ row(2),+ row(3),+ row(4),+ row(5, { removed_at: '2026-10-20' }),+ row(7),+ ];+ // 6 isn't in the catalog; 7's link the path couldn't keep.+ draftRow().shopping_path = pathOf({+ products: [1, 2, 3, 4, 5, 6].map((n) => inPath(n)).concat(inPath(7, '')),+ });++ expect(await getShoppingCheck(DRAFT)).toEqual({+ categories: ['shop.example/collections/boots'],+ products: (+ [+ [1, 'ok'],+ [2, 'sold_out'],+ [3, 'refused'],+ [4, 'ok'],+ [5, 'gone'],+ [6, 'gone'],+ ] as const+ ).map(([n, state]) => ({+ key: `shop.example/products/${n}`,+ title: `Boot ${n}`,+ state,+ inPath: true,+ })),+ site: 'https://www.shop.example/',+ });+ // The refusals of the variants in stock alone.+ expect(of('catalog_item_issues').flatMap(inList).sort()).toEqual(+ [v1, v3a, v3b, v4a, v4b, db.catalog_variants[8]].map((v) => v.external_id).sort(),+ );+ });++ it('checks the removed and left-out products that no longer sell, at the catalog’s page', async () => {+ db.catalog_products = [+ row(10),+ row(11),+ row(12, { removed_at: '2026-10-21' }),+ row(13, { url: null }),+ ];+ const v13 = variant(13, 'in_stock', { url: 'https://shop.example/products/13?variant=1' });+ db.catalog_variants = [variant(10, 'out_of_stock'), variant(11, 'in_stock'), v13];+ db.catalog_item_issues = [issue(v13, 'FREE_LISTINGS')];+ draftRow().shopping_path = pathOf({+ products: [inPath(1)],+ removed: [P(10), P(11), P(12), P(1)],+ leftOut: [+ { id: P(13), title: 'Left Boot', reason: 'refused' },+ { id: P(10), title: null, reason: 'sold_out' },+ ],+ });+ db.catalog_products.push(row(1));+ db.catalog_variants.push(variant(1, 'in_stock'));++ const check = await getShoppingCheck(DRAFT);+ expect(check!.products).toEqual([+ { key: 'shop.example/products/1', title: 'Boot 1', state: 'ok', inPath: true },+ // 11 still sells: linking it is fine.+ { key: 'shop.example/products/10', title: 'Catalog 10', state: 'sold_out', inPath: false },+ { key: 'shop.example/products/12', title: 'Catalog 12', state: 'gone', inPath: false },+ {+ key: 'shop.example/products/13?variant=1',+ title: 'Left Boot',+ state: 'refused',+ inPath: false,+ },+ ]);+ });++ it('reads the draft’s brand, 100 ids a request and every page of variants past 1,000', async () => {+ // 1,100 variants of the first, its 50 in stock on the second page.+ db.catalog_variants = Array.from({ length: 1100 }, (_, i) =>+ variant(1, i < 1050 ? 'out_of_stock' : 'in_stock'),+ );+ // 250 in stock, each refused: refused only once every refusal is read.+ const refusedOnes = Array.from({ length: 250 }, () => variant(2, 'in_stock'));+ db.catalog_variants.push(...refusedOnes);+ db.catalog_item_issues = refusedOnes.map((v) => issue(v, 'FREE_LISTINGS'));+ // 3 is another brand's: not this draft's catalog.+ db.catalog_products = [row(1), row(2), row(3, { brand_id: BRAND })];+ draftRow().shopping_path = pathOf({+ products: [inPath(1), inPath(2), inPath(3)],+ removed: Array.from({ length: 150 }, (_, i) => P(100 + i)),+ });++ const check = await getShoppingCheck(DRAFT);+ expect(check!.products.map((p) => p.state)).toEqual(['ok', 'refused', 'gone']);+ const catalog = ['catalog_products', 'catalog_variants', 'catalog_item_issues'].flatMap(of);+ for (const call of catalog) {+ expect(call.filters).toContainEqual(['eq', 'brand_id', SHOP]);+ expect(inList(call).length).toBeLessThanOrEqual(100);+ expect(call.limit).toBeUndefined();+ }+ expect(of('catalog_products').map((c) => inList(c).length)).toEqual([100, 53]);+ expect(of('catalog_variants').map((c) => c.range)).toContainEqual([1000, 1999]);+ expect(of('catalog_item_issues').map((c) => inList(c).length)).toEqual([100, 100, 100]);+ });++ it('reads a relative link against the live page, the page it optimizes, else the brand’s site', async () => {+ draftRow().published_url = 'https://shop.example/blog/boots';+ draftRow().source_url = 'https://shop.example/old';+ expect((await getShoppingCheck(DRAFT))!.site).toBe('https://shop.example/blog/boots');+ draftRow().published_url = null;+ expect((await getShoppingCheck(DRAFT))!.site).toBe('https://shop.example/old');+ expect(of('brand_domains')).toHaveLength(0);+ draftRow().source_url = null;+ expect((await getShoppingCheck(DRAFT))!.site).toBe('https://www.shop.example/');++ // The brand's site unread: no site, the rest of the check stands.+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ down = { brand_domains: 'down' };+ expect(await getShoppingCheck(DRAFT)).toMatchObject({+ categories: ['shop.example/collections/boots'],+ site: null,+ });+ } finally {+ error.mockRestore();+ }+ });++ it('is null without a path, reads no catalog for an empty one, and fails on a failed read', async () => {+ draftRow().shopping_path = null;+ expect(await getShoppingCheck(DRAFT)).toBeNull();+ draftRow().shopping_path = pathOf();+ expect(await getShoppingCheck(DRAFT)).toMatchObject({ products: [] });+ expect(calls.some((c) => c.table.startsWith('catalog_'))).toBe(false);++ await expect(getShoppingCheck('nope')).rejects.toThrow('invalid');+ db.content_drafts = [];+ await expect(getShoppingCheck(DRAFT)).rejects.toThrow('not_found');+ for (const table of [+ 'content_drafts',+ 'catalog_products',+ 'catalog_variants',+ 'catalog_item_issues',+ ]) {+ db.content_drafts = [+ {+ id: DRAFT,+ brand_id: SHOP,+ shopping_path: pathOf({ products: [inPath(1)] }),+ published_url: null,+ source_url: null,+ },+ ];+ db.catalog_products = [row(1)];+ db.catalog_variants = [variant(1, 'in_stock')];+ down = { [table]: `${table} down` };+ await expect(getShoppingCheck(DRAFT)).rejects.toThrow(`${table} down`);+ }+ });++ it('is null for a kept path it can’t read', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ draftRow().shopping_path = { ...pathOf(), version: 2 };+ expect(await getShoppingCheck(DRAFT)).toBeNull();+ } finally {+ error.mockRestore();+ }+ });+});diff --git a/web/src/lib/actions/shopping-path.ts b/web/src/lib/actions/shopping-path.tsindex 8f464cce4..fe56799c7 100644--- a/web/src/lib/actions/shopping-path.ts+++ b/web/src/lib/actions/shopping-path.ts@@ -5,7 +5,14 @@ import { API_BASE_URL } from '@/config/api';import { createClient } from '@/lib/supabase/server';import { jsonbBytes } from '@/lib/content/draft-inputs';import { variantStock } from '@/lib/content/feed-match';+import { linkKey } from '@/lib/content/link-targets';import { MAX_BLOCK_PRODUCTS } from '@/lib/content/product-block';+import type {+ ShoppingCheck,+ ShoppingLinkState,+ ShoppingProductCheck,+} from '@/lib/content/shopping-check';+import { readAllRpcRows } from '@/lib/supabase/rpc-pages';import {NO_PATH_REASONS,shoppingChoicesSchema,@@ -28,6 +35,17 @@ 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 });+/** A kept path as the tab reads it: none until built, `unreadable` when it isn't one it reads. */+function readPath(kept: Json | null): { path: ShoppingPath | null; unreadable?: true } {+ if (kept == null) return { path: null };+ const parsed = shoppingPathSchema.safeParse(kept);+ 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 };+}+/*** 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).@@ -45,13 +63,7 @@ export async function getDraftShoppingPath(.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 };+ return readPath(data.shopping_path);}/**@@ -306,6 +318,184 @@ export async function getProductsForBlock(});}+/**+ * Merchant Center refusals that keep a product out of AI shopping: its free+ * listings, which AI Overviews and AI Mode draw on, or an issue with no+ * destination. A refusal for Shopping ads alone doesn't. Read as the API's+ * `refuses` reads it (server/src/lib/shopping-path.js): trimmed, any case.+ */+const REFUSING_CONTEXTS = new Set(['FREE_LISTINGS', '']);++/** Ids one `in` filter takes: 100 UUIDs keep a request's address well under the edge's limit. */+const IN_CHUNK = 100;++/**+ * Every row a read by ids gives: IN_CHUNK ids a request, each read a page+ * at a time (PostgREST's 1,000-row cap; `page` orders its rows).+ */+async function readByIds<T>(+ ids: readonly string[],+ page: (+ chunk: string[],+ from: number,+ to: number,+ ) => PromiseLike<{ data: T[] | null; error: { message: string } | null }>,+): Promise<T[]> {+ const chunks: string[][] = [];+ for (let i = 0; i < ids.length; i += IN_CHUNK) chunks.push(ids.slice(i, i + IN_CHUNK));+ const rows = await Promise.all(+ chunks.map((chunk) => readAllRpcRows<T>((from, to) => page(chunk, from, to))),+ );+ return rows.flat();+}++/**+ * What a relative link on the page is read against: where it went live,+ * else the page it optimizes, else the brand's site. Null when none is+ * known, or the brand's site can't be read: a relative link then isn't+ * matched, and the rest of the check stands.+ */+async function pageSite(+ supabase: Client,+ draft: { brand_id: string; published_url: string | null; source_url: string | null },+): Promise<string | null> {+ for (const url of [draft.published_url, draft.source_url]) {+ if (url && linkKey(url)) return url.trim();+ }+ const { data, error } = await supabase+ .from('brand_domains')+ .select('domain')+ .eq('brand_id', draft.brand_id)+ .eq('is_primary', true)+ .limit(1)+ .maybeSingle();+ if (error) {+ console.error('Failed to read the brand’s site:', error.message);+ return null;+ }+ const host = String(data?.domain ?? '')+ .trim()+ .replace(/^https?:\/\//i, '')+ .replace(/\/.*$/, '');+ return host ? `https://${host}/` : null;+}++/**+ * The draft's shopping path read against the catalog now (shopping path,+ * part 6): each of its products sold out, refused by Merchant Center, gone,+ * or fine; the ones removed from it or left out that no longer sell, in+ * case the page still links them; and the category pages. Read for the+ * draft's own brand, whatever brand the tab has open. Null without a path;+ * throws when the draft or the catalog can't be read.+ */+export async function getShoppingCheck(draftId: string): Promise<ShoppingCheck | null> {+ if (!guid.safeParse(draftId).success) throw new Error('invalid');+ const supabase = await createClient();+ const { data: draft, error } = await supabase+ .from('content_drafts')+ .select('brand_id, shopping_path, published_url, source_url')+ .eq('id', draftId)+ .maybeSingle();+ if (error) throw new Error(error.message);+ if (!draft) throw new Error('not_found');+ const { path } = readPath(draft.shopping_path);+ if (!path) return null;+ const brandId = draft.brand_id;++ const inPath = new Set(path.products.map((p) => p.id));+ const others = [...new Set([...path.removed, ...path.leftOut.map((p) => p.id)])].filter(+ (id) => !inPath.has(id),+ );+ const ids = [...inPath, ...others].filter((id) => guid.safeParse(id).success);+ const [products, variants, site] = await Promise.all([+ readByIds(ids, (chunk, from, to) =>+ supabase+ .from('catalog_products')+ .select('id, title, url, removed_at')+ .eq('brand_id', brandId)+ .in('id', chunk)+ .order('id')+ .range(from, to),+ ),+ readByIds(ids, (chunk, from, to) =>+ supabase+ .from('catalog_variants')+ .select('id, product_id, external_id, url, availability')+ .eq('brand_id', brandId)+ .in('product_id', chunk)+ .is('removed_at', null)+ .order('id')+ .range(from, to),+ ),+ pageSite(supabase, draft),+ ]);+ // A refusal matters only for a variant in stock: the others are sold out anyway.+ const inStock = variants.filter((v) => variantStock(v.availability) === 'in');+ const issues = await readByIds(+ [...new Set(inStock.map((v) => v.external_id))],+ (chunk, from, to) =>+ supabase+ .from('catalog_item_issues')+ .select('id, external_id, reporting_context')+ .eq('brand_id', brandId)+ .eq('severity', 'disapproved')+ .in('external_id', chunk)+ .order('id')+ .range(from, to),+ );+ const refused = new Set(+ issues+ .filter((i) =>+ REFUSING_CONTEXTS.has(+ String(i.reporting_context ?? '')+ .trim()+ .toUpperCase(),+ ),+ )+ .map((i) => i.external_id),+ );++ const byId = new Map(products.map((p) => [p.id, p]));+ const selling = new Map<string, typeof inStock>();+ for (const v of inStock) {+ const list = selling.get(v.product_id);+ if (list) list.push(v);+ else selling.set(v.product_id, [v]);+ }+ const stateOf = (id: string): ShoppingLinkState => {+ const product = byId.get(id);+ if (!product || product.removed_at) return 'gone';+ const sells = selling.get(id) ?? [];+ if (!sells.length) return 'sold_out';+ return sells.every((v) => refused.has(v.external_id)) ? 'refused' : 'ok';+ };++ const pathProducts = path.products.flatMap((p): ShoppingProductCheck[] => {+ // A link the path couldn't keep (not http(s)) is null: nothing to check.+ const key = p.url ? linkKey(p.url) : null;+ return key ? [{ key, title: p.title, state: stateOf(p.id), inPath: true }] : [];+ });+ // Removed or left out: listed only when it no longer sells, at the+ // catalog's page for it (the path doesn't keep one).+ const leftOutTitles = new Map(path.leftOut.map((p) => [p.id, p.title]));+ const otherProducts = others.flatMap((id): ShoppingProductCheck[] => {+ const state = stateOf(id);+ const product = byId.get(id);+ if (state === 'ok' || !product) return [];+ const url = product.url ?? variants.find((v) => v.product_id === id && v.url)?.url ?? null;+ const key = url ? linkKey(url) : null;+ const title = leftOutTitles.get(id) ?? product.title;+ return key ? [{ key, title, state, inPath: false }] : [];+ });+ return {+ categories: path.categories+ .map((c) => (c.url ? linkKey(c.url) : null))+ .filter((k): k is string => !!k),+ products: [...pathProducts, ...otherProducts],+ site,+ };+}+/*** + Insert › Products' search: the brand's live catalog products whose* title holds `query` (searchCatalogProducts), each with its price anddiff --git a/web/src/lib/content/rules.test.ts b/web/src/lib/content/rules.test.tsindex b139cf666..c6502c9e3 100644--- a/web/src/lib/content/rules.test.ts+++ b/web/src/lib/content/rules.test.ts@@ -1,4 +1,6 @@import { describe, expect, it } from 'vitest';+import { htmlBlockElement } from './html-allowlist';+import type { ShoppingCheck, ShoppingLinkState } from './shopping-check';import {NO_DRAFT_RULES,NOT_FOR_AGENT,@@ -37,6 +39,7 @@ import {keptOutOfReach,lengthOutOfReach,rewriteAdvice,+ SHOPPING_RULE_KEYS,type RuleStatus,} from './rules';@@ -452,6 +455,166 @@ describe('links and sources', () => {});});+describe('shopping path rules (shopping path, part 6)', () => {+ const item = (n: number, title: string, state: ShoppingLinkState, inPath = true) => ({+ key: `shop.example/products/p${n}`,+ title,+ state,+ inPath,+ });+ const shopping: ShoppingCheck = {+ categories: ['shop.example/collections/hiking-boots'],+ products: [+ item(1, 'Summit', 'ok'),+ item(2, 'Trail', 'sold_out'),+ item(3, 'Ridge', 'ok'),+ item(4, 'Alpine', 'ok'),+ ],+ site: 'https://shop.example/blog/boots',+ };+ const shopRule = (key: string, value?: string) => {+ const found = activeRules(+ ruleSet('buying_guide', { shopping: true }),+ value === undefined ? NO_DRAFT_RULES : { overrides: { [key]: { value } } },+ ).find((r) => r.key === key);+ if (!found) throw new Error(`no rule ${key}`);+ return found;+ };+ const grid = (hrefs: string[]) =>+ htmlBlockElement(hrefs.map((h) => `<a class="ansvisor-product" href="${h}">x</a>`).join(''));+ const html =+ '<h1>Boots</h1><p>Our <a href="https://shop.example/collections/hiking-boots/">hiking boots</a>.</p>' ++ '<p>The <a href="https://www.shop.example/products/p1?utm_source=x">Summit</a>.</p>' ++ grid(['https://shop.example/products/p2', 'https://shop.example/products/p3']);+ const status = (+ key: string,+ read = page(html),+ with_: RuleContext['shopping'] = shopping,+ value?: string,+ ) => checkRule(shopRule(key, value), read, { ...ctx, shopping: with_ });++ it('come only on an online shop’s page that takes a shopping path', () => {+ const keys = (pageType: Parameters<typeof ruleSet>[0], on: boolean) =>+ ruleSet(pageType, { shopping: on })+ .map((r) => r.key)+ .filter((k) => SHOPPING_RULE_KEYS.has(k));+ expect(keys('buying_guide', true)).toEqual([+ 'shopCategoryLink',+ 'shopProductLinks',+ 'shopLinksLive',+ ]);+ expect(keys('buying_guide', false)).toEqual([]);+ expect(keys('product_page', true)).toEqual([]);+ expect(NOT_FOR_AGENT.has('shopLinksLive')).toBe(true);+ });++ it('read every link on the page: the text’s, a heading’s, a table’s and a product grid’s, each once', () => {+ const read = page(+ '<h2><a href="https://shop.example/products/p4">Alpine</a></h2>' ++ '<table><tr><td><a href="https://shop.example/products/p3">Ridge</a></td></tr></table>' ++ '<ul><li><a href="https://shop.example/products/p1">Summit</a></li></ul>' ++ grid(['https://shop.example/products/p1', 'https://shop.example/products/p2']),+ );+ expect(read.links).toEqual([+ 'https://shop.example/products/p4',+ 'https://shop.example/products/p3',+ 'https://shop.example/products/p1',+ 'https://shop.example/products/p2',+ ]);+ expect(status('shopProductLinks', read)).toEqual({ state: 'ok' });+ expect(status('shopCategoryLink')).toEqual({ state: 'ok' });+ });++ it('count only the products that sell towards the number, and name the ones that don’t', () => {+ // Summit and Ridge sell; Trail, in the grid, is sold out: 2 of 3.+ expect(status('shopProductLinks')).toEqual({ state: 'bad', code: 'partOf', count: 2, of: 3 });+ expect(status('shopLinksLive')).toEqual({+ state: 'bad',+ code: 'found',+ count: 1,+ items: [{ title: 'Trail', state: 'sold_out' }],+ });+ // A path of three, one sold out: both rules can be met, by the two that sell.+ const three = { ...shopping, products: shopping.products.slice(0, 3) };+ const two = page(+ '<p><a href="https://shop.example/products/p1">a</a> <a href="https://shop.example/products/p3">b</a></p>',+ );+ expect(status('shopProductLinks', two, three)).toEqual({ state: 'ok' });+ expect(status('shopLinksLive', two, three)).toEqual({ state: 'ok' });+ });++ it('find a link to a product removed from the path that no longer sells', () => {+ const removed = {+ ...shopping,+ products: [...shopping.products, item(9, 'Canyon', 'gone', false)],+ };+ const read = page('<p><a href="/products/p9">Canyon</a></p>');+ expect(status('shopLinksLive', read, removed)).toEqual({+ state: 'bad',+ code: 'found',+ count: 1,+ items: [{ title: 'Canyon', state: 'gone' }],+ });+ // Not one of the path's: it never counts towards the products linked.+ expect(status('shopProductLinks', read, removed, '1')).toEqual({+ state: 'bad',+ code: 'partOf',+ count: 0,+ of: 1,+ });+ });++ it('want the category page, three products or all of a smaller path, none sold out', () => {+ const bare = page('<p>Nothing linked.</p>');+ expect(status('shopCategoryLink', bare)).toEqual({ state: 'bad', code: 'missing' });+ expect(status('shopProductLinks', bare)).toEqual({+ state: 'bad',+ code: 'partOf',+ count: 0,+ of: 3,+ });+ expect(+ status('shopProductLinks', bare, { ...shopping, products: shopping.products.slice(0, 2) }),+ ).toEqual({ state: 'bad', code: 'partOf', count: 0, of: 1 });+ expect(status('shopLinksLive', bare)).toEqual({ state: 'ok' });+ });++ it('wait for the path, say when there is none, and when it can’t be read', () => {+ expect(status('shopProductLinks', page(html), 'reading')).toEqual({+ state: 'info',+ code: 'shoppingReading',+ });+ expect(status('shopLinksLive', page(html), 'failed')).toEqual({+ state: 'info',+ code: 'shoppingFailed',+ });+ expect(status('shopLinksLive', page(html), null)).toEqual({+ state: 'info',+ code: 'noShoppingPath',+ });+ expect(status('shopCategoryLink', page(html), { ...shopping, categories: [] })).toEqual({+ state: 'info',+ code: 'noShoppingPath',+ });+ // Every product sold out: none to link, pick again in Brief.+ const soldOut = { ...shopping, products: [item(2, 'Trail', 'sold_out')] };+ expect(status('shopProductLinks', page(html), soldOut)).toEqual({+ state: 'info',+ code: 'noShoppingPath',+ });+ });++ it('says what to do instead when only a sold-out link is open: not the feed’s message', () => {+ expect(notForAgentMessage([{ rule: { key: 'shopLinksLive' } }])).toBe('notForAgentShopping');+ expect(+ notForAgentMessage([{ rule: { key: 'shopLinksLive' } }, { rule: { key: 'feedMatch' } }]),+ ).toBe('notForAgentFeed');+ expect(+ notForAgentMessage([{ rule: { key: 'shopLinksLive' } }, { rule: { key: 'oneH1' } }]),+ ).toBe('notForAgent');+ });+});+describe('style', () => {it('finds AI traces and banned words', () => {expect(check('aiTraces', '<p>Let’s delve in. It is important to note this.</p>')).toEqual({diff --git a/web/src/lib/content/rules.ts b/web/src/lib/content/rules.tsindex ed579ac02..f3ea163de 100644--- a/web/src/lib/content/rules.ts+++ b/web/src/lib/content/rules.ts@@ -8,6 +8,12 @@ import { decodeHtmlBlock } from '@/lib/content/html-allowlist';import { pageOffer } from '@/lib/content/page-schema';import { countWords, languageCode } from '@/lib/content/readability';import { wordsOf } from '@/lib/content/sources';+import {+ shoppingLinks,+ type ShoppingCheck,+ type ShoppingLinkState,+} from '@/lib/content/shopping-check';+import { PRODUCTS_FOR } from '@/lib/content/shopping-path';/*** The editor's Rules tab (Content Editor CE-009, spec §10): the rules a page@@ -258,17 +264,47 @@ export function languageRuleValue(code: string | null | undefined): string {return label ? label.replace(/\s*\([^)]*\)$/, '') : 'English (US)';}+/**+ * A shopping path's rules (shopping path, part 6), on an online shop's page+ * that takes one: it links its category page, enough of its products, and+ * none that no longer sells.+ */+const SHOPPING_RULES: RuleDef[] = [+ { key: 'shopCategoryLink', group: 'links', kind: 'switch', value: '', check: 'page' },+ {+ key: 'shopProductLinks',+ group: 'links',+ kind: 'number',+ value: '3',+ unit: 'links',+ check: 'page',+ },+ { key: 'shopLinksLive', group: 'links', kind: 'switch', value: '', check: 'page' },+];++/** The Shopping rules' keys: checked against the shopping path (shoppingStatus). */+export const SHOPPING_RULE_KEYS: ReadonlySet<string> = new Set(SHOPPING_RULES.map((r) => r.key));+/*** The rules of a set: the type's own, then the shared groups, with the- * type's length, or the page's own when it was brought in to optimize.+ * type's length, or the page's own when it was brought in to optimize; and+ * a shopping path's on an online shop's page that takes one (`shopping`).*/export function ruleSet(pageType: PageType | null,- defaults: { keywords?: string[]; language?: string | null; length?: number | null } = {},+ defaults: {+ keywords?: string[];+ language?: string | null;+ length?: number | null;+ shopping?: boolean;+ } = {},): RuleDef[] {const own = (pageType && TYPE_RULES[pageType]) || [];+ const shopping =+ defaults.shopping && pageType && Object.hasOwn(PRODUCTS_FOR, pageType) ? SHOPPING_RULES : [];return [...own,+ ...shopping,...SHARED_RULES.map((rule) => {if (rule.key === 'length') {return { ...rule, value: String(defaults.length ?? lengthTarget(pageType)) };@@ -531,6 +567,12 @@ export interface PageRead {characters: number;/** H1s with words inside the page's HTML blocks. */htmlBlockH1s?: number;+ /**+ * Every link on the page, each once: in any block (a heading's, a table's+ * too) and inside its HTML blocks (a product card or grid's). What the+ * Shopping rules and Before you publish read (shopping path).+ */+ links?: string[];}const BLOCK_TAGS = 'h1, h2, h3, p, li, table, ol, ul, blockquote';@@ -556,6 +598,11 @@ export function readPage(html: string, characters: number): PageRead {// An HTML block's H1s are the page's too (One H1 per page): the editor// doesn't rewrite them, so the rule says so.let htmlBlockH1s = 0;+ // Every link, whatever block holds it, an HTML block's too: a product+ // card's or grid's counts for the Shopping rules.+ const links = new Set(+ [...doc.body.querySelectorAll('a[href]')].map((a) => a.getAttribute('href') ?? ''),+ );for (const el of doc.body.querySelectorAll('[data-html-block]')) {const inner = decodeHtmlBlock(el.getAttribute('data-html-block') ?? '');if (!inner) continue;@@ -563,6 +610,7 @@ export function readPage(html: string, characters: number): PageRead {htmlBlockH1s += [...block.body.querySelectorAll('h1')].filter((h) =>h.textContent?.trim(),).length;+ for (const a of block.body.querySelectorAll('a[href]')) links.add(a.getAttribute('href') ?? '');}return {blocks,@@ -572,6 +620,7 @@ export function readPage(html: string, characters: number): PageRead {.join(' '),characters,htmlBlockH1s,+ links: [...links].filter((href) => href.trim()),};}@@ -584,7 +633,13 @@ const isQuestion = (b: PageBlock) => b.text.trim().endsWith('?');/** A rule's status: met, not met (with what's missing), or one the page can't say. */export type RuleStatus =| { state: 'ok' }- | { state: 'bad'; code: 'over' | 'found'; count: number }+ | {+ state: 'bad';+ code: 'over' | 'found';+ count: number;+ /** The linked products that no longer sell, by name and why (shopLinksLive). */+ items?: { title: string; state: ShoppingLinkState }[];+ }| {state: 'bad';code: 'partOf';@@ -614,7 +669,11 @@ export type RuleStatus =| 'addKeywords'| 'notHowTo'| 'englishOnly'- | 'noSizes';+ | 'noSizes'+ /** No shopping path yet, it's being read, or it couldn't be (shopping path, part 6). */+ | 'noShoppingPath'+ | 'shoppingReading'+ | 'shoppingFailed';};export interface RuleContext {@@ -630,6 +689,12 @@ export interface RuleContext {* is read; none where the feed isn't checked (before Phase 3, other types).*/catalog?: CatalogMatch | 'reading' | null;+ /**+ * The page's shopping path read against the catalog now (shopping-check.ts),+ * for the Shopping rules: 'reading' while it is read, 'failed' when it+ * couldn't be; none without a path.+ */+ shopping?: ShoppingCheck | 'reading' | 'failed' | null;}/** Phrases that read as machine-written (spec §10, "Remove AI traces"). */@@ -763,13 +828,20 @@ const atLeast = (have: number, want: number): RuleStatus =>* Rules the Content Agent can't fix: it changes words and adds blocks, never* a heading's level, so a page's extra H1s are made H2s in the editor; a* price, GTIN or stock that differs from the feed is the person's to check- * (the page or the feed may be the one that's wrong).+ * (the page or the feed may be the one that's wrong); a linked product that+ * no longer sells is the person's to remove or replace.*/-export const NOT_FOR_AGENT = new Set(['oneH1', 'feedMatch']);+export const NOT_FOR_AGENT = new Set(['oneH1', 'feedMatch', 'shopLinksLive']);-/** What to do instead, for the open rules the agent doesn't fix: its message's key. */-export const notForAgentMessage = (open: readonly { rule: { key: string } }[]) =>- open.some(({ rule }) => rule.key === 'oneH1') ? 'notForAgent' : 'notForAgentFeed';+/**+ * What to do instead, for the open rules the agent doesn't fix: its+ * message's key, the extra H1s' first, then the feed's.+ */+export const notForAgentMessage = (open: readonly { rule: { key: string } }[]) => {+ const has = (key: string) => open.some(({ rule }) => rule.key === key);+ if (has('oneH1')) return 'notForAgent';+ return has('shopLinksLive') && !has('feedMatch') ? 'notForAgentShopping' : 'notForAgentFeed';+};/*** The fan-outs a rule still needs (fanoutH2, fanoutFaq), quoted for the@@ -1051,13 +1123,51 @@ function feedStatus(: { state: 'ok' };}+/**+ * A Shopping rule's status (shopping path, part 6), from every link on the+ * page (PageRead's `links`): the category page linked; at least `n` of the+ * path's products that sell, or all of them when fewer do; none that no+ * longer sells, by name.+ */+function shoppingStatus(+ key: string,+ n: number,+ hrefs: string[],+ check: RuleContext['shopping'],+): RuleStatus {+ if (check === 'reading') return { state: 'info', code: 'shoppingReading' };+ if (check === 'failed') return { state: 'info', code: 'shoppingFailed' };+ if (!check) return { state: 'info', code: 'noShoppingPath' };+ const read = shoppingLinks(hrefs, check, n);+ if (key === 'shopCategoryLink') {+ if (!check.categories.length) return { state: 'info', code: 'noShoppingPath' };+ return read.categoryLinked ? { state: 'ok' } : { state: 'bad', code: 'missing' };+ }+ if (key === 'shopProductLinks') {+ if (!read.products) return { state: 'info', code: 'noShoppingPath' };+ return atLeast(read.linked.length, read.want);+ }+ return read.bad.length+ ? {+ state: 'bad',+ code: 'found',+ count: read.bad.length,+ items: read.bad.map((p) => ({ title: p.title, state: p.state })),+ }+ : { state: 'ok' };+}++/** A number rule's value as the checks read it: a whole number, 0 when it isn't one. */+export const ruleNumber = (rule: Pick<ActiveRule, 'current'>) =>+ Math.max(0, Math.floor(Number(rule.current) || 0));+/** Checks one rule against the page as written. */export function checkRule(rule: ActiveRule, page: PageRead, ctx: RuleContext): RuleStatus {if (rule.check === 'feed') return feedStatus(page, ctx.catalog);if (rule.key === 'whoFor' && !rule.current.trim()) return { state: 'bad', code: 'notSet' };if (rule.check === 'ai') return { state: 'info', code: 'aiCheck' };- const n = Math.max(0, Math.floor(Number(rule.current) || 0));+ const n = ruleNumber(rule);const { blocks } = page;const h1 = blocks.findIndex((b) => b.tag === 'h1');const firstH2 = blocks.findIndex((b) => b.tag === 'h2');@@ -1067,6 +1177,9 @@ export function checkRule(rule: ActiveRule, page: PageRead, ctx: RuleContext): Rconst own = ctx.brandDomains.map(normalizeDomain);const competitors = ctx.competitorDomains.map(normalizeDomain);const links = blocks.flatMap((b) => (isText(b) ? b.links : []));+ if (SHOPPING_RULE_KEYS.has(rule.key)) {+ return shoppingStatus(rule.key, n, page.links ?? [], ctx.shopping);+ }const outbound = (href: string) => {const host = linkHost(href);if (!host) return false;diff --git a/web/src/lib/content/shopping-check.test.ts b/web/src/lib/content/shopping-check.test.tsnew file mode 100644index 000000000..af5b27eea--- /dev/null+++ b/web/src/lib/content/shopping-check.test.ts@@ -0,0 +1,95 @@+import { describe, expect, it } from 'vitest';+import {+ listed,+ shoppingLinks,+ type ShoppingCheck,+ type ShoppingLinkState,+} from './shopping-check';++/** A page's shopping links against its path (shopping path, part 6). */++const product = (id: string, state: ShoppingLinkState, inPath = true) => ({+ key: `shop.example/products/${id}`,+ title: id.toUpperCase(),+ state,+ inPath,+});++const CHECK: ShoppingCheck = {+ categories: ['shop.example/collections/boots'],+ products: [+ product('a', 'ok'),+ product('b', 'gone'),+ product('c', 'sold_out'),+ product('d', 'ok'),+ // Removed from the path, and sold out since.+ product('r', 'sold_out', false),+ ],+ site: 'https://www.shop.example/blog/boots',+};++describe('shoppingLinks', () => {+ it('reads the category page and the products linked, each once, and those that no longer sell', () => {+ const read = shoppingLinks(+ [+ 'https://www.shop.example/collections/boots/',+ 'https://shop.example/products/a?utm_source=feed',+ 'https://shop.example/products/a',+ 'https://shop.example/products/b',+ '/about',+ ],+ CHECK,+ 3,+ );+ expect(read.categoryLinked).toBe(true);+ // Only a product that sells counts as linked: the gone one is to remove.+ expect(read.linked.map((p) => p.title)).toEqual(['A']);+ expect(read.bad).toEqual([product('b', 'gone')]);+ // Two of the path's products sell: the rule's 3 asks for both.+ expect(read).toMatchObject({ products: 2, want: 2, categories: 1 });+ });++ it('counts a link to a product removed from the path that no longer sells', () => {+ const read = shoppingLinks(['https://shop.example/products/r'], CHECK, 3);+ expect(read.bad).toEqual([product('r', 'sold_out', false)]);+ expect(read.linked).toEqual([]);+ });++ it("keeps the path's product when a removed one has the same page", () => {+ const check = { ...CHECK, products: [product('a', 'ok'), product('a', 'gone', false)] };+ const read = shoppingLinks(['https://shop.example/products/a'], check, 3);+ expect(read.linked.map((p) => p.state)).toEqual(['ok']);+ expect(read.bad).toEqual([]);+ });++ it("reads a relative link against the page's address, and none without one", () => {+ const hrefs = [+ '/products/a',+ 'products/d',+ '//shop.example/products/c',+ 'mailto:[email protected]',+ ];+ const read = shoppingLinks(hrefs, CHECK, 3);+ expect(read.linked.map((p) => p.title)).toEqual(['A']);+ expect(read.bad.map((p) => p.title)).toEqual(['C']);+ // "products/d" is read beside the page: /blog/products/d, not the product.+ expect(shoppingLinks(['/products/a'], { ...CHECK, site: null }, 3).linked).toEqual([]);+ });++ it('asks for the number given, or all that sell when fewer do; none for 0', () => {+ expect(shoppingLinks([], CHECK, 1).want).toBe(1);+ expect(shoppingLinks([], CHECK, 0).want).toBe(0);+ expect(shoppingLinks([], CHECK, -2).want).toBe(0);+ expect(shoppingLinks([], { ...CHECK, products: [product('c', 'sold_out')] }, 3)).toMatchObject({+ products: 0,+ want: 0,+ });+ });+});++describe('listed', () => {+ it('names the first three, and counts the rest', () => {+ expect(listed([1, 2, 3, 4, 5])).toEqual({ shown: [1, 2, 3], more: 2 });+ expect(listed([1])).toEqual({ shown: [1], more: 0 });+ });+});diff --git a/web/src/lib/content/shopping-check.ts b/web/src/lib/content/shopping-check.tsnew file mode 100644index 000000000..fecdb0191--- /dev/null+++ b/web/src/lib/content/shopping-check.ts@@ -0,0 +1,106 @@+import { linkKey } from '@/lib/content/link-targets';++/**+ * Whether a page's shopping links still lead somewhere that sells+ * (shopping path, part 6): the category page it should link, and its+ * products as the catalog has them now. Read for the Rules tab's Shopping+ * rules and for Before you publish. A product the page links is checked+ * when it's one of the page's shopping path, or one the person removed from+ * it or the path left out: the page may still link it.+ */++/** A product's state now: sold out, refused by Merchant Center, gone from the catalog, or fine. */+export type ShoppingLinkState = 'ok' | 'sold_out' | 'refused' | 'gone';++export interface ShoppingProductCheck {+ /** Its page's link key (link-targets.ts linkKey). */+ key: string;+ title: string;+ state: ShoppingLinkState;+ /**+ * In the path now. False for one removed from it or left out, listed only+ * when it no longer sells: it counts for "No sold-out or refused product+ * linked" alone.+ */+ inPath: boolean;+}++export interface ShoppingCheck {+ /** The category pages' link keys (link-targets.ts linkKey). */+ categories: string[];+ /** The path's products first, then the removed and left-out ones that no longer sell. */+ products: ShoppingProductCheck[];+ /**+ * What a relative link on the page ("/products/x") is read against: the+ * page's address, else the brand's site; null when neither is known.+ */+ site: string | null;+}++/** What a page's links do with its shopping path. */+export interface ShoppingLinks {+ categoryLinked: boolean;+ /** The path's products that sell now and the page links, each once. */+ linked: ShoppingProductCheck[];+ /** The products the page links that no longer sell: sold out, refused or gone. */+ bad: ShoppingProductCheck[];+ /** The path's products that sell now, linked or not. */+ products: number;+ /** How many of them the page should link: `n`, or all of them when fewer sell; 0 for none. */+ want: number;+ /** The path's category pages. */+ categories: number;+}++/** A link's key, a relative one read against `site`; null when it leads to no page. */+function hrefKey(href: string, site: string | null): string | null {+ const text = href.trim();+ if (!text) return null;+ // A scheme ("https:", "mailto:"): read as written.+ if (/^[a-z][a-z\d+.-]*:/i.test(text)) return linkKey(text);+ if (!site) return null;+ try {+ return linkKey(new URL(text, site).toString());+ } catch {+ return null;+ }+}++/**+ * The page's links read against its shopping path, `n` the products it+ * should link (the Shopping rule's number). Only products that sell count+ * towards it: a sold-out one is the one to swap, not a link that counts.+ */+export function shoppingLinks(+ hrefs: readonly string[],+ check: ShoppingCheck,+ n = 0,+): ShoppingLinks {+ const keys = new Set(+ hrefs.map((href) => hrefKey(href, check.site)).filter((k): k is string => !!k),+ );+ // One per page: the path's first, before a removed one with the same page.+ const seen = new Set<string>();+ const products = check.products.filter((p) => {+ if (seen.has(p.key)) return false;+ seen.add(p.key);+ return true;+ });+ const selling = products.filter((p) => p.inPath && p.state === 'ok');+ return {+ categoryLinked: check.categories.some((key) => keys.has(key)),+ linked: selling.filter((p) => keys.has(p.key)),+ bad: products.filter((p) => p.state !== 'ok' && keys.has(p.key)),+ products: selling.length,+ want: Math.min(Math.max(0, n), selling.length),+ categories: check.categories.length,+ };+}++/** Names a list shows before "+N more". */+export const LISTED_MAX = 3;++/** The first few of a list to name, and how many more there are. */+export function listed<T>(items: readonly T[], max = LISTED_MAX): { shown: T[]; more: number } {+ return { shown: items.slice(0, max), more: Math.max(0, items.length - max) };+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 3d541f82f..d5f960f6d 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -917,6 +917,72 @@ export type Database = {},]}+ catalog_item_issues: {+ Row: {+ attribute: string | null+ brand_id: string+ code: string+ countries: string[]+ created_at: string+ description: string | null+ detail: string | null+ documentation: string | null+ external_id: string+ id: string+ reporting_context: string | null+ resolution: string | null+ severity: string+ source_id: string+ }+ Insert: {+ attribute?: string | null+ brand_id: string+ code: string+ countries?: string[]+ created_at?: string+ description?: string | null+ detail?: string | null+ documentation?: string | null+ external_id: string+ id?: string+ reporting_context?: string | null+ resolution?: string | null+ severity: string+ source_id: string+ }+ Update: {+ attribute?: string | null+ brand_id?: string+ code?: string+ countries?: string[]+ created_at?: string+ description?: string | null+ detail?: string | null+ documentation?: string | null+ external_id?: string+ id?: string+ reporting_context?: string | null+ resolution?: string | null+ severity?: string+ source_id?: string+ }+ Relationships: [+ {+ foreignKeyName: "catalog_item_issues_brand_id_fkey"+ columns: ["brand_id"]+ isOneToOne: false+ referencedRelation: "brands"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "catalog_item_issues_source_id_fkey"+ columns: ["source_id"]+ isOneToOne: false+ referencedRelation: "catalog_sources"+ referencedColumns: ["id"]+ },+ ]+ }catalog_products: {Row: {brand_id: string