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 a shop's Shopping opportunities in the Content Plan (shopping path, part 7c) (#1617)

Cihanb5919470281a
diff --git a/docs/guides/content-editor.mdx b/docs/guides/content-editor.mdx
index 8142267e0..21e94e014 100644
--- a/docs/guides/content-editor.mdx
+++ b/docs/guides/content-editor.mdx
@@ -80,6 +80,15 @@ The shares cover only the cited addresses whose type can be read. Forums, encycl
category pages for e-commerce, destination and help pages for B2C.
</Tip>
+### Shopping opportunities
+
+For an online shop whose product catalog (**Settings › Integrations › Product catalog**) has categories, **Shopping opportunities** above the priority list shows the pages that lead readers, and AI answers, to your category pages and products:
+
+- **Buying guide · New**: a category with at least 3 products in stock that no page of yours guides shoppers to yet (no draft's shopping path holds it, and no draft's title names it). Why says how many of your tracked prompts ask about it, and whether it has a category page to link. **Create** starts the draft, "How to choose …" as a buying guide, from the first of those prompts, and opens it in the editor. A draft already being written for the category shows **Open draft** instead.
+- **Existing post · Fix**: a published post whose last check, after a catalog sync, found it links a product that no longer sells, or not each of its shopping path's category pages. **Optimize** opens it in the editor.
+
+Rows are ranked on the Plan's Priority Score scale. A guide scores as a new page, more for the prompts asking and the products in stock; a post scores more the more products it links that no longer sell.
+
## New content
**New content** opens from the Plan and the Library, from a Plan row's button, from **Send to Editor** on an opportunity, and from **Create content** in a prompt's menu on [Tracked Prompts](/guides/prompts).
@@ -178,6 +187,10 @@ The **Library** lists the drafts by status, each tab with its count:
The columns are Content, Type, Method (Create or Optimize), By (you, the Content Agent or a teammate), Status, Created and Updated. Click a row to open the draft in the editor. The **Created** filter narrows the list to the last 7, 30 or 90 days. Once a page has been sent to your CMS, a **Last send** filter lists the pages by how their last send went: never sent, sending, sent, failed or published (see [Send to CMS](/guides/send-to-cms)).
+For an online shop, a **Shopping path** column shows what the last check found for each draft with a shopping path. After each catalog sync, every such draft is read again: the live page once it's published, else the draft. A live page off your site, too short to be the page, or linking none of its shopping path while its draft does, is read from the draft. A draft needs attention when it links a product that is sold out, refused by Merchant Center or gone from your catalog; hover the mark for the products and how many of its category pages and products it links. The **Shopping path** filter narrows the list to drafts that need attention, are fine, or have none.
+
+When a published page links a product that no longer sells, the check also opens a **Fix** action in the [Action Center](/guides/action-center), "Best rain jackets for 2026: 2 products are sold out", with one task: swap them for products that sell, its shopping path's in-stock products named. **Swap in the editor** opens the draft. The next catalog sync's check, or **Check now** on the task, closes the task, and the action, once the live page links none of them. A dismissed action isn't opened again for the same products.
+
### Row menu
- **Status**: set the draft to In progress, In review, Ready or Published. Ready works like the editor's Mark ready. **Published** asks for the page's live address, as the editor's **Mark published** does (not for archived drafts). Moving a ready or published draft back to In progress or In review opens its task again, as the editor's **Ready** does; a published one also opens the action's Publish task again and stops its Live page being measured for the action.
diff --git a/web/messages/en.json b/web/messages/en.json
index 876621b05..29531c8d2 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3495,6 +3495,46 @@
"toggle": "{count, plural, one {# hidden row} other {# hidden rows}} · {open, select, true {Hide} other {Show}}",
"show": "Show again"
},
+ "shopping": {
+ "title": "Shopping opportunities",
+ "lead": "Pages that lead readers, and AI answers, to your category pages and products",
+ "catalog": "Catalog: {products, plural, one {# product} other {# products}} in {categories, plural, one {# category} other {# categories}}",
+ "columns": {
+ "page": "Page to make",
+ "why": "Why",
+ "category": "Category",
+ "score": "Priority",
+ "action": "Action"
+ },
+ "kinds": {
+ "guide": "Buying guide",
+ "fix": "Existing post"
+ },
+ "badges": {
+ "new": "New",
+ "draft": "Draft",
+ "fix": "Fix"
+ },
+ "guideTitle": "How to choose {category}",
+ "why": {
+ "prompts": "AI is asked about {category} in {count, plural, one {# of your prompts} other {# of your prompts}}, and no page of yours answers it.",
+ "noPrompts": "No page of yours guides shoppers to your {category} yet.",
+ "draft": "A draft for it is being written.",
+ "noCategoryPage": "It has no category page to link: set one in Settings › Integrations › Product catalog.",
+ "noCategoryLink": "No link to the {category} page.",
+ "categoryLinks": "It links {linked} of its {count} category pages.",
+ "soldOut": "{count, plural, one {# product it links is sold out.} other {# products it links are sold out.}}",
+ "noLongerSell": "{count, plural, one {# product it links no longer sells.} other {# products it links no longer sell.}}"
+ },
+ "stock": "{products, plural, one {# product} other {# products}} · {inStock} in stock",
+ "categoryGone": "No longer in your catalog",
+ "empty": "No shopping opportunities right now: each category in stock has a page, and your posts link products that sell.",
+ "create": "Create",
+ "open": "Open draft",
+ "optimize": "Optimize",
+ "createFailed": "Couldn't start the guide. Try again.",
+ "note": "Shopping opportunities show for shops with a product catalog. The Plan's other rows stay below."
+ },
"assign": {
"title": "Assign “{title}”",
"description": "It goes to the Action Center as a task for this teammate.",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_shopping-opportunities.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_shopping-opportunities.test.tsx
new file mode 100644
index 000000000..6cf8916ff
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_shopping-opportunities.test.tsx
@@ -0,0 +1,205 @@
+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 { CategoryPage } from '@/lib/catalog-client';
+import type { ShoppingPlanDraft } from '@/lib/content/shopping-plan';
+
+/** Plan › Shopping opportunities (shopping path, part 7). */
+
+const push = vi.hoisted(() => vi.fn());
+const listCategoryPages = vi.hoisted(() => vi.fn());
+const getShoppingPlan = vi.hoisted(() => vi.fn());
+const createContentDraft = vi.hoisted(() => vi.fn());
+const toastError = vi.hoisted(() => vi.fn());
+
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, children, ...props }: { href: string; children: React.ReactNode }) => (
+ <a href={href} {...props}>
+ {children}
+ </a>
+ ),
+ useRouter: () => ({ push }),
+}));
+vi.mock('sonner', () => ({ toast: { error: toastError } }));
+vi.mock('@/lib/catalog-client', () => ({ listCategoryPages }));
+vi.mock('@/lib/actions/shopping-plan', () => ({ getShoppingPlan }));
+vi.mock('@/lib/actions/content-drafts', () => ({ createContentDraft }));
+
+const { ShoppingOpportunities } = await import('./_shopping-opportunities');
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const BRAND = '33333333-3333-3333-3333-333333333333';
+
+const category = (name: string, inStock: number, page = true): CategoryPage => ({
+ name,
+ products: inStock + 6,
+ inStock,
+ page: page ? { url: 'https://shop.example/c/x', title: name } : null,
+ how: page ? 'address' : null,
+});
+
+const published = (id: string, over: Partial<ShoppingPlanDraft> = {}): ShoppingPlanDraft => ({
+ id,
+ title: 'Best rain jackets for 2026',
+ status: 'published',
+ categories: ['Outerwear > Rain Jackets'],
+ shopping: {
+ state: 'attention',
+ readFrom: 'page',
+ checkedAt: '2026-10-27T09:00:00Z',
+ categories: 1,
+ categoriesLinked: 0,
+ products: 4,
+ productsLinked: 2,
+ bad: [
+ { id: 'p1', title: 'Storm Shell 2', state: 'sold_out' },
+ { id: 'p2', title: 'Pack-Lite Jacket', state: 'sold_out' },
+ ],
+ },
+ ...over,
+});
+
+let container: HTMLDivElement;
+let root: Root;
+
+async function render(hidden = false) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <ShoppingOpportunities brandId={BRAND} hidden={hidden} />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+const button = (text: string) =>
+ [...container.querySelectorAll('button')].find((b) => b.textContent?.includes(text));
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ push.mockReset();
+ createContentDraft.mockReset();
+ toastError.mockReset();
+ listCategoryPages.mockReset().mockResolvedValue({
+ ok: true,
+ value: [
+ category('Shoes > Hiking Boots', 18),
+ category('Outerwear > Rain Jackets', 12),
+ category('Tents', 5, false),
+ ],
+ });
+ getShoppingPlan.mockReset().mockResolvedValue({
+ drafts: [published('d1')],
+ prompts: [
+ { id: '44444444-4444-4444-4444-444444444444', text: 'best waterproof hiking boots' },
+ { id: '55555555-5555-5555-5555-555555555555', text: 'hiking boots for wide feet' },
+ ],
+ products: 1240,
+ });
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('ShoppingOpportunities', () => {
+ it('lists the guides its categories miss and the posts to fix, ranked, with why and the stock', async () => {
+ await render();
+ expect(container.textContent).toContain('Shopping opportunities');
+ expect(container.textContent).toContain('Catalog: 1,240 products in 3 categories');
+ const rows = [...container.querySelectorAll('tbody tr')].map((r) => r.textContent);
+ // The post linking two sold-out products first, then the guides by their prompts and stock.
+ expect(rows).toHaveLength(3);
+ expect(rows[0]).toContain('Existing post');
+ expect(rows[0]).toContain('Best rain jackets for 2026');
+ expect(rows[0]).toContain(
+ 'No link to the Rain Jackets page. 2 products it links are sold out.',
+ );
+ expect(rows[0]).toContain('18 products · 12 in stock');
+ expect(rows[0]).toContain('Optimize');
+ expect(rows[1]).toContain('How to choose hiking boots');
+ expect(rows[1]).toContain('AI is asked about hiking boots in 2 of your prompts');
+ expect(rows[2]).toContain('How to choose tents');
+ expect(rows[2]).toContain('It has no category page to link');
+ const optimize = container.querySelector('a[href="/dashboard/content/editor/d1"]');
+ expect(optimize?.textContent).toBe('Optimize');
+ });
+
+ it("starts a buying guide as a draft from the category's first prompt, and opens it", async () => {
+ createContentDraft.mockResolvedValue('new-draft');
+ await render();
+ await act(async () => button('Create')!.click());
+ expect(createContentDraft).toHaveBeenCalledWith(BRAND, {
+ method: 'create',
+ title: 'How to choose hiking boots',
+ pageType: 'buying_guide',
+ typePicked: true,
+ source: { kind: 'prompt', id: '44444444-4444-4444-4444-444444444444' },
+ });
+ expect(push).toHaveBeenCalledWith('/dashboard/content/editor/new-draft');
+ });
+
+ it('says when a guide could not be started, and lets it be tried again', async () => {
+ createContentDraft.mockRejectedValue(new Error('boom'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ await render();
+ await act(async () => button('Create')!.click());
+ expect(toastError).toHaveBeenCalledWith("Couldn't start the guide. Try again.");
+ expect(button('Create')!.disabled).toBe(false);
+ });
+
+ it('opens the draft being written for a category instead of starting another', async () => {
+ getShoppingPlan.mockResolvedValue({
+ drafts: [
+ published('d1', { categories: [], shopping: { state: 'none' } }),
+ published('d2', { title: 'Hiking boots, a guide', status: 'draft', categories: [] }),
+ ],
+ prompts: [],
+ products: 30,
+ });
+ await render();
+ const open = container.querySelector('a[href="/dashboard/content/editor/d2"]');
+ expect(open?.textContent).toBe('Open draft');
+ expect(container.textContent).toContain('A draft for it is being written.');
+ });
+
+ it('says when there is nothing to do, and stays hidden without catalog categories', async () => {
+ listCategoryPages.mockResolvedValue({ ok: true, value: [category('Socks', 1)] });
+ getShoppingPlan.mockResolvedValue({ drafts: [], prompts: [], products: 1 });
+ await render();
+ expect(container.textContent).toContain('No shopping opportunities right now');
+
+ listCategoryPages.mockResolvedValue({ ok: true, value: [] });
+ act(() => root.unmount());
+ root = createRoot(container);
+ await render();
+ expect(container.textContent).toBe('');
+
+ listCategoryPages.mockResolvedValue({ ok: false, code: 'failed' });
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ act(() => root.unmount());
+ root = createRoot(container);
+ await render();
+ expect(container.textContent).toBe('');
+ });
+
+ it('keeps what it read while hidden, and shows it again without reading it anew', async () => {
+ await render(true);
+ expect(container.textContent).toBe('');
+ expect(getShoppingPlan).toHaveBeenCalledOnce();
+ await render(false);
+ expect(container.textContent).toContain('Shopping opportunities');
+ expect(getShoppingPlan).toHaveBeenCalledOnce();
+ expect(listCategoryPages).toHaveBeenCalledOnce();
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_shopping-opportunities.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_shopping-opportunities.tsx
new file mode 100644
index 000000000..84be9274a
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/_shopping-opportunities.tsx
@@ -0,0 +1,284 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { Loader2 } from 'lucide-react';
+import { Link, useRouter } from '@/i18n/navigation';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { buttonVariants } from '@/components/ui/button-variants';
+import { Card, CardContent } from '@/components/ui/card';
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@/components/ui/table';
+import { PriorityBadge } from '@/components/action-center/action-table';
+import { DRAFT_METHOD_BADGE } from '@/components/content/draft-badges';
+import { createContentDraft } from '@/lib/actions/content-drafts';
+import { getShoppingPlan } from '@/lib/actions/shopping-plan';
+import { listCategoryPages } from '@/lib/catalog-client';
+import { contentEditorPath } from '@/lib/content/drafts';
+import { planPriorityLevel } from '@/lib/content/plan';
+import { categoryLeaf, shoppingOpportunities, type ShoppingRow } from '@/lib/content/shopping-plan';
+import { formatNumber } from '@/lib/format';
+import { cn } from '@/lib/utils';
+
+type Read = {
+ brandId: string;
+ rows: ShoppingRow[];
+ products: number;
+ categories: number;
+};
+
+/**
+ * Plan › Shopping opportunities (shopping path, part 7): for a shop whose
+ * catalog has categories, the buying guides its categories in stock are
+ * missing and the published posts whose shopping links need fixing
+ * (lib/content/shopping-plan.ts), ranked on the Plan's scale. Create starts
+ * the guide as a draft in the editor; a row with a draft opens it. Read on
+ * its own: when it can't be, or the catalog has no categories, the section
+ * stays hidden and the Plan works as before. `hidden` keeps what it read
+ * while the Plan's list loads another period.
+ */
+export function ShoppingOpportunities({
+ brandId,
+ hidden = false,
+}: {
+ brandId: string;
+ hidden?: boolean;
+}) {
+ const t = useTranslations('contentEditor.plan.shopping');
+ const router = useRouter();
+ const [read, setRead] = useState<Read | null>(null);
+ const [creating, setCreating] = useState<string | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ Promise.all([listCategoryPages(brandId), getShoppingPlan(brandId)])
+ .then(([categories, plan]) => {
+ if (cancelled) return;
+ if (!categories.ok) {
+ console.error('Failed to read the catalog categories:', categories.code);
+ return;
+ }
+ setRead({
+ brandId,
+ rows: shoppingOpportunities({ categories: categories.value, ...plan }),
+ products: plan.products,
+ categories: categories.value.length,
+ });
+ })
+ .catch((err) => console.error('Failed to read the shopping opportunities:', err));
+ return () => {
+ cancelled = true;
+ };
+ }, [brandId]);
+
+ const current = read?.brandId === brandId ? read : null;
+ if (hidden || !current || current.categories === 0) return null;
+
+ const create = async (row: Extract<ShoppingRow, { kind: 'guide' }>) => {
+ setCreating(row.key);
+ try {
+ const id = await createContentDraft(brandId, {
+ method: 'create',
+ title: t('guideTitle', { category: row.leaf.toLocaleLowerCase() }),
+ pageType: 'buying_guide',
+ typePicked: true,
+ // The first prompt asking about it, else none yet: added in Sources.
+ source: row.promptId ? { kind: 'prompt', id: row.promptId } : { kind: 'content' },
+ });
+ router.push(contentEditorPath(id));
+ } catch (err) {
+ console.error('Failed to start the buying guide:', err);
+ toast.error(t('createFailed'));
+ setCreating(null);
+ }
+ };
+
+ return (
+ <ShoppingOpportunitiesView
+ rows={current.rows}
+ products={current.products}
+ categories={current.categories}
+ creating={creating}
+ onCreate={(row) => void create(row)}
+ />
+ );
+}
+
+/** The section as read: the catalog's line, the rows, and each row's button. */
+export function ShoppingOpportunitiesView({
+ rows,
+ products,
+ categories,
+ creating,
+ onCreate,
+}: {
+ rows: ShoppingRow[];
+ products: number;
+ categories: number;
+ /** The guide being started, by its row's key: every Create waits for it. */
+ creating: string | null;
+ onCreate: (row: Extract<ShoppingRow, { kind: 'guide' }>) => void;
+}) {
+ const t = useTranslations('contentEditor.plan.shopping');
+ return (
+ <section aria-labelledby="shopping-opportunities" className="space-y-2">
+ <div className="flex flex-wrap items-baseline justify-between gap-2">
+ <div>
+ <h2 id="shopping-opportunities" className="text-sm font-medium">
+ {t('title')}
+ </h2>
+ <p className="text-xs text-muted-foreground">{t('lead')}</p>
+ </div>
+ <p className="text-xs text-muted-foreground">{t('catalog', { products, categories })}</p>
+ </div>
+ <Card className="py-0">
+ <CardContent className="px-0">
+ {rows.length === 0 ? (
+ <p className="px-6 py-8 text-center text-sm text-muted-foreground">{t('empty')}</p>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="pl-6">{t('columns.page')}</TableHead>
+ <TableHead>{t('columns.why')}</TableHead>
+ <TableHead>{t('columns.category')}</TableHead>
+ <TableHead>{t('columns.score')}</TableHead>
+ <TableHead className="pr-6 text-right">{t('columns.action')}</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {rows.map((row) => (
+ <TableRow key={row.key}>
+ <TableCell className="min-w-[160px] max-w-[200px] whitespace-normal pl-6 xl:max-w-[260px]">
+ <p className="flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">
+ {t(`kinds.${row.kind}`)}
+ <Badge
+ variant="outline"
+ className={cn(
+ 'shrink-0',
+ row.kind === 'fix'
+ ? DRAFT_METHOD_BADGE.optimize
+ : row.draft
+ ? 'font-normal'
+ : DRAFT_METHOD_BADGE.create,
+ )}
+ >
+ {t(`badges.${row.kind === 'fix' ? 'fix' : row.draft ? 'draft' : 'new'}`)}
+ </Badge>
+ </p>
+ <RowTitle row={row} title={t('guideTitle', { category: guideName(row) })} />
+ </TableCell>
+ <TableCell className="min-w-[220px] max-w-[360px] whitespace-normal text-sm text-muted-foreground">
+ <WhyText row={row} />
+ </TableCell>
+ <TableCell className="max-w-[160px] xl:max-w-[200px]">
+ <CategoryCell row={row} />
+ </TableCell>
+ <TableCell>
+ <PriorityBadge
+ score={Math.round(row.score)}
+ level={planPriorityLevel(row.score)}
+ levelClassName="hidden xl:inline"
+ />
+ </TableCell>
+ <TableCell className="pr-6 text-right">
+ {row.draft ? (
+ <Link
+ href={contentEditorPath(row.draft.id)}
+ className={buttonVariants({ variant: 'outline', size: 'sm' })}
+ >
+ {row.kind === 'fix' ? t('optimize') : t('open')}
+ </Link>
+ ) : row.kind === 'guide' ? (
+ <Button
+ size="sm"
+ disabled={creating !== null}
+ onClick={() => onCreate(row)}
+ className="gap-1.5"
+ >
+ {creating === row.key && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
+ {t('create')}
+ </Button>
+ ) : null}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ )}
+ </CardContent>
+ </Card>
+ <p className="text-xs text-muted-foreground">{t('note')}</p>
+ </section>
+ );
+}
+
+/** A guide's category as its title reads it: "How to choose hiking boots". */
+function guideName(row: ShoppingRow): string {
+ return row.kind === 'guide' ? row.leaf.toLocaleLowerCase() : '';
+}
+
+function RowTitle({ row, title }: { row: ShoppingRow; title: string }) {
+ const text = row.kind === 'fix' ? row.draft.title : (row.draft?.title ?? title);
+ return (
+ <p className="mt-0.5 line-clamp-2 break-words font-medium" title={text}>
+ {text}
+ </p>
+ );
+}
+
+/** Why the row is listed, in one or two sentences. */
+function WhyText({ row }: { row: ShoppingRow }) {
+ const t = useTranslations('contentEditor.plan.shopping.why');
+ if (row.kind === 'guide') {
+ const category = row.leaf.toLocaleLowerCase();
+ return (
+ <>
+ {row.draft
+ ? t('draft')
+ : row.prompts > 0
+ ? t('prompts', { category, count: row.prompts })
+ : t('noPrompts', { category })}
+ {!row.category.page && <> {t('noCategoryPage')}</>}
+ </>
+ );
+ }
+ const lines: string[] = [];
+ if (row.categoriesLinked < row.categories) {
+ lines.push(
+ row.categories === 1 && row.categoryName
+ ? t('noCategoryLink', { category: categoryLeaf(row.categoryName) })
+ : t('categoryLinks', { linked: row.categoriesLinked, count: row.categories }),
+ );
+ }
+ if (row.bad > 0) lines.push(t(row.soldOut ? 'soldOut' : 'noLongerSell', { count: row.bad }));
+ return <>{lines.join(' ')}</>;
+}
+
+/** The category's own name and its products, as the catalog counts them now. */
+function CategoryCell({ row }: { row: ShoppingRow }) {
+ const t = useTranslations('contentEditor.plan.shopping');
+ const category = row.category;
+ const name = row.kind === 'guide' ? row.leaf : row.categoryName;
+ if (!name) return <span className="text-muted-foreground">—</span>;
+ return (
+ <>
+ <p className="truncate text-sm" title={category?.name ?? name}>
+ {categoryLeaf(name)}
+ </p>
+ <p className="truncate text-xs text-muted-foreground">
+ {category
+ ? t('stock', { products: category.products, inStock: formatNumber(category.inStock) })
+ : t('categoryGone')}
+ </p>
+ </>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx
index e0c91ed29..a3a0f7992 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.test.tsx
@@ -27,6 +27,20 @@ vi.mock('./_assign-dialog', () => ({
AssignDialog: ({ row }: { row: { title: string } | null }) =>
row ? <div data-testid="assign-dialog">{row.title}</div> : null,
}));
+// Shopping opportunities are _shopping-opportunities.test.tsx's; here, for
+// which brands, and that a new period's read keeps them (each mount reads).
+const shopping = vi.hoisted(() => ({ mounts: 0 }));
+vi.mock('./_shopping-opportunities', async () => {
+ const { useEffect } = await import('react');
+ return {
+ ShoppingOpportunities: ({ brandId, hidden }: { brandId: string; hidden?: boolean }) => {
+ useEffect(() => {
+ shopping.mounts += 1;
+ }, []);
+ return hidden ? null : <div data-testid="shopping-opportunities">{brandId}</div>;
+ },
+ };
+});
const role = vi.hoisted(() => ({ canManage: true }));
vi.mock('@/hooks/use-user-role', () => ({ useUserRole: () => role }));
const toast = vi.hoisted(() => Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn() }));
@@ -50,7 +64,10 @@ vi.mock('@/i18n/navigation', () => ({
}));
const brandState = vi.hoisted(() => ({
activeBrandId: 'brand-1' as string | null,
- brands: [{ id: 'brand-1', siteType: 'b2b' }],
+ brands: [
+ { id: 'brand-1', siteType: 'b2b' },
+ { id: 'shop-1', siteType: 'ecommerce' },
+ ],
}));
vi.mock('@/stores/use-brand-store', () => ({
useBrandStore: (selector: (state: typeof brandState) => unknown) => selector(brandState),
@@ -555,6 +572,39 @@ describe('the Content plan', () => {
expect(getContentPlanInsights).toHaveBeenCalledTimes(1);
});
+ it('shows a shop its Shopping opportunities above the list, and no other brand (shopping path, part 7)', async () => {
+ await renderPage();
+ expect(container.querySelector('[data-testid="shopping-opportunities"]')).toBeNull();
+ act(() => root.unmount());
+ root = createRoot(container);
+ brandState.activeBrandId = 'shop-1';
+ await renderPage();
+ const section = container.querySelector('[data-testid="shopping-opportunities"]');
+ expect(section?.textContent).toBe('shop-1');
+ // Above the ranked list.
+ const list = [...container.querySelectorAll('h2')].find(
+ (h) => h.textContent === 'Priority list',
+ );
+ expect(section!.compareDocumentPosition(list!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ });
+
+ it('keeps the Shopping opportunities through another period’s read, hidden while it loads', async () => {
+ brandState.activeBrandId = 'shop-1';
+ await renderPage();
+ const section = () => container.querySelector('[data-testid="shopping-opportunities"]');
+ expect(section()).not.toBeNull();
+ const mounts = shopping.mounts;
+ let resolve: (plan: typeof PLAN) => void = () => {};
+ getContentPlan.mockReturnValueOnce(new Promise((r) => (resolve = r)));
+ await act(async () => button('Last 7 days').click());
+ // The list loads: one spinner, the section kept but not shown.
+ expect(section()).toBeNull();
+ await act(async () => resolve(PLAN));
+ expect(section()?.textContent).toBe('shop-1');
+ // Not read again: the same section, never mounted anew.
+ expect(shopping.mounts).toBe(mounts);
+ });
+
it('says so when the plan can’t be read, and tries again', async () => {
getContentPlan.mockRejectedValueOnce(new Error('boom'));
await renderPage();
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx
index 8262e130a..9047e56b7 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/plan/page.tsx
@@ -39,6 +39,7 @@ import { useBrandStore } from '@/stores/use-brand-store';
import { AssignDialog } from './_assign-dialog';
import { AiResultsStrip, PageTypeMix } from './_plan-insights';
import { PlanTable } from './_plan-table';
+import { ShoppingOpportunities } from './_shopping-opportunities';
import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';
type PlanRead = {
@@ -88,7 +89,8 @@ function presetFor(row: PlanRow): DialogPreset {
* assigns it to a teammate, and lets admins and managers mark it as a
* priority or hide it; hidden rows can be shown again below the list. The
* period lives in the URL (?days=7). Getting started's content steps open
- * the Plan on its top Create or Optimize row (?start=create, 00234).
+ * the Plan on its top Create or Optimize row (?start=create, 00234). A shop
+ * with a catalog sees its Shopping opportunities above the list.
*/
export default function ContentPlanPage() {
const t = useTranslations('contentEditor.plan');
@@ -388,7 +390,15 @@ export default function ContentPlanPage() {
onSelect={setMixType}
/>
)}
-
+ </>
+ )}
+ {/* Its own read, of the catalog: kept through another period's read,
+ hidden while that loads, so the page still opens in its final layout. */}
+ {siteType === 'ecommerce' && (
+ <ShoppingOpportunities brandId={activeBrandId} hidden={loading} />
+ )}
+ {!loading && (
+ <>
<div className="space-y-2">
<div className="flex flex-wrap items-baseline justify-between gap-2">
<h2 className="text-sm font-medium">{t('listTitle')}</h2>
diff --git a/web/src/lib/actions/shopping-plan.test.ts b/web/src/lib/actions/shopping-plan.test.ts
new file mode 100644
index 000000000..d7c55f982
--- /dev/null
+++ b/web/src/lib/actions/shopping-plan.test.ts
@@ -0,0 +1,130 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Plan › Shopping opportunities' read (shopping path, part 7): the brand's
+ * drafts with their path's categories and last check, its active prompts,
+ * and its catalog's live products.
+ */
+
+const BRAND = '33333333-3333-3333-3333-333333333333';
+
+let tables: Record<string, { data?: unknown; count?: number; error?: { message: string } | null }>;
+let calls: { table: string; op: string; args: unknown[] }[];
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => ({
+ from: (table: string) => {
+ const chain: Record<string, unknown> = {};
+ for (const op of ['select', 'eq', 'is', 'order', 'limit']) {
+ chain[op] = (...args: unknown[]) => (calls.push({ table, op, args }), chain);
+ }
+ chain.then = (resolve: (r: unknown) => void) =>
+ resolve({ data: null, count: null, error: null, ...tables[table] });
+ return chain;
+ },
+ })),
+}));
+
+const { getShoppingPlan } = await import('./shopping-plan');
+
+beforeEach(() => {
+ calls = [];
+ tables = {
+ content_drafts: {
+ data: [
+ {
+ id: 'd1',
+ title: 'Best rain jackets',
+ status: 'published',
+ shopping_built: '2026-10-26T09:00:00.000Z',
+ shopping_categories: [
+ { name: 'Outerwear > Rain Jackets', url: 'https://shop.example/c/rain', title: 'Rain' },
+ ],
+ content_shopping_checks: [
+ {
+ read_from: 'page',
+ checked_at: '2026-10-27T09:00:00Z',
+ categories: 1,
+ categories_linked: 0,
+ products: 3,
+ products_linked: 2,
+ bad: [{ id: 'p1', title: 'Storm Shell 2', state: 'sold_out' }],
+ },
+ ],
+ },
+ {
+ id: 'd2',
+ title: null,
+ status: 'odd',
+ shopping_built: null,
+ shopping_categories: { not: 'a list' },
+ content_shopping_checks: [],
+ },
+ ],
+ },
+ prompts: {
+ data: [
+ { id: 'q1', text: 'best rain jackets' },
+ { id: 'q2', text: null },
+ ],
+ },
+ catalog_products: { count: 1240 },
+ };
+});
+
+describe('getShoppingPlan', () => {
+ it("reads the brand's drafts with their path's categories and last check, its prompts and products", async () => {
+ const plan = await getShoppingPlan(BRAND);
+ expect(plan.products).toBe(1240);
+ expect(plan.prompts).toEqual([
+ { id: 'q1', text: 'best rain jackets' },
+ { id: 'q2', text: '' },
+ ]);
+ expect(plan.drafts[0]).toEqual({
+ id: 'd1',
+ title: 'Best rain jackets',
+ status: 'published',
+ categories: ['Outerwear > Rain Jackets'],
+ shopping: expect.objectContaining({
+ state: 'attention',
+ readFrom: 'page',
+ categoriesLinked: 0,
+ bad: [{ id: 'p1', title: 'Storm Shell 2', state: 'sold_out' }],
+ }),
+ });
+ // A row of an odd shape is read as a draft with no path.
+ expect(plan.drafts[1]).toEqual({
+ id: 'd2',
+ title: '',
+ status: 'draft',
+ categories: [],
+ shopping: { state: 'none' },
+ });
+ const filters = (table: string) =>
+ calls.filter((c) => c.table === table && c.op !== 'select').map((c) => [c.op, c.args[0]]);
+ expect(filters('content_drafts')).toEqual(
+ expect.arrayContaining([
+ ['eq', 'brand_id'],
+ ['is', 'archived_at'],
+ ]),
+ );
+ expect(filters('prompts')).toEqual(
+ expect.arrayContaining([
+ ['eq', 'prompt_sets.brand_id'],
+ ['eq', 'is_active'],
+ ]),
+ );
+ expect(filters('catalog_products')).toEqual(
+ expect.arrayContaining([
+ ['eq', 'brand_id'],
+ ['is', 'removed_at'],
+ ]),
+ );
+ });
+
+ it('refuses a brand id that is no id, and throws a read that fails', async () => {
+ await expect(getShoppingPlan('nope')).rejects.toThrow('invalid');
+ tables.prompts = { error: { message: 'boom' } };
+ await expect(getShoppingPlan(BRAND)).rejects.toThrow('boom');
+ });
+});
diff --git a/web/src/lib/actions/shopping-plan.ts b/web/src/lib/actions/shopping-plan.ts
new file mode 100644
index 000000000..e31bfd0a9
--- /dev/null
+++ b/web/src/lib/actions/shopping-plan.ts
@@ -0,0 +1,76 @@
+'use server';
+
+import { z } from 'zod';
+import { createClient } from '@/lib/supabase/server';
+import { DRAFT_STATUSES } from '@/lib/content/drafts';
+import { draftShopping } from '@/lib/content/shopping-check';
+import type { ShoppingPlanDraft, ShoppingPlanPrompt } from '@/lib/content/shopping-plan';
+
+/**
+ * What Plan › Shopping opportunities is built from besides the catalog's
+ * categories (the browser reads those from the API, listCategoryPages),
+ * through the signed-in member's session: the brand's drafts with their
+ * shopping path's categories and its last check (00352), its active
+ * prompts, and how many products its catalog has. lib/content/
+ * shopping-plan.ts makes the rows.
+ */
+
+/** The newest drafts read: enough to know which categories a page guides to. */
+const DRAFT_LIMIT = 1000;
+/** The newest active prompts read, as Start matches a page's (PAGE_PROMPTS_READ). */
+const PROMPT_LIMIT = 1000;
+
+const categoriesSchema = z
+ .array(z.object({ name: z.string() }).passthrough())
+ .catch([])
+ .transform((list) => list.map((c) => c.name));
+
+export async function getShoppingPlan(brandId: string): Promise<{
+ drafts: ShoppingPlanDraft[];
+ prompts: ShoppingPlanPrompt[];
+ /** The catalog's live products. */
+ products: number;
+}> {
+ if (!z.guid().safeParse(brandId).success) throw new Error('invalid');
+ const supabase = await createClient();
+ const [drafts, prompts, products] = await Promise.all([
+ supabase
+ .from('content_drafts')
+ .select(
+ 'id, title, status, shopping_built:shopping_path->>builtAt, shopping_categories:shopping_path->categories, content_shopping_checks(read_from, checked_at, categories, categories_linked, products, products_linked, bad)',
+ )
+ .eq('brand_id', brandId)
+ .is('archived_at', null)
+ .order('updated_at', { ascending: false })
+ .limit(DRAFT_LIMIT),
+ supabase
+ .from('prompts')
+ .select('id, text, prompt_sets!inner(brand_id)')
+ .eq('prompt_sets.brand_id', brandId)
+ .eq('is_active', true)
+ .order('created_at', { ascending: false })
+ .limit(PROMPT_LIMIT),
+ supabase
+ .from('catalog_products')
+ .select('id', { count: 'exact', head: true })
+ .eq('brand_id', brandId)
+ .is('removed_at', null),
+ ]);
+ if (drafts.error) throw new Error(drafts.error.message);
+ if (prompts.error) throw new Error(prompts.error.message);
+ if (products.error) throw new Error(products.error.message);
+
+ return {
+ drafts: (drafts.data ?? []).map((row) => ({
+ id: row.id,
+ title: row.title ?? '',
+ status: (DRAFT_STATUSES as readonly string[]).includes(row.status)
+ ? (row.status as ShoppingPlanDraft['status'])
+ : 'draft',
+ categories: categoriesSchema.parse(row.shopping_categories),
+ shopping: draftShopping(row.shopping_built, row.content_shopping_checks),
+ })),
+ prompts: (prompts.data ?? []).map((p) => ({ id: p.id, text: p.text ?? '' })),
+ products: products.count ?? 0,
+ };
+}
diff --git a/web/src/lib/content/shopping-plan.test.ts b/web/src/lib/content/shopping-plan.test.ts
new file mode 100644
index 000000000..aef8311ac
--- /dev/null
+++ b/web/src/lib/content/shopping-plan.test.ts
@@ -0,0 +1,187 @@
+import { describe, expect, it } from 'vitest';
+import type { CategoryPage } from '@/lib/catalog-client';
+import { planPriorityLevel } from './plan';
+import type { DraftShopping } from './shopping-check';
+import {
+ MAX_GUIDES,
+ MIN_IN_STOCK,
+ categoryLeaf,
+ fixScore,
+ guideScore,
+ shoppingOpportunities,
+ type ShoppingPlanDraft,
+} from './shopping-plan';
+
+/** Plan › Shopping opportunities (shopping path, part 7). */
+
+const category = (name: string, inStock = 12, extra: Partial<CategoryPage> = {}): CategoryPage => ({
+ name,
+ products: inStock + 4,
+ inStock,
+ page: { url: `https://shop.example/c/${name.toLowerCase().replace(/\W+/g, '-')}`, title: name },
+ how: 'address',
+ ...extra,
+});
+
+const checked = (
+ over: Partial<Extract<DraftShopping, { readFrom: unknown }>> = {},
+): DraftShopping => ({
+ state: 'ok',
+ readFrom: 'page',
+ checkedAt: '2026-10-27T09:00:00Z',
+ categories: 1,
+ categoriesLinked: 1,
+ products: 3,
+ productsLinked: 3,
+ bad: [],
+ ...over,
+});
+
+const draft = (id: string, over: Partial<ShoppingPlanDraft> = {}): ShoppingPlanDraft => ({
+ id,
+ title: `Post ${id}`,
+ status: 'published',
+ categories: [],
+ shopping: { state: 'none' },
+ ...over,
+});
+
+describe('categoryLeaf', () => {
+ it("is a category's own name, the last step of its path", () => {
+ expect(categoryLeaf('Shoes > Hiking Boots')).toBe('Hiking Boots');
+ expect(categoryLeaf('Apparel › Jackets / Rain jackets')).toBe('Rain jackets');
+ expect(categoryLeaf('Boots')).toBe('Boots');
+ });
+});
+
+describe('scores', () => {
+ it("rank a guide as the Plan's new pages, up to 60, by the prompts asking and the stock", () => {
+ expect(guideScore(0, 0)).toBe(30);
+ expect(guideScore(3, 20)).toBe(60);
+ expect(guideScore(1, 20)).toBeGreaterThan(guideScore(0, 20));
+ expect(guideScore(9, 400)).toBe(60);
+ });
+
+ it('rank a post linking products that no longer sell above one missing its category link', () => {
+ expect(fixScore(0)).toBeLessThan(fixScore(1));
+ expect(fixScore(1)).toBeLessThan(fixScore(4));
+ expect(fixScore(4)).toBe(fixScore(10));
+ expect(planPriorityLevel(fixScore(4))).toBe('high');
+ });
+});
+
+describe('shoppingOpportunities', () => {
+ it('lists a buying guide for a category in stock no page guides to, with the prompts asking about it', () => {
+ const rows = shoppingOpportunities({
+ categories: [category('Shoes > Hiking Boots'), category('Socks', MIN_IN_STOCK - 1)],
+ drafts: [],
+ prompts: [
+ { id: 'q1', text: 'best waterproof hiking boots' },
+ { id: 'q2', text: 'Hiking boot for wide feet?' },
+ { id: 'q3', text: 'best running shoes' },
+ ],
+ });
+ expect(rows).toEqual([
+ expect.objectContaining({
+ kind: 'guide',
+ key: 'guide:Shoes > Hiking Boots',
+ leaf: 'Hiking Boots',
+ prompts: 2,
+ promptId: 'q1',
+ draft: null,
+ }),
+ ]);
+ });
+
+ it('leaves out a category a published page holds in its path or names in its title, and opens one still being written', () => {
+ const rows = shoppingOpportunities({
+ categories: [category('Rain Jackets'), category('Hiking Boots'), category('Tents')],
+ drafts: [
+ draft('d1', { categories: ['Rain Jackets'] }),
+ draft('d2', { title: 'The best hiking boots of 2026' }),
+ draft('d3', { title: 'Tents for two', status: 'draft' }),
+ ],
+ prompts: [],
+ });
+ expect(rows).toEqual([
+ expect.objectContaining({
+ kind: 'guide',
+ leaf: 'Tents',
+ draft: { id: 'd3', title: 'Tents for two' },
+ }),
+ ]);
+ });
+
+ it('lists a published post whose last check found sold-out links or a category page it misses', () => {
+ const rows = shoppingOpportunities({
+ categories: [category('Outerwear > Rain Jackets', 2)],
+ drafts: [
+ draft('sold', {
+ categories: ['Outerwear > Rain Jackets'],
+ shopping: checked({
+ state: 'attention',
+ categoriesLinked: 0,
+ bad: [
+ { id: 'p1', title: 'Storm Shell 2', state: 'sold_out' },
+ { id: 'p2', title: 'Pack-Lite', state: 'sold_out' },
+ ],
+ }),
+ }),
+ draft('unlinked', {
+ categories: ['Gone category'],
+ shopping: checked({ categories: 2, categoriesLinked: 1 }),
+ }),
+ draft('mixed', {
+ shopping: checked({
+ state: 'attention',
+ bad: [
+ { id: 'p1', title: 'Storm Shell 2', state: 'sold_out' },
+ { id: 'p3', title: 'Old', state: 'gone' },
+ ],
+ }),
+ }),
+ draft('fine', { shopping: checked() }),
+ draft('unchecked', { shopping: { state: 'unchecked' } }),
+ draft('writing', { status: 'ready', shopping: checked({ state: 'attention', bad: [] }) }),
+ ],
+ prompts: [],
+ });
+ expect(rows.map((r) => r.key)).toEqual(['fix:sold', 'fix:mixed', 'fix:unlinked']);
+ expect(rows[0]).toMatchObject({
+ kind: 'fix',
+ draft: { id: 'sold', title: 'Post sold' },
+ categoryName: 'Outerwear > Rain Jackets',
+ category: expect.objectContaining({ inStock: 2 }),
+ bad: 2,
+ soldOut: true,
+ categories: 1,
+ categoriesLinked: 0,
+ });
+ expect(rows[1]).toMatchObject({ soldOut: false, category: null, categoryName: null });
+ expect(rows[2]).toMatchObject({ bad: 0, category: null, categoryName: 'Gone category' });
+ });
+
+ it(`ranks every row by its score, at most ${MAX_GUIDES} guides`, () => {
+ const categories = Array.from({ length: MAX_GUIDES + 3 }, (_, i) =>
+ category(`Category ${String.fromCharCode(65 + i)}`, MIN_IN_STOCK + i),
+ );
+ const rows = shoppingOpportunities({
+ categories,
+ drafts: [
+ draft('sold', {
+ shopping: checked({
+ state: 'attention',
+ bad: [{ id: 'p1', title: 'Storm Shell 2', state: 'sold_out' }],
+ }),
+ }),
+ ],
+ prompts: [],
+ });
+ expect(rows.filter((r) => r.kind === 'guide')).toHaveLength(MAX_GUIDES);
+ expect(rows[0].key).toBe('fix:sold');
+ const scores = rows.map((r) => r.score);
+ expect(scores).toEqual([...scores].sort((a, b) => b - a));
+ // The deepest stock first among the guides: the shallowest ones are left out.
+ expect(rows.some((r) => r.key === 'guide:Category A')).toBe(false);
+ });
+});
diff --git a/web/src/lib/content/shopping-plan.ts b/web/src/lib/content/shopping-plan.ts
new file mode 100644
index 000000000..29ec1c6f9
--- /dev/null
+++ b/web/src/lib/content/shopping-plan.ts
@@ -0,0 +1,187 @@
+import type { CategoryPage } from '@/lib/catalog-client';
+import type { DraftStatus } from './drafts';
+import { SCORE_WEIGHTS } from './plan';
+import type { DraftShopping } from './shopping-check';
+import { wordsOf } from './sources';
+
+/**
+ * Plan › Shopping opportunities (shopping path, part 7; the mockup's
+ * "Content Plan · Shopping opportunities"): pages that lead readers, and AI
+ * answers, to a shop's category pages and products. Only for a shop with a
+ * catalog that has categories.
+ *
+ * - A buying guide for a catalog category with products in stock that no
+ * page of the brand's guides shoppers to yet: no draft's shopping path
+ * holds it and no draft's title names it. A draft still being written
+ * for it makes the row its draft's, to open; a published one ends it.
+ * - A published post to fix: the last check after a catalog sync (00352)
+ * found it links a product that no longer sells, or not each of its
+ * path's category pages.
+ *
+ * Scored on the Plan's scale (SCORE_WEIGHTS, planPriorityLevel): a guide as
+ * a new page, its opportunity the tracked prompts that ask about the
+ * category and the products in stock; a post by how bad its links are.
+ */
+
+/** A category needs this many products in stock for a guide. */
+export const MIN_IN_STOCK = 3;
+/** The guides listed, the best first. */
+export const MAX_GUIDES = 10;
+/** Prompts about a category that count in full for its opportunity, and products in stock. */
+const FULL_PROMPTS = 3;
+const FULL_IN_STOCK = 20;
+/** As the Plan's rows: a new page's severity, no page value known yet, no opportunity behind a fix. */
+const NEW_PAGE_SEVERITY = 0.5;
+const NEUTRAL_PAGE_VALUE = 0.5;
+const NO_OPPORTUNITY = 0.4;
+/** A post linking none of its category pages, and nothing worse. */
+const UNLINKED_SEVERITY = 0.45;
+/** Links to products that no longer sell that make it as bad as it gets. */
+const FULL_BAD = 4;
+
+/** A draft as the section reads it (lib/actions/shopping-plan.ts). */
+export interface ShoppingPlanDraft {
+ id: string;
+ title: string;
+ status: DraftStatus;
+ /** Its shopping path's categories, by name. */
+ categories: string[];
+ shopping: DraftShopping;
+}
+
+export interface ShoppingPlanPrompt {
+ id: string;
+ text: string;
+}
+
+export type ShoppingRow =
+ | {
+ kind: 'guide';
+ key: string;
+ category: CategoryPage;
+ /** The category's own name: "Hiking Boots" of "Shoes > Hiking Boots". */
+ leaf: string;
+ /** Tracked prompts that ask about it, and the first of them, for the draft. */
+ prompts: number;
+ promptId: string | null;
+ /** A draft being written for it. */
+ draft: { id: string; title: string } | null;
+ score: number;
+ }
+ | {
+ kind: 'fix';
+ key: string;
+ draft: { id: string; title: string };
+ /** Its path's first category, as the catalog counts it now (null when it's gone). */
+ category: CategoryPage | null;
+ categoryName: string | null;
+ /** Linked products that no longer sell, and whether every one is sold out. */
+ bad: number;
+ soldOut: boolean;
+ categories: number;
+ categoriesLinked: number;
+ score: number;
+ };
+
+/** A category's own name: the last step of "Shoes > Hiking Boots". */
+export function categoryLeaf(name: string): string {
+ const steps = name
+ .split(/\s*[>›/|]\s*/)
+ .map((s) => s.trim())
+ .filter(Boolean);
+ return steps.at(-1) ?? name.trim();
+}
+
+/** Whether a text names a category: every word of its own name is in it. */
+function names(textWords: Set<string>, leafWords: string[]): boolean {
+ return leafWords.length > 0 && leafWords.every((w) => textWords.has(w));
+}
+
+const round1 = (n: number) => Math.round(n * 10) / 10;
+
+/** A new guide's score: a new page's, its opportunity the prompts asking and the products in stock. */
+export function guideScore(prompts: number, inStock: number): number {
+ const opportunity =
+ 0.5 * Math.min(1, prompts / FULL_PROMPTS) + 0.5 * Math.min(1, inStock / FULL_IN_STOCK);
+ return round1(
+ SCORE_WEIGHTS.severity * NEW_PAGE_SEVERITY +
+ SCORE_WEIGHTS.opportunity * opportunity +
+ SCORE_WEIGHTS.pageValue * NEUTRAL_PAGE_VALUE,
+ );
+}
+
+/** A post's score: by the products it links that no longer sell, else the category pages it misses. */
+export function fixScore(bad: number): number {
+ const severity = bad > 0 ? 0.6 + 0.4 * Math.min(1, bad / FULL_BAD) : UNLINKED_SEVERITY;
+ return round1(
+ SCORE_WEIGHTS.severity * severity +
+ SCORE_WEIGHTS.opportunity * NO_OPPORTUNITY +
+ SCORE_WEIGHTS.pageValue * NEUTRAL_PAGE_VALUE,
+ );
+}
+
+/** The section's rows, the highest score first. */
+export function shoppingOpportunities({
+ categories,
+ drafts,
+ prompts,
+}: {
+ categories: readonly CategoryPage[];
+ drafts: readonly ShoppingPlanDraft[];
+ prompts: readonly ShoppingPlanPrompt[];
+}): ShoppingRow[] {
+ const byName = new Map(categories.map((c) => [c.name, c]));
+ const promptWords = prompts.map((p) => ({ id: p.id, words: new Set(wordsOf(p.text)) }));
+ const draftWords = drafts.map((d) => ({ draft: d, words: new Set(wordsOf(d.title)) }));
+
+ const guides: ShoppingRow[] = [];
+ for (const category of categories) {
+ if (category.inStock < MIN_IN_STOCK) continue;
+ const leaf = categoryLeaf(category.name);
+ const leafWords = [...new Set(wordsOf(leaf))];
+ const covering = draftWords
+ .filter(
+ ({ draft, words }) => draft.categories.includes(category.name) || names(words, leafWords),
+ )
+ .map(({ draft }) => draft);
+ // A published page already guides shoppers there: its links are the fix rows'.
+ if (covering.some((d) => d.status === 'published')) continue;
+ const asking = promptWords.filter((p) => names(p.words, leafWords));
+ const draft = covering[0];
+ guides.push({
+ kind: 'guide',
+ key: `guide:${category.name}`,
+ category,
+ leaf,
+ prompts: asking.length,
+ promptId: asking[0]?.id ?? null,
+ draft: draft ? { id: draft.id, title: draft.title } : null,
+ score: guideScore(asking.length, category.inStock),
+ });
+ }
+
+ const fixes: ShoppingRow[] = [];
+ for (const draft of drafts) {
+ if (draft.status !== 'published') continue;
+ const check = draft.shopping;
+ if (check.state !== 'attention' && check.state !== 'ok') continue;
+ const unlinked = check.categoriesLinked < check.categories;
+ if (!check.bad.length && !unlinked) continue;
+ const categoryName = draft.categories[0] ?? null;
+ fixes.push({
+ kind: 'fix',
+ key: `fix:${draft.id}`,
+ draft: { id: draft.id, title: draft.title },
+ category: categoryName ? (byName.get(categoryName) ?? null) : null,
+ categoryName,
+ bad: check.bad.length,
+ soldOut: check.bad.length > 0 && check.bad.every((b) => b.state === 'sold_out'),
+ categories: check.categories,
+ categoriesLinked: check.categoriesLinked,
+ score: fixScore(check.bad.length),
+ });
+ }
+
+ const byScore = (a: ShoppingRow, b: ShoppingRow) => b.score - a.score;
+ return [...guides.sort(byScore).slice(0, MAX_GUIDES), ...fixes].sort(byScore);
+}