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(prompts): suggest shopping questions from the brand's catalog, with a Shopping filter (Product Visibility, part 14) (#1649)

Cihanfb4163669570
diff --git a/docs/guides/prompts.mdx b/docs/guides/prompts.mdx
index a02734978..d333f646d 100644
--- a/docs/guides/prompts.mdx
+++ b/docs/guides/prompts.mdx
@@ -53,13 +53,14 @@ Late and Missing list the furthest behind first. A prompt with no answers in the
## Prompt Suggestions
-Open **Prompts → Prompt Suggestions**. Each refresh writes up to 25 prompt ideas, each with a topic label and a one-line reason. They come from three sources, and the **Source** filter shows one at a time:
+Open **Prompts → Prompt Suggestions**. Each refresh writes up to 25 prompt ideas, each with a topic label and a one-line reason. They come from four sources, and the **Source** filter shows one at a time:
- **Ansvisor Agents** — written by AI from your brand and tracking data. Each shows an estimated monthly AI volume as a grey range (see [Estimated AI search volume](#estimated-ai-search-volume)).
- **Google Search Console** — queries people already search, with their impressions a month.
- **Google Analytics (GA4)** — pages that earn revenue or conversions, or already get AI visits, with that evidence on the row.
+- **Your catalog** — for an online shop with a product catalog, the questions a shopper asks before buying in its categories, using their price bands ("best hiking backpacks under $150"). Hover the badge for the category; the **Shopping** filter lists them.
-When Search Console or Analytics is connected, a share of each refresh is drawn from their data. Use **Search prompts…** to narrow the list, `+` to add a suggestion, `×` to dismiss it and **New** to generate a fresh list. **Clear All** dismisses the AI suggestions listed; Search Console and Analytics suggestions are kept, so dismiss those one by one.
+When Search Console or Analytics is connected, a share of each refresh is drawn from their data, and a few shopping questions from the catalog when the brand has one. Use **Search prompts…** to narrow the list, `+` to add a suggestion, `×` to dismiss it and **New** to generate a fresh list. **Clear All** dismisses the AI suggestions listed; Search Console and Analytics suggestions are kept, so dismiss those one by one.
### Add All
diff --git a/server/src/lib/catalog-suggestions.js b/server/src/lib/catalog-suggestions.js
new file mode 100644
index 000000000..ba1a6422d
--- /dev/null
+++ b/server/src/lib/catalog-suggestions.js
@@ -0,0 +1,143 @@
+/**
+ * Catalog-fed suggestion candidates (ECOM-003).
+ *
+ * Shopping questions start from what the brand sells: its catalog's
+ * categories (00278), each with how many live products it has and their
+ * price band, so the model can ask what a shopper asks an assistant before
+ * buying there ("best hiking backpacks under $150"). Everything up to the
+ * LLM handoff is deterministic. Any failure returns [] so the base
+ * suggestion flow never degrades; brands without a catalog short-circuit on
+ * the first (empty) read.
+ */
+
+import supabaseAdmin from '../config/supabase.js';
+import { readAllRpcRows } from './rpc-pages.js';
+import { logger } from './logger.js';
+
+/** Categories offered to the model at most, those with the most products first. */
+export const MAX_CANDIDATES = 8;
+/** A category with fewer live products than this isn't offered. */
+const MIN_PRODUCTS = 2;
+/** Prices read for a band: the share of the category's products under its "under" price. */
+const UNDER_SHARE = 0.75;
+
+/** A price rounded up to one a shopper would name: 40, 150, 2,500. */
+export function roundPrice(value) {
+ if (!(value > 0)) return null;
+ const scale = 10 ** Math.floor(Math.log10(value));
+ for (const step of [1, 1.5, 2, 2.5, 3, 4, 5, 7.5, 10]) {
+ if (step * scale >= value) return Math.round(step * scale * 100) / 100;
+ }
+ return 10 * scale;
+}
+
+/**
+ * The categories as candidates: each one's products (live, priced or not)
+ * and, when they share a currency, their lowest and highest price and the
+ * round price most of them sell under.
+ *
+ * @param {{ categories: { id: string, name: string }[], links: { product_id: string, category_id: string }[], variants: { product_id: string, price: number|null, sale_price: number|null, currency: string|null }[] }} catalog
+ */
+export function composeCatalogCandidates({ categories, links, variants }) {
+ // Each product's price: its lowest variant's, on sale or not.
+ const priceOf = new Map();
+ for (const v of variants) {
+ const amount = Number(v.sale_price ?? v.price);
+ if (!(amount > 0)) continue;
+ const kept = priceOf.get(v.product_id);
+ if (!kept || amount < kept.amount) {
+ priceOf.set(v.product_id, { amount, currency: v.currency ?? null });
+ }
+ }
+ const productsOf = new Map();
+ for (const link of links) {
+ if (!productsOf.has(link.category_id)) productsOf.set(link.category_id, new Set());
+ productsOf.get(link.category_id).add(link.product_id);
+ }
+ const candidates = [];
+ for (const category of categories) {
+ const products = [...(productsOf.get(category.id) ?? [])];
+ if (products.length < MIN_PRODUCTS) continue;
+ const prices = products.map((id) => priceOf.get(id)).filter(Boolean);
+ const currencies = new Set(prices.map((p) => p.currency));
+ const band =
+ prices.length && currencies.size === 1 && [...currencies][0]
+ ? (() => {
+ const amounts = prices.map((p) => p.amount).sort((a, b) => a - b);
+ const at = Math.min(amounts.length - 1, Math.ceil(amounts.length * UNDER_SHARE) - 1);
+ return {
+ priceLow: amounts[0],
+ priceHigh: amounts.at(-1),
+ priceUnder: roundPrice(amounts[at]),
+ currency: [...currencies][0],
+ };
+ })()
+ : { priceLow: null, priceHigh: null, priceUnder: null, currency: null };
+ candidates.push({ category: category.name, products: products.length, ...band });
+ }
+ return candidates
+ .sort((a, b) => b.products - a.products || a.category.localeCompare(b.category))
+ .slice(0, MAX_CANDIDATES);
+}
+
+async function readAll(what, page) {
+ const { data, error } = await readAllRpcRows(what, page);
+ if (error) throw new Error(`${what} read: ${error.message}`);
+ return data;
+}
+
+/**
+ * The brand's catalog categories as shopping-question candidates; [] for a
+ * brand without a catalog, or when it can't be read.
+ */
+export async function getCatalogSuggestionCandidates(brandId, { db = supabaseAdmin } = {}) {
+ try {
+ const { data: categories, error } = await db
+ .from('catalog_categories')
+ .select('id, name')
+ .eq('brand_id', brandId)
+ .order('id')
+ .limit(1000);
+ if (error) throw new Error(error.message);
+ if (!categories?.length) return [];
+ const [products, links, variants] = await Promise.all([
+ readAll('catalog_products', (from, to) =>
+ db
+ .from('catalog_products')
+ .select('id')
+ .eq('brand_id', brandId)
+ .is('removed_at', null)
+ .order('id')
+ .range(from, to),
+ ),
+ readAll('catalog_product_categories', (from, to) =>
+ db
+ .from('catalog_product_categories')
+ .select('product_id, category_id')
+ .eq('brand_id', brandId)
+ .order('product_id')
+ .order('category_id')
+ .range(from, to),
+ ),
+ readAll('catalog_variants', (from, to) =>
+ db
+ .from('catalog_variants')
+ .select('product_id, price, sale_price, currency')
+ .eq('brand_id', brandId)
+ .is('removed_at', null)
+ .order('id')
+ .range(from, to),
+ ),
+ ]);
+ // A removed product's links stay; only the live ones count.
+ const live = new Set(products.map((p) => p.id));
+ return composeCatalogCandidates({
+ categories,
+ links: links.filter((link) => live.has(link.product_id)),
+ variants,
+ });
+ } catch (err) {
+ logger.error({ err, brandId }, '[catalog-suggestions] candidate read failed');
+ return [];
+ }
+}
diff --git a/server/src/lib/catalog-suggestions.test.js b/server/src/lib/catalog-suggestions.test.js
new file mode 100644
index 000000000..8a946ef53
--- /dev/null
+++ b/server/src/lib/catalog-suggestions.test.js
@@ -0,0 +1,158 @@
+import { describe, expect, it, vi } from 'vitest';
+
+// The module reaches the supabase admin client at import time, whose config
+// hard-exits when SUPABASE_* env is absent (as in CI).
+vi.mock('../config/supabase.js', () => ({ default: {} }));
+
+import { fakeDb } from './catalog/__fixtures__/fake-db.js';
+import {
+ MAX_CANDIDATES,
+ composeCatalogCandidates,
+ getCatalogSuggestionCandidates,
+ roundPrice,
+} from './catalog-suggestions.js';
+
+/** Shopping questions from the brand's catalog (ECOM-003). */
+
+describe('roundPrice', () => {
+ it('rounds a price up to one a shopper would name', () => {
+ expect([8, 38, 119, 140, 151, 1240, 9000].map(roundPrice)).toEqual([
+ 10, 40, 150, 150, 200, 1500, 10000,
+ ]);
+ expect(roundPrice(0)).toBeNull();
+ expect(roundPrice(null)).toBeNull();
+ });
+});
+
+describe('composeCatalogCandidates', () => {
+ const categories = [
+ { id: 'packs', name: 'Bags > Hiking backpacks' },
+ { id: 'socks', name: 'Socks' },
+ { id: 'mixed', name: 'Gift cards' },
+ { id: 'one', name: 'Tents' },
+ ];
+ const links = [
+ ...['p1', 'p2', 'p3', 'p4'].map((product_id) => ({ product_id, category_id: 'packs' })),
+ ...['s1', 's2'].map((product_id) => ({ product_id, category_id: 'socks' })),
+ ...['g1', 'g2'].map((product_id) => ({ product_id, category_id: 'mixed' })),
+ { product_id: 't1', category_id: 'one' },
+ ];
+ const variant = (product_id, price, extra = {}) => ({
+ product_id,
+ price,
+ sale_price: null,
+ currency: 'USD',
+ ...extra,
+ });
+ const variants = [
+ variant('p1', 60),
+ variant('p1', 80),
+ variant('p2', 119),
+ variant('p3', 140, { sale_price: 129 }),
+ variant('p4', 180),
+ // Socks without prices; gift cards in two currencies.
+ variant('s1', null),
+ variant('g1', 25),
+ variant('g2', 25, { currency: 'EUR' }),
+ ];
+
+ it('offers each category with its products and price band, the biggest first', () => {
+ expect(composeCatalogCandidates({ categories, links, variants })).toEqual([
+ {
+ category: 'Bags > Hiking backpacks',
+ products: 4,
+ priceLow: 60,
+ priceHigh: 180,
+ priceUnder: 150,
+ currency: 'USD',
+ },
+ {
+ category: 'Gift cards',
+ products: 2,
+ priceLow: null,
+ priceHigh: null,
+ priceUnder: null,
+ currency: null,
+ },
+ {
+ category: 'Socks',
+ products: 2,
+ priceLow: null,
+ priceHigh: null,
+ priceUnder: null,
+ currency: null,
+ },
+ ]);
+ });
+
+ it(`offers ${MAX_CANDIDATES} categories at most`, () => {
+ const many = Array.from({ length: 12 }, (_, i) => ({ id: `c${i}`, name: `Cat ${i}` }));
+ const manyLinks = many.flatMap((c) =>
+ ['a', 'b'].map((p) => ({ product_id: `${c.id}${p}`, category_id: c.id })),
+ );
+ expect(
+ composeCatalogCandidates({ categories: many, links: manyLinks, variants: [] }),
+ ).toHaveLength(MAX_CANDIDATES);
+ });
+});
+
+describe('getCatalogSuggestionCandidates', () => {
+ it("reads the brand's live catalog, and nothing for a brand without one", async () => {
+ const fake = fakeDb();
+ expect(await getCatalogSuggestionCandidates('brand-1', { db: fake.db })).toEqual([]);
+ fake.rows('catalog_categories').push({ id: 'c1', brand_id: 'brand-1', name: 'Boots' });
+ fake
+ .rows('catalog_products')
+ .push(
+ { id: 'p1', brand_id: 'brand-1', removed_at: null },
+ { id: 'p2', brand_id: 'brand-1', removed_at: null },
+ { id: 'p3', brand_id: 'brand-1', removed_at: '2026-10-01T00:00:00Z' },
+ );
+ fake.rows('catalog_product_categories').push(
+ ...['p1', 'p2', 'p3'].map((product_id) => ({
+ brand_id: 'brand-1',
+ product_id,
+ category_id: 'c1',
+ })),
+ );
+ fake.rows('catalog_variants').push(
+ {
+ id: 'v1',
+ brand_id: 'brand-1',
+ product_id: 'p1',
+ price: 99,
+ currency: 'USD',
+ removed_at: null,
+ },
+ {
+ id: 'v2',
+ brand_id: 'brand-1',
+ product_id: 'p2',
+ price: 129,
+ currency: 'USD',
+ removed_at: null,
+ },
+ );
+ expect(await getCatalogSuggestionCandidates('brand-1', { db: fake.db })).toEqual([
+ {
+ category: 'Boots',
+ products: 2,
+ priceLow: 99,
+ priceHigh: 129,
+ priceUnder: 150,
+ currency: 'USD',
+ },
+ ]);
+ });
+
+ it('returns nothing when the catalog cannot be read', async () => {
+ const db = {
+ from: () => ({
+ select: () => {
+ throw new Error('down');
+ },
+ }),
+ };
+ expect(await getCatalogSuggestionCandidates('brand-1', { db })).toEqual([]);
+ });
+});
diff --git a/server/src/routes/prompts-suggestions-refresh.test.js b/server/src/routes/prompts-suggestions-refresh.test.js
index 576cc78e1..efa67f43e 100644
--- a/server/src/routes/prompts-suggestions-refresh.test.js
+++ b/server/src/routes/prompts-suggestions-refresh.test.js
@@ -74,6 +74,8 @@ vi.mock('ai', () => ({ generateObject, NoObjectGeneratedError: class extends Err
vi.mock('../lib/ai-provider.js', () => ({ resolveModel: vi.fn(() => 'model') }));
vi.mock('../lib/gsc-suggestions.js', () => ({ getGscSuggestionCandidates: async () => [] }));
vi.mock('../lib/ga-suggestions.js', () => ({ getGaSuggestionCandidates: async () => [] }));
+const getCatalogSuggestionCandidates = vi.fn();
+vi.mock('../lib/catalog-suggestions.js', () => ({ getCatalogSuggestionCandidates }));
// Retries without the real backoff delay.
vi.mock('../lib/retry.js', () => ({
withRetry: async (fn, { attempts }) => {
@@ -114,6 +116,7 @@ beforeEach(async () => {
delete process.env.PROMPT_SUGGESTION_MODEL;
db = { inserts: [] };
reserveRelevanceAllowance.mockResolvedValue({ unlimited: false, id: 'r1' });
+ getCatalogSuggestionCandidates.mockResolvedValue([]);
settleRelevanceUsage.mockResolvedValue();
generateObject.mockResolvedValue(answer({ relevance: 8 }));
@@ -227,3 +230,41 @@ describe('suggestion refresh relevance', () => {
expect((await refresh()).status).toBe(200);
});
});
+
+describe('suggestion refresh from the catalog (ECOM-003)', () => {
+ const packs = {
+ category: 'Bags > Hiking backpacks',
+ products: 18,
+ priceLow: 60,
+ priceHigh: 180,
+ priceUnder: 150,
+ currency: 'USD',
+ };
+
+ it('asks for shopping questions from the categories, and keeps the one each came from', async () => {
+ getCatalogSuggestionCandidates.mockResolvedValue([packs]);
+ const suggestions = Array.from({ length: 15 }, (_, i) => suggestion(i));
+ suggestions[0] = suggestion(0, { sourceCategory: 'bags > hiking backpacks ' });
+ // A category the catalog never offered: a plain suggestion.
+ suggestions[1] = suggestion(1, { sourceCategory: 'Tents' });
+ generateObject.mockResolvedValue({ object: { suggestions }, usage: {} });
+
+ expect((await refresh()).status).toBe(200);
+ const { system, prompt } = generateObject.mock.calls[0][0];
+ expect(system).toContain('WHAT THE BRAND SELLS');
+ expect(system).toContain('Derive at least 1 shopping suggestions');
+ expect(prompt).toContain(
+ '"Bags > Hiking backpacks" — 18 products, 60–180 USD (most under 150 USD)',
+ );
+ const [rows] = insertsInto('prompt_suggestions');
+ expect(rows[0]).toMatchObject({ source: 'catalog', source_data: packs });
+ expect(rows[1]).toMatchObject({ source: 'llm', source_data: null });
+ });
+
+ it('leaves the catalog out of the prompt for a brand without one', async () => {
+ expect((await refresh()).status).toBe(200);
+ const { system, prompt } = generateObject.mock.calls[0][0];
+ expect(system).not.toContain('WHAT THE BRAND SELLS');
+ expect(prompt).not.toContain('product catalog categories');
+ });
+});
diff --git a/server/src/routes/prompts.js b/server/src/routes/prompts.js
index cfe7a3ea3..d4ea0f8f8 100644
--- a/server/src/routes/prompts.js
+++ b/server/src/routes/prompts.js
@@ -19,6 +19,7 @@ import {
import { withRetry } from '../lib/retry.js';
import { getGscSuggestionCandidates } from '../lib/gsc-suggestions.js';
import { getGaSuggestionCandidates } from '../lib/ga-suggestions.js';
+import { getCatalogSuggestionCandidates } from '../lib/catalog-suggestions.js';
import { suggestPromptsForPage } from '../lib/page-prompt-suggestions.js';
import { UNTRACKED_QUERY_SCAN, untrackedGoogleQueries } from '../lib/untracked-queries.js';
import { RELEVANCE_SCALE, ratingCostUsd, toRelevance } from '../lib/suggestion-relevance.js';
@@ -163,9 +164,11 @@ async function loadSuggestionContext(brandId) {
const SUGGESTIONS_PER_REFRESH = 25;
const MIN_SUGGESTIONS = 15;
// Floors for suggestions drawn from the brand's own data, when it has any —
-// about two in five from Search Console and one in four from Analytics.
+// about two in five from Search Console and one in four from Analytics, and
+// a few shopping questions from its catalog (ECOM-003).
const MIN_FROM_SEARCH_CONSOLE = 10;
const MIN_FROM_ANALYTICS = 6;
+const MIN_FROM_CATALOG = 5;
const newSuggestionSchema = z.object({
suggestions: z
@@ -211,6 +214,13 @@ const newSuggestionSchema = z.object({
.describe(
'ONLY when this suggestion was derived from one of the provided Analytics pages: the EXACT landing page path, verbatim. Omit for all other suggestions.',
),
+ sourceCategory: z
+ .string()
+ .max(750)
+ .optional()
+ .describe(
+ 'ONLY when this suggestion was derived from one of the provided catalog categories: the EXACT category name, verbatim. Omit for all other suggestions.',
+ ),
}),
)
.min(MIN_SUGGESTIONS)
@@ -298,6 +308,10 @@ async function generateSuggestions(brandId, { orgId, log }) {
// brands that have neither.
const gaCandidates = await getGaSuggestionCandidates(brandId, ctx.existingPromptTexts);
+ // What the brand sells (ECOM-003): its catalog's categories and price bands
+ // — [] without a catalog, which keeps every prompt block below unchanged.
+ const catalogCandidates = await getCatalogSuggestionCandidates(brandId);
+
const promptModel = process.env.PROMPT_SUGGESTION_MODEL || 'google/gemini-3-flash-preview';
const aiModel = resolveModel(promptModel);
const reservation = await reserveRating(orgId, brandId, promptModel, log);
@@ -329,6 +343,11 @@ RULES:
? `
- THE BRAND'S OWN ANALYTICS: a list of pages from this brand's Google Analytics is provided, each with what the page itself says it is about. Derive at least ${Math.min(MIN_FROM_ANALYTICS, gaCandidates.length)} suggestions from those pages. Write the prompt at the level of the need the page serves, NOT the page's product name or URL — a model number nobody types into an AI assistant becomes the category question that leads to it ("best noise-cancelling headphones", not "ANS-2400 Pro Black"). For each such suggestion set sourcePage to the EXACT landing page path, verbatim. Never set sourcePage on suggestions that did not come from that list, and never set both sourceQuery and sourcePage on the same suggestion.`
: ''
+ }${
+ catalogCandidates.length
+ ? `
+- WHAT THE BRAND SELLS: a list of its product catalog's categories is provided, each with how many products it sells and their price band. Derive at least ${Math.min(MIN_FROM_CATALOG, catalogCandidates.length)} shopping suggestions from those categories: the questions a shopper asks an AI assistant before buying in the category — best-of, under a budget (use the category's price band and currency, written as a shopper writes it), for a use or a person, or which type to choose. Use the category's own words, not the brand's or a product's name. For each such suggestion set sourceCategory to the EXACT category name, verbatim. Never set sourceCategory on suggestions that did not come from that list, and never set it together with sourceQuery or sourcePage.`
+ : ''
}`;
const v = ctx.volume;
@@ -385,6 +404,20 @@ ${gaCandidates
: ''
}
+${
+ catalogCandidates.length
+ ? `
+
+The brand's product catalog categories (live products, price band):
+${catalogCandidates
+ .map(
+ (c) =>
+ ` • "${c.category}" — ${c.products.toLocaleString('en-US')} products${c.currency ? `, ${c.priceLow}–${c.priceHigh} ${c.currency} (most under ${c.priceUnder} ${c.currency})` : ''}`,
+ )
+ .join('\n')}`
+ : ''
+}
+
Suggest the next ${SUGGESTIONS_PER_REFRESH} prompts this brand should start tracking, with topic, reason and a calibrated monthly AI search volume (estVolume).`;
// #379 pattern — bounded retry: generateObject throws "No object generated:
@@ -407,7 +440,7 @@ Suggest the next ${SUGGESTIONS_PER_REFRESH} prompts this brand should start trac
{ attempts: REFRESH_ATTEMPTS, baseDelayMs: 500, label: 'suggestion-refresh' },
);
usage = callUsage;
- return { suggestions: object.suggestions, gscCandidates, gaCandidates };
+ return { suggestions: object.suggestions, gscCandidates, gaCandidates, catalogCandidates };
} finally {
if (rate) await settleRating(log, reservation, { modelId: promptModel, attempts, usage });
}
@@ -438,10 +471,11 @@ router.post(
async (req, res) => {
try {
const { brand } = await assertBrandAccess(req.params.brandId, req.user.id);
- const { suggestions, gscCandidates, gaCandidates } = await generateSuggestions(
- req.params.brandId,
- { orgId: brand.organization_id, log: req.log },
- );
+ const { suggestions, gscCandidates, gaCandidates, catalogCandidates } =
+ await generateSuggestions(req.params.brandId, {
+ orgId: brand.organization_id,
+ log: req.log,
+ });
await supabaseAdmin
.from('prompt_suggestions')
@@ -459,6 +493,9 @@ router.post(
const normalizeQuery = (q) => q.trim().toLowerCase();
const candidateByQuery = new Map(gscCandidates.map((c) => [normalizeQuery(c.query), c]));
const candidateByPage = new Map(gaCandidates.map((c) => [normalizeQuery(c.landingPage), c]));
+ const candidateByCategory = new Map(
+ catalogCandidates.map((c) => [normalizeQuery(c.category), c]),
+ );
const rows = [];
for (const s of suggestions) {
@@ -473,6 +510,12 @@ router.post(
!candidate && s.sourcePage
? candidateByPage.get(normalizeQuery(s.sourcePage))
: undefined;
+ // A category only when neither Google source claims it: both are
+ // measured demand, the catalog is what the brand sells.
+ const catalogCandidate =
+ !candidate && !gaCandidate && s.sourceCategory
+ ? candidateByCategory.get(normalizeQuery(s.sourceCategory))
+ : undefined;
rows.push({
brand_id: req.params.brandId,
suggested_text: s.text,
@@ -483,7 +526,7 @@ router.post(
// estimate must cap out, not reject the whole generated batch.
est_volume: Math.min(s.estVolume, 10_000_000),
relevance: toRelevance(s.relevance),
- source: candidate ? 'gsc' : gaCandidate ? 'ga' : 'llm',
+ source: candidate ? 'gsc' : gaCandidate ? 'ga' : catalogCandidate ? 'catalog' : 'llm',
source_data: candidate
? {
query: candidate.query,
@@ -506,7 +549,16 @@ router.post(
aiPlatforms: gaCandidate.aiPlatforms,
pageTitle: gaCandidate.page?.title ?? null,
}
- : null,
+ : catalogCandidate
+ ? {
+ category: catalogCandidate.category,
+ products: catalogCandidate.products,
+ priceLow: catalogCandidate.priceLow,
+ priceHigh: catalogCandidate.priceHigh,
+ priceUnder: catalogCandidate.priceUnder,
+ currency: catalogCandidate.currency,
+ }
+ : null,
status: 'new',
expires_at: expiresAt,
});
diff --git a/supabase/migrations/00362_prompt_suggestions_catalog_source.sql b/supabase/migrations/00362_prompt_suggestions_catalog_source.sql
new file mode 100644
index 000000000..4a2f49b76
--- /dev/null
+++ b/supabase/migrations/00362_prompt_suggestions_catalog_source.sql
@@ -0,0 +1,11 @@
+-- ============================================================================
+-- 00362: the catalog as a prompt-suggestion source (product visibility, part 14)
+-- ============================================================================
+-- Shopping questions drawn from the brand's catalog categories and their price
+-- bands (ECOM-003) carry source 'catalog', with the category behind them in
+-- source_data. Without it in the check the suggestion insert fails outright,
+-- so this lands with the generator that writes those rows.
+
+alter table public.prompt_suggestions drop constraint prompt_suggestions_source_check;
+alter table public.prompt_suggestions add constraint prompt_suggestions_source_check
+ check (source = any (array['llm', 'heuristic', 'gsc', 'ga', 'catalog']));
diff --git a/supabase/schema.sql b/supabase/schema.sql
index a1b7d829e..71f6f2ef9 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -42073,6 +42073,21 @@ comment on function public.catalog_product_ai_stats(uuid, timestamptz, timestamp
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00362_prompt_suggestions_catalog_source.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00362: the catalog as a prompt-suggestion source (product visibility, part 14)
+-- ============================================================================
+-- Shopping questions drawn from the brand's catalog categories and their price
+-- bands (ECOM-003) carry source 'catalog', with the category behind them in
+-- source_data. Without it in the check the suggestion insert fails outright,
+-- so this lands with the generator that writes those rows.
+
+alter table public.prompt_suggestions drop constraint prompt_suggestions_source_check;
+alter table public.prompt_suggestions add constraint prompt_suggestions_source_check
+ check (source = any (array['llm', 'heuristic', 'gsc', 'ga', 'catalog']));
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00365_action_outcome_mixed.sql
-- ─────────────────────────────────────────────────────────────────────────
diff --git a/web/messages/en.json b/web/messages/en.json
index 0a2ac7e1f..3e583fe47 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -7274,6 +7274,12 @@
"gaps": "Content Gaps",
"suggestions": {
"measuredSuggestionsKept": "Search Console and Analytics suggestions were kept — dismiss them individually to hide them for 30 days.",
+ "catalog": {
+ "badge": "Your catalog",
+ "tooltip": "A shopping question from your catalog's “{category}” category, with {products, plural, one {# product} other {# products}}.",
+ "tooltipPrice": "A shopping question from your catalog's “{category}” category, with {products, plural, one {# product} other {# products}}, most under {price}.",
+ "filter": "Shopping"
+ },
"addAll": "Add All",
"addingAll": "Adding…",
"addAllTitle": "Add every suggestion listed below to your tracked prompts",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx
index 168db5584..dd7b5fced 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.test.tsx
@@ -291,3 +291,49 @@ describe('SuggestionsCard on a read-only workspace (plan not active)', () => {
expect(openUpgrade).not.toHaveBeenCalled();
});
});
+
+describe('SuggestionsCard — shopping questions from the catalog (ECOM-003)', () => {
+ const fromCatalog: PromptSuggestion = {
+ ...suggestion(2),
+ suggestedText: 'best hiking backpacks under $150',
+ source: 'catalog',
+ sourceData: {
+ category: 'Bags > Hiking backpacks',
+ products: 18,
+ priceLow: 60,
+ priceHigh: 180,
+ priceUnder: 150,
+ currency: 'USD',
+ },
+ };
+
+ async function show(search = '') {
+ window.history.replaceState(null, '', `/dashboard/prompts${search}`);
+ actions.getPromptSuggestions.mockResolvedValue({ suggestions: [suggestion(1), fromCatalog] });
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <SuggestionsCard brandId="b1" onAccepted={onAccepted} sourceStates={null} />
+ </NextIntlClientProvider>,
+ );
+ });
+ }
+
+ afterEach(() => window.history.replaceState(null, '', '/'));
+
+ it('marks a suggestion drawn from the catalog as Your catalog', async () => {
+ await show();
+ const [plain, shopping] = [...rows()];
+ expect(plain.textContent).not.toContain('Your catalog');
+ expect(shopping.textContent).toContain('Your catalog');
+ expect(shopping.textContent).toContain('Ansvisor Agents');
+ });
+
+ it('lists only the shopping questions on ?source=shopping', async () => {
+ await show('?source=shopping');
+ expect([...rows()].map((li) => li.textContent)).toEqual([
+ expect.stringContaining('best hiking backpacks under $150'),
+ ]);
+ expect(container.textContent).toContain('Shopping');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx
index 98f65904e..f45fac421 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx
@@ -24,6 +24,7 @@ import {
Trash2,
BarChart3,
Clock,
+ ShoppingBag,
} from 'lucide-react';
import { Filter } from 'lucide-react';
import { Input } from '@/components/ui/input';
@@ -53,7 +54,9 @@ import {
type PromptSuggestion,
} from '@/lib/actions/prompt-suggestions';
import type { PlanId } from '@/config/plans';
+import { priceText } from '@/lib/shopping/price';
import {
+ catalogSourceData,
fromYourData,
gaSourceData,
gscSourceData,
@@ -154,13 +157,15 @@ function HoverTip({ content, children }: { content: string; children: React.Reac
*
* Every suggestion is phrased by our own generation step, so `Ansvisor Agents`
* is always present; a data source badge joins it when the suggestion was
- * mined from the brand's own Search Console or Analytics rather than from the
- * model alone. Two badges is the honest reading — the data and the phrasing
- * come from different places.
+ * mined from the brand's own Search Console or Analytics, or drawn from its
+ * catalog (ECOM-003), rather than from the model alone. Two badges is the
+ * honest reading — the data and the phrasing come from different places.
*/
function SourceBadges({ suggestion }: { suggestion: PromptSuggestion }) {
+ const tCatalog = useTranslations('prompts.suggestions.catalog');
const gsc = gscSourceData(suggestion);
const ga = gaSourceData(suggestion);
+ const catalog = catalogSourceData(suggestion);
return (
<div className="flex flex-wrap items-center gap-1.5">
@@ -197,6 +202,24 @@ function SourceBadges({ suggestion }: { suggestion: PromptSuggestion }) {
</Badge>
</HoverTip>
)}
+ {catalog && (
+ <HoverTip
+ content={
+ catalog.priceUnder !== null
+ ? tCatalog('tooltipPrice', {
+ category: catalog.category,
+ products: catalog.products,
+ price: priceText(catalog.priceUnder, catalog.currency),
+ })
+ : tCatalog('tooltip', { category: catalog.category, products: catalog.products })
+ }
+ >
+ <Badge variant="outline" className="gap-1.5 bg-card text-xs font-normal">
+ <ShoppingBag className="h-3.5 w-3.5 text-emerald-600 dark:text-emerald-400" />
+ {tCatalog('badge')}
+ </Badge>
+ </HoverTip>
+ )}
<HoverTip content="Phrased by Ansvisor from your brand, the prompts you already track, and the competitors cited in your AI answers.">
<Badge variant="outline" className="gap-1.5 bg-card text-xs font-normal">
<Shield className="h-3.5 w-3.5 text-muted-foreground" />
@@ -208,9 +231,12 @@ function SourceBadges({ suggestion }: { suggestion: PromptSuggestion }) {
}
/** Which data source a row carries, for the source filter. */
-type SourceFilter = 'all' | 'data' | 'gsc' | 'ga' | 'agents';
+type SourceFilter = 'all' | 'data' | 'gsc' | 'ga' | 'shopping' | 'agents';
+
+const SOURCE_FILTERS: SourceFilter[] = ['all', 'data', 'gsc', 'ga', 'shopping', 'agents'];
-const SOURCE_FILTER_LABELS: Record<SourceFilter, string> = {
+// Shopping's label is translated (prompts.suggestions.catalog.filter).
+const SOURCE_FILTER_LABELS: Record<Exclude<SourceFilter, 'shopping'>, string> = {
all: 'All sources',
// Either Google source: Getting started's high-value prompts step links here
// with ?source=data.
@@ -302,13 +328,7 @@ export function SuggestionsCard({
const [sourceFilter, setSourceFilter] = useState<SourceFilter>('all');
// A link can open the list on a source (?source=data).
useEffect(() => {
- setSourceFilter(
- readUrlChoice<SourceFilter>(
- 'source',
- Object.keys(SOURCE_FILTER_LABELS) as SourceFilter[],
- 'all',
- ),
- );
+ setSourceFilter(readUrlChoice<SourceFilter>('source', SOURCE_FILTERS, 'all'));
}, []);
const [search, setSearch] = useState('');
const [clearing, setClearing] = useState(false);
@@ -371,7 +391,8 @@ export function SuggestionsCard({
if (sourceFilter === 'data' && !fromYourData(s)) return false;
if (sourceFilter === 'gsc' && !gscSourceData(s)) return false;
if (sourceFilter === 'ga' && !gaSourceData(s)) return false;
- if (sourceFilter === 'agents' && fromYourData(s)) return false;
+ if (sourceFilter === 'shopping' && !catalogSourceData(s)) return false;
+ if (sourceFilter === 'agents' && (fromYourData(s) || catalogSourceData(s))) return false;
if (!q) return true;
return (
s.suggestedText.toLowerCase().includes(q) ||
@@ -381,6 +402,16 @@ export function SuggestionsCard({
});
}, [suggestions, sourceFilter, search]);
+ // Shopping is offered once the catalog gave a suggestion (ECOM-003), or a link asked for it.
+ const filters = SOURCE_FILTERS.filter(
+ (key) =>
+ key !== 'shopping' ||
+ sourceFilter === 'shopping' ||
+ suggestions.some((s) => catalogSourceData(s) !== null),
+ );
+ const filterLabel = (key: SourceFilter) =>
+ key === 'shopping' ? t('catalog.filter') : SOURCE_FILTER_LABELS[key];
+
const notice = useMemo(
() => sourceNotice(sourceStates, suggestions),
[sourceStates, suggestions],
@@ -518,13 +549,13 @@ export function SuggestionsCard({
<SelectTrigger className="h-8 w-44 text-xs">
<Filter className="h-3.5 w-3.5 text-muted-foreground" />
<SelectValue placeholder="All sources">
- {(value) => SOURCE_FILTER_LABELS[(value as SourceFilter) ?? 'all']}
+ {(value) => filterLabel((value as SourceFilter) ?? 'all')}
</SelectValue>
</SelectTrigger>
<SelectContent>
- {(Object.keys(SOURCE_FILTER_LABELS) as SourceFilter[]).map((key) => (
+ {filters.map((key) => (
<SelectItem key={key} value={key}>
- {SOURCE_FILTER_LABELS[key]}
+ {filterLabel(key)}
</SelectItem>
))}
</SelectContent>
diff --git a/web/src/lib/prompt-suggestion-source.ts b/web/src/lib/prompt-suggestion-source.ts
index 573971db0..21ac14a48 100644
--- a/web/src/lib/prompt-suggestion-source.ts
+++ b/web/src/lib/prompt-suggestion-source.ts
@@ -35,9 +35,26 @@ export interface GaSuggestionSourceData {
pageTitle: string | null;
}
-export type SuggestionSourceData = GscSuggestionSourceData | GaSuggestionSourceData;
+/**
+ * The catalog category behind a shopping suggestion (ECOM-003): its live
+ * products and, when they share a currency, their price band.
+ */
+export interface CatalogSuggestionSourceData {
+ category: string;
+ products: number;
+ priceLow: number | null;
+ priceHigh: number | null;
+ /** The round price most of its products sell under. */
+ priceUnder: number | null;
+ currency: string | null;
+}
-export type PromptSuggestionSource = 'llm' | 'heuristic' | 'gsc' | 'ga';
+export type SuggestionSourceData =
+ | GscSuggestionSourceData
+ | GaSuggestionSourceData
+ | CatalogSuggestionSourceData;
+
+export type PromptSuggestionSource = 'llm' | 'heuristic' | 'gsc' | 'ga' | 'catalog';
interface SourceCarrier {
source: PromptSuggestionSource;
@@ -60,6 +77,11 @@ export function gaSourceData(s: SourceCarrier): GaSuggestionSourceData | null {
return s.source === 'ga' && s.sourceData && 'landingPage' in s.sourceData ? s.sourceData : null;
}
+/** A shopping question drawn from the brand's catalog: Prompt Suggestions' "Shopping" filter. */
+export function catalogSourceData(s: SourceCarrier): CatalogSuggestionSourceData | null {
+ return s.source === 'catalog' && s.sourceData && 'category' in s.sourceData ? s.sourceData : null;
+}
+
/**
* Built from the brand's own Search Console or Analytics data: Prompt
* Suggestions' "From your data" filter, which Getting started links to.