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(shopping): normalize prompt_result_shopping_cards + parser worker (#143)
Gökhan Geyik048e5d001bb7
diff --git a/server/src/lib/cloro-result-handler.js b/server/src/lib/cloro-result-handler.jsindex 5299e5305..1560762d2 100644--- a/server/src/lib/cloro-result-handler.js+++ b/server/src/lib/cloro-result-handler.js@@ -10,11 +10,13 @@* 2. Runs sentiment analysis (only if brand was mentioned)* 3. Computes visibility metrics + competitor mentions via parseResponse* 4. Inserts a `prompt_results` row+ * 5. Normalizes any captured shopping_cards into prompt_result_shopping_cards*/import supabaseAdmin from '../config/supabase.js';import { analyzeSentimentAI } from './ai-tracker.js';import { parseResponse, countBrandMentions } from './response-parser.js';+import { normalizeShoppingCards, matchCardBrand } from './shopping-cards.js';/*** @param {object} args@@ -43,33 +45,117 @@ export async function handleScraperResult({? await analyzeSentimentAI(aiResponse.text, brandInfo.brandName): { sentiment: 'neutral', confidence: 0, reason: 'Brand not mentioned' };- const metrics = parseResponse(- aiResponse,- brandInfo,- sentimentResult.sentiment,- competitors,- );+ const metrics = parseResponse(aiResponse, brandInfo, sentimentResult.sentiment, competitors);- const { error } = await supabaseAdmin.from('prompt_results').insert({- prompt_id: promptId,- brand_id: brandId,- platform: scraperId,- response: aiResponse.text,- citations: aiResponse.citations,- mention_count: metrics.mentionCount,- citation_count: metrics.citationCount,- sentiment: sentimentResult.sentiment,- visibility_score: metrics.visibilityScore,- model_used: aiResponse.model,- region: region ?? null,- competitor_mentions: metrics.competitorMentions,- shopping_cards: aiResponse.shopping_cards ?? [],- });+ const { data: inserted, error } = await supabaseAdmin+ .from('prompt_results')+ .insert({+ prompt_id: promptId,+ brand_id: brandId,+ platform: scraperId,+ response: aiResponse.text,+ citations: aiResponse.citations,+ mention_count: metrics.mentionCount,+ citation_count: metrics.citationCount,+ sentiment: sentimentResult.sentiment,+ visibility_score: metrics.visibilityScore,+ model_used: aiResponse.model,+ region: region ?? null,+ competitor_mentions: metrics.competitorMentions,+ shopping_cards: aiResponse.shopping_cards ?? [],+ })+ .select('id')+ .single();if (error) {console.error('[cloro-result] Failed to insert result:', error.message);throw error;}+ // Best-effort normalization of any shopping cards on this result.+ // Failures here must not abort the result insert — the raw cards are+ // already persisted on prompt_results.shopping_cards and the backfill+ // script can re-derive the normalized rows later.+ await persistShoppingCards({+ promptResultId: inserted.id,+ brandId,+ platform: scraperId,+ region,+ rawCards: aiResponse.shopping_cards ?? [],+ brandInfo: { brandId, brandName: brandInfo.brandName, domains: brandInfo.domains },+ competitors,+ });+return { inserted: true };}++/**+ * Normalize and insert shopping cards into the analytical table.+ *+ * Exported so the backfill script can reuse the exact same code path+ * against historical prompt_results rows without duplicating the parse ++ * brand-match logic.+ *+ * @param {object} args+ * @param {string} args.promptResultId+ * @param {string} args.brandId+ * @param {string} args.platform+ * @param {string|null} args.region+ * @param {unknown[]} args.rawCards+ * @param {{ brandId: string, brandName: string, domains: string[] }} args.brandInfo+ * @param {Array<{ id: string, name: string, domain: string|null }>} args.competitors+ * @returns {Promise<number>} number of rows inserted (0 if none / on failure)+ */+export async function persistShoppingCards({+ promptResultId,+ brandId,+ platform,+ region,+ rawCards,+ brandInfo,+ competitors,+}) {+ const normalized = normalizeShoppingCards(platform, rawCards);+ if (normalized.length === 0) return 0;++ const rows = normalized.map((card) => {+ const match = matchCardBrand(card, brandInfo, competitors);+ return {+ prompt_result_id: promptResultId,+ brand_id: brandId,+ position: card.position,+ product_title: card.product_title,+ product_brand: card.product_brand,+ price_amount: card.price_amount,+ price_currency: card.price_currency,+ image_url: card.image_url,+ merchant_url: card.merchant_url,+ merchant_domain: card.merchant_domain,+ rating: card.rating,+ review_count: card.review_count,+ raw: card.raw,+ matched_brand_id: match.matched_brand_id,+ matched_brand_role: match.matched_brand_role,+ platform,+ region: region ?? null,+ };+ });++ // `onConflict: 'prompt_result_id,position' ignoreDuplicates: true` keeps+ // the call idempotent — re-running the backfill or a retry on the same+ // prompt_result won't duplicate or error.+ const { error } = await supabaseAdmin+ .from('prompt_result_shopping_cards')+ .upsert(rows, { onConflict: 'prompt_result_id,position', ignoreDuplicates: true });++ if (error) {+ console.error('[cloro-result] Shopping card normalization failed:', error.message, {+ promptResultId,+ platform,+ cardCount: rows.length,+ });+ return 0;+ }++ return rows.length;+}diff --git a/server/src/lib/shopping-cards.js b/server/src/lib/shopping-cards.jsnew file mode 100644index 000000000..fbb7f8593--- /dev/null+++ b/server/src/lib/shopping-cards.js@@ -0,0 +1,337 @@+/**+ * Normalize shopping cards captured into `prompt_results.shopping_cards`.+ *+ * Three providers feed this column today with three different raw shapes:+ *+ * - **Perplexity** (`platform = 'perplexity-web'`) — snake_case keys+ * (`image_url`, `review_count`, …).+ * - **Google AI Mode** (`platform = 'google-aimode'`) — camelCase keys+ * (`imageUrl`, `reviewCount`, …). NB: the live response is camelCase+ * even though the docs show snake_case — verified in #86.+ * - **Microsoft Copilot** (`platform = 'copilot-web'`) — camelCase keys.+ *+ * The downstream `prompt_result_shopping_cards` table flattens those onto+ * a single set of analytical columns. Each normalizer here pulls the+ * fields we care about, parses the price into amount + currency, and+ * leaves the original card under `raw` so we can re-derive columns later+ * without going back to the provider.+ *+ * Field-name lookups are intentionally lenient — both providers we've+ * looked at have shipped silent renames before (#49 retro on AI Mode),+ * and the cost of `?? otherName` is tiny.+ */++import { URL } from 'node:url';++// Loose set of currency codes Perplexity / Copilot embed in price strings+// like "$29.99", "EUR 19,90", "₺499". Anything else falls back to null —+// we still capture the numeric amount and the symbol stays in `raw`.+const CURRENCY_SYMBOLS = {+ $: 'USD',+ '€': 'EUR',+ '£': 'GBP',+ '¥': 'JPY',+ '₺': 'TRY',+ '₹': 'INR',+ '₩': 'KRW',+};++const CURRENCY_CODES = new Set([+ 'USD',+ 'EUR',+ 'GBP',+ 'JPY',+ 'TRY',+ 'INR',+ 'KRW',+ 'CAD',+ 'AUD',+ 'CHF',+ 'CNY',+ 'SEK',+ 'NOK',+ 'DKK',+ 'MXN',+ 'BRL',+]);++/**+ * @param {unknown} value+ * @returns {{ amount: number|null, currency: string|null }}+ */+function parsePrice(value) {+ if (value == null) return { amount: null, currency: null };++ // Object form: { amount, currency } or { value, currency }+ if (typeof value === 'object' && !Array.isArray(value)) {+ const amount =+ typeof value.amount === 'number'+ ? value.amount+ : typeof value.value === 'number'+ ? value.value+ : Number.parseFloat(value.amount ?? value.value ?? '');+ const currency =+ typeof value.currency === 'string'+ ? value.currency.toUpperCase()+ : typeof value.currencyCode === 'string'+ ? value.currencyCode.toUpperCase()+ : null;+ return {+ amount: Number.isFinite(amount) ? amount : null,+ currency: currency && CURRENCY_CODES.has(currency) ? currency : currency || null,+ };+ }++ // Numeric form (rare, but tolerate)+ if (typeof value === 'number' && Number.isFinite(value)) {+ return { amount: value, currency: null };+ }++ // String form — the common case. Examples we see in the wild:+ // "$29.99", "USD 29.99", "29.99 USD", "₺499,90", "€19,90"+ if (typeof value === 'string') {+ const trimmed = value.trim();++ // Currency by leading symbol+ let currency = null;+ for (const [symbol, code] of Object.entries(CURRENCY_SYMBOLS)) {+ if (trimmed.includes(symbol)) {+ currency = code;+ break;+ }+ }++ // Currency by 3-letter code anywhere in the string+ if (!currency) {+ const codeMatch = trimmed.match(/\b([A-Z]{3})\b/);+ if (codeMatch && CURRENCY_CODES.has(codeMatch[1])) {+ currency = codeMatch[1];+ }+ }++ // Amount — first decimal-looking number. Handles both "29.99" and+ // "29,99" (EU comma decimals) by normalizing comma → dot.+ const amountMatch = trimmed.replace(/\s+/g, '').match(/-?\d+(?:[.,]\d+)?/);+ const amount = amountMatch ? Number.parseFloat(amountMatch[0].replace(',', '.')) : null;++ return {+ amount: Number.isFinite(amount) ? amount : null,+ currency,+ };+ }++ return { amount: null, currency: null };+}++/**+ * @param {string|null|undefined} url+ * @returns {string|null}+ */+function extractHostname(url) {+ if (!url || typeof url !== 'string') return null;+ try {+ return new URL(url).hostname.replace(/^www\./i, '').toLowerCase();+ } catch {+ return null;+ }+}++/**+ * @param {unknown} value+ * @returns {number|null}+ */+function toNumber(value) {+ if (typeof value === 'number' && Number.isFinite(value)) return value;+ if (typeof value === 'string') {+ const n = Number.parseFloat(value.replace(',', '.'));+ return Number.isFinite(n) ? n : null;+ }+ return null;+}++/**+ * @param {unknown} value+ * @returns {number|null}+ */+function toInteger(value) {+ const n = toNumber(value);+ return n == null ? null : Math.round(n);+}++/**+ * @param {unknown} value+ * @returns {string|null}+ */+function toStringOrNull(value) {+ if (typeof value !== 'string') return null;+ const trimmed = value.trim();+ return trimmed.length > 0 ? trimmed : null;+}++/**+ * Perplexity card normalizer. Snake_case provider shape:+ *+ * { title, brand, price, image_url, url, rating, review_count, merchant, … }+ *+ * @param {object} card+ * @param {number} position+ */+export function parsePerplexityCard(card, position) {+ const price = parsePrice(card.price);+ const merchantUrl = toStringOrNull(card.url ?? card.link);+ return {+ position,+ product_title: toStringOrNull(card.title ?? card.name),+ product_brand: toStringOrNull(card.brand ?? card.merchant),+ price_amount: price.amount,+ price_currency: price.currency,+ image_url: toStringOrNull(card.image_url ?? card.image),+ merchant_url: merchantUrl,+ merchant_domain: extractHostname(merchantUrl),+ rating: toNumber(card.rating),+ review_count: toInteger(card.review_count ?? card.reviews),+ raw: card,+ };+}++/**+ * Google AI Mode card normalizer. CamelCase provider shape:+ *+ * { title, brand, price, imageUrl, url, rating, reviewCount, merchant, … }+ *+ * @param {object} card+ * @param {number} position+ */+export function parseAiModeCard(card, position) {+ const price = parsePrice(card.price);+ const merchantUrl = toStringOrNull(card.url ?? card.link);+ return {+ position,+ product_title: toStringOrNull(card.title ?? card.name ?? card.productName),+ product_brand: toStringOrNull(card.brand ?? card.merchant),+ price_amount: price.amount,+ price_currency: price.currency,+ image_url: toStringOrNull(card.imageUrl ?? card.image),+ merchant_url: merchantUrl,+ merchant_domain: extractHostname(merchantUrl),+ rating: toNumber(card.rating),+ review_count: toInteger(card.reviewCount ?? card.reviews),+ raw: card,+ };+}++/**+ * Microsoft Copilot card normalizer. CamelCase, slightly different field+ * names from AI Mode (`productName`, `productBrand`, `merchantName`).+ *+ * @param {object} card+ * @param {number} position+ */+export function parseCopilotCard(card, position) {+ const price = parsePrice(card.price);+ const merchantUrl = toStringOrNull(card.url ?? card.link ?? card.productUrl);+ return {+ position,+ product_title: toStringOrNull(card.productName ?? card.title ?? card.name),+ product_brand: toStringOrNull(card.productBrand ?? card.brand ?? card.merchantName),+ price_amount: price.amount,+ price_currency: price.currency,+ image_url: toStringOrNull(card.imageUrl ?? card.image),+ merchant_url: merchantUrl,+ merchant_domain: extractHostname(merchantUrl),+ rating: toNumber(card.rating),+ review_count: toInteger(card.reviewCount ?? card.reviewsCount ?? card.reviews),+ raw: card,+ };+}++/**+ * Pick the right normalizer for a platform / scraper id.+ *+ * @param {string|null|undefined} platform+ */+function pickParser(platform) {+ if (!platform || typeof platform !== 'string') return null;+ const p = platform.toLowerCase();+ if (p.startsWith('perplexity')) return parsePerplexityCard;+ if (p.startsWith('google-aimode') || p === 'google-ai-mode') return parseAiModeCard;+ if (p.startsWith('copilot')) return parseCopilotCard;+ return null;+}++/**+ * Normalize the raw `shopping_cards` array off a prompt_results row into+ * an array of analytical-column-shaped objects ready for insert.+ *+ * Returns `[]` for any platform without a parser or for empty input —+ * the worker can safely call this on every result without branching.+ *+ * @param {string} platform+ * @param {unknown} cards+ */+export function normalizeShoppingCards(platform, cards) {+ if (!Array.isArray(cards) || cards.length === 0) return [];+ const parser = pickParser(platform);+ if (!parser) return [];+ return cards+ .map((card, i) => {+ if (!card || typeof card !== 'object') return null;+ try {+ return parser(card, i);+ } catch (err) {+ // A bad card shouldn't kill the whole batch — log and drop.+ console.error('[shopping-cards] parser failed:', err.message, { platform, position: i });+ return null;+ }+ })+ .filter(Boolean);+}++/**+ * Match a normalized card against the tracked brand and competitors.+ * Returns `{ matched_brand_id, matched_brand_role }`.+ *+ * - `own` when the product brand, product title, or merchant domain+ * contains the tracked brand name OR matches one of its domains.+ * `matched_brand_id` is the brand's uuid.+ * - `competitor` when those same fields contain a tracked competitor's+ * name or merchant domain. `matched_brand_id` is the competitor's uuid.+ * - `other` otherwise. `matched_brand_id` is null.+ *+ * Substring matching mirrors the citations matcher in response-parser.js —+ * keeps the two surfaces aligned without an extra dependency.+ *+ * @param {ReturnType<typeof parsePerplexityCard>} card+ * @param {{ brandId: string, brandName: string, domains: string[] }} brand+ * @param {Array<{ id: string, name: string, domain: string|null }>} competitors+ */+export function matchCardBrand(card, brand, competitors) {+ const blob = [card.product_brand, card.product_title, card.merchant_domain]+ .filter(Boolean)+ .join(' ')+ .toLowerCase();++ const brandName = brand.brandName?.toLowerCase() ?? '';+ if (brandName && blob.includes(brandName)) {+ return { matched_brand_id: brand.brandId, matched_brand_role: 'own' };+ }+ for (const domain of brand.domains ?? []) {+ const d = domain?.toLowerCase();+ if (d && card.merchant_domain === d) {+ return { matched_brand_id: brand.brandId, matched_brand_role: 'own' };+ }+ }++ for (const comp of competitors ?? []) {+ const compName = comp.name?.toLowerCase();+ if (compName && blob.includes(compName)) {+ return { matched_brand_id: comp.id, matched_brand_role: 'competitor' };+ }+ const compDomain = comp.domain?.toLowerCase();+ if (compDomain && card.merchant_domain === compDomain) {+ return { matched_brand_id: comp.id, matched_brand_role: 'competitor' };+ }+ }++ return { matched_brand_id: null, matched_brand_role: 'other' };+}diff --git a/server/src/scripts/backfill-shopping-cards.js b/server/src/scripts/backfill-shopping-cards.jsnew file mode 100644index 000000000..67b828846--- /dev/null+++ b/server/src/scripts/backfill-shopping-cards.js@@ -0,0 +1,130 @@+/**+ * Backfill prompt_result_shopping_cards from the raw+ * prompt_results.shopping_cards JSONB column.+ *+ * Run: `node src/scripts/backfill-shopping-cards.js`+ *+ * Options via env:+ * - SHOPPING_BACKFILL_DAYS how far back to walk, in days (default 90)+ * - SHOPPING_BACKFILL_BATCH prompt_results pulled per batch (default 200)+ *+ * Idempotent: the underlying `persistShoppingCards` upserts on+ * `(prompt_result_id, position)` with `ignoreDuplicates: true`, so re-running+ * this script is safe and skips work that's already there.+ *+ * Brand info + competitors are loaded per brand (not per row) and reused+ * across every prompt_result that targets that brand — same data the+ * worker uses live; same matcher.+ */++import 'dotenv/config';+import supabaseAdmin from '../config/supabase.js';+import { persistShoppingCards } from '../lib/cloro-result-handler.js';++const DAYS = Number.parseInt(process.env.SHOPPING_BACKFILL_DAYS ?? '90', 10);+const BATCH = Number.parseInt(process.env.SHOPPING_BACKFILL_BATCH ?? '200', 10);++/**+ * @param {string} brandId+ * @returns {Promise<{ brandInfo: { brandId: string, brandName: string, domains: string[] }|null, competitors: Array<{ id: string, name: string, domain: string|null }> }>}+ */+async function loadBrandContext(brandId) {+ const [{ data: brand }, { data: domainRows }, { data: competitorRows }] = await Promise.all([+ supabaseAdmin.from('brands').select('id, name').eq('id', brandId).maybeSingle(),+ supabaseAdmin.from('brand_domains').select('domain').eq('brand_id', brandId),+ supabaseAdmin.from('competitors').select('id, name, domain').eq('brand_id', brandId),+ ]);++ if (!brand) return { brandInfo: null, competitors: [] };++ return {+ brandInfo: {+ brandId: brand.id,+ brandName: brand.name,+ domains: (domainRows ?? []).map((d) => d.domain).filter(Boolean),+ },+ competitors: (competitorRows ?? []).map((c) => ({+ id: c.id,+ name: c.name,+ domain: c.domain ?? null,+ })),+ };+}++async function main() {+ const cutoff = new Date(Date.now() - DAYS * 24 * 60 * 60 * 1000).toISOString();+ console.log(`[backfill] Walking prompt_results since ${cutoff} (${DAYS}d, batch=${BATCH})`);++ // Cache brand context across rows — vast majority of results share a+ // handful of brand_ids per run.+ const brandCache = new Map();++ let offset = 0;+ let totalRows = 0;+ let totalCards = 0;+ let totalSkipped = 0;++ while (true) {+ const { data: rows, error } = await supabaseAdmin+ .from('prompt_results')+ .select('id, brand_id, platform, region, shopping_cards')+ .gte('created_at', cutoff)+ .not('shopping_cards', 'is', null)+ .order('created_at', { ascending: true })+ .range(offset, offset + BATCH - 1);++ if (error) {+ console.error('[backfill] Failed to fetch prompt_results batch:', error.message);+ process.exit(1);+ }++ if (!rows || rows.length === 0) break;++ for (const row of rows) {+ totalRows += 1;+ const cards = Array.isArray(row.shopping_cards) ? row.shopping_cards : [];+ if (cards.length === 0) {+ totalSkipped += 1;+ continue;+ }++ let ctx = brandCache.get(row.brand_id);+ if (!ctx) {+ ctx = await loadBrandContext(row.brand_id);+ brandCache.set(row.brand_id, ctx);+ }+ if (!ctx.brandInfo) {+ // Brand row missing — orphaned result, skip rather than fail.+ totalSkipped += 1;+ continue;+ }++ const inserted = await persistShoppingCards({+ promptResultId: row.id,+ brandId: row.brand_id,+ platform: row.platform,+ region: row.region,+ rawCards: cards,+ brandInfo: ctx.brandInfo,+ competitors: ctx.competitors,+ });+ totalCards += inserted;+ }++ console.log(+ `[backfill] +${rows.length} rows (running: ${totalRows} rows, ${totalCards} cards, ${totalSkipped} skipped)`,+ );+ offset += rows.length;+ if (rows.length < BATCH) break;+ }++ console.log(+ `[backfill] Done. ${totalRows} prompt_results scanned, ${totalCards} cards normalized, ${totalSkipped} skipped.`,+ );+ process.exit(0);+}++main().catch((err) => {+ console.error('[backfill] Fatal:', err);+ process.exit(1);+});diff --git a/supabase/migrations/00011_prompt_result_shopping_cards.sql b/supabase/migrations/00011_prompt_result_shopping_cards.sqlnew file mode 100644index 000000000..6fefd4cd9--- /dev/null+++ b/supabase/migrations/00011_prompt_result_shopping_cards.sql@@ -0,0 +1,110 @@+-- Normalized shopping cards.+--+-- `prompt_results.shopping_cards` stores the raw provider JSON (snake_case+-- for Perplexity, camelCase for Google AI Mode and Microsoft Copilot).+-- That's fine for archival but useless for analytics — "show me cards+-- where a competitor's product appears alongside mine" today means+-- scanning every prompt_result and JSON-parsing in app code.+--+-- This table is one row per card per prompt_result with the fields we+-- query on hoisted to real columns + the original card preserved in+-- `raw` for forward-compat. Populated by the worker after the+-- prompt_results insert (see server/src/lib/cloro-result-handler.js)+-- and backfilled by server/src/scripts/backfill-shopping-cards.js.++create table if not exists public.prompt_result_shopping_cards (+ id uuid primary key default gen_random_uuid(),+ prompt_result_id uuid not null references public.prompt_results(id) on delete cascade,+ -- denormalized from prompt_results.brand_id so org-scoped queries don't+ -- have to join the parent row.+ brand_id uuid not null references public.brands(id) on delete cascade,+ -- Position within the provider's `shopping_cards` array (0-indexed).+ -- Combined with prompt_result_id, this is the natural identity of a card+ -- and the key the backfill script uses to stay idempotent.+ position integer not null,++ -- Hoisted analytical columns.+ product_title text,+ product_brand text,+ price_amount numeric,+ price_currency text,+ image_url text,+ merchant_url text,+ merchant_domain text,+ rating numeric,+ review_count integer,++ -- Original card JSON. Lets us re-parse if the schema evolves without+ -- needing another backfill from the provider.+ raw jsonb not null,++ -- Brand matching, computed at insert time.+ --+ -- role = 'own' → matched_brand_id points to brands.id (the tracked brand)+ -- role = 'competitor' → matched_brand_id points to competitors.id+ -- role = 'other' → matched_brand_id is null+ --+ -- Intentionally polymorphic (no FK) so a single column can express both+ -- relations. ON DELETE of the underlying row doesn't cascade — analytics+ -- on historical mentions stay intact even if the brand or competitor+ -- record is later removed.+ matched_brand_id uuid,+ matched_brand_role text not null default 'other'+ check (matched_brand_role in ('own', 'competitor', 'other')),++ -- Denormalized for fast "show me Copilot shopping cards in TR last week".+ platform text not null,+ region text,+ created_at timestamptz not null default now(),++ unique (prompt_result_id, position)+);++-- Indexes targeted at the Shopping dashboard's three top-level queries:+-- "show me competitor products" → (brand_id, matched_brand_role)+-- "rank product brands by mention count" → (product_brand)+-- "merchant domain leaderboard" → (merchant_domain)+create index if not exists prompt_result_shopping_cards_brand_role_idx+ on public.prompt_result_shopping_cards (brand_id, matched_brand_role);+create index if not exists prompt_result_shopping_cards_product_brand_idx+ on public.prompt_result_shopping_cards (product_brand);+create index if not exists prompt_result_shopping_cards_merchant_domain_idx+ on public.prompt_result_shopping_cards (merchant_domain);++alter table public.prompt_result_shopping_cards enable row level security;++-- RLS mirrors `prompt_results`: org members can read their org's cards,+-- service role inserts + deletes everything. The worker writes through+-- supabaseAdmin which bypasses RLS, but the explicit policy keeps the+-- table reachable from a future authenticated-write surface.+create policy "shopping_cards: org member select"+ on public.prompt_result_shopping_cards+ for select+ using (+ brand_id in (+ select b.id+ from public.brands b+ where b.organization_id in (+ select organization_id+ from public.profiles+ where id = auth.uid()+ )+ )+ );++create policy "Service role can insert shopping cards"+ on public.prompt_result_shopping_cards+ for insert+ with check (true);++create policy "Service role can delete shopping cards"+ on public.prompt_result_shopping_cards+ for delete+ using (true);++comment on table public.prompt_result_shopping_cards is+ 'One row per shopping card extracted from a prompt_result, normalized across providers. Source of truth for the Shopping dashboard and the MCP shopping tools.';+comment on column public.prompt_result_shopping_cards.matched_brand_id is+ 'Polymorphic uuid: brands.id when role=own, competitors.id when role=competitor, null when role=other. Intentionally no FK so deletes don''t orphan historical analytics.';+comment on column public.prompt_result_shopping_cards.raw is+ 'Original card JSON as the provider returned it. Kept for re-parsing if columns evolve.';