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(shopping): brand-level Shopping mode toggle + ChatGPT Shopping platform + Insights isolation (#155) (#157)

Gökhan Geyikd6fb84f637d4
diff --git a/server/src/lib/cloro-result-handler.js b/server/src/lib/cloro-result-handler.js
index 1560762d2..dc9c30cf2 100644
--- a/server/src/lib/cloro-result-handler.js
+++ b/server/src/lib/cloro-result-handler.js
@@ -63,6 +63,7 @@ export async function handleScraperResult({
region: region ?? null,
competitor_mentions: metrics.competitorMentions,
shopping_cards: aiResponse.shopping_cards ?? [],
+ inline_products: aiResponse.inline_products ?? [],
})
.select('id')
.single();
diff --git a/server/src/lib/cloro-scraper.js b/server/src/lib/cloro-scraper.js
index c31fd967e..73d59bfbd 100644
--- a/server/src/lib/cloro-scraper.js
+++ b/server/src/lib/cloro-scraper.js
@@ -11,6 +11,7 @@ const CLORO_API = 'https://api.cloro.dev';
const SCRAPER_TASK_TYPES = {
'chatgpt-web': 'CHATGPT',
+ 'chatgpt-shopping': 'CHATGPT',
'google-aio': 'GOOGLE',
'google-aimode': 'AIMODE',
'copilot-web': 'COPILOT',
@@ -31,6 +32,21 @@ function getApiKey() {
function buildRequestBody(promptText, scraperId, region) {
const country = region || 'US';
+ if (scraperId === 'chatgpt-shopping') {
+ // ChatGPT Shopping uses the same CHATGPT task but flips include.shopping.
+ // Cloro's response then includes `shoppingCards` and `inlineProducts`
+ // surfaced in the live ChatGPT shopping experience.
+ return {
+ prompt: promptText,
+ country,
+ include: {
+ html: false,
+ markdown: true,
+ shopping: true,
+ },
+ };
+ }
+
if (scraperId === 'google-aio') {
return {
query: promptText,
@@ -66,6 +82,29 @@ function buildRequestBody(promptText, scraperId, region) {
}
export function parseScraperResponse(result, scraperId) {
+ if (scraperId === 'chatgpt-shopping') {
+ // ChatGPT Shopping returns a normal ChatGPT response shape *plus*
+ // camelCase `shoppingCards` and `inlineProducts` payloads. Both arrays
+ // go on the prompt_results row raw — the Shopping page consumes them.
+ // Model is forced to the shopping-specific id so Insights aggregates
+ // (which exclude `platform = 'chatgpt-shopping'`) never mix this row
+ // into brand-level visibility numbers.
+ const text = result.markdown || result.text || '';
+ const citations = (result.sources || []).map((src, idx) => ({
+ url: src.url || '',
+ title: src.label || '',
+ startIndex: idx * 100,
+ endIndex: idx * 100 + 50,
+ }));
+ return {
+ text,
+ citations,
+ model: result.model || 'gpt-5-3-mini',
+ shopping_cards: result.shoppingCards ?? result.shopping_cards ?? [],
+ inline_products: result.inlineProducts ?? result.inline_products ?? [],
+ };
+ }
+
if (scraperId === 'google-aio') {
const aio = result.aioverview;
if (!aio) {
diff --git a/supabase/migrations/00012_shopping_mode.sql b/supabase/migrations/00012_shopping_mode.sql
new file mode 100644
index 000000000..f5ec9a15d
--- /dev/null
+++ b/supabase/migrations/00012_shopping_mode.sql
@@ -0,0 +1,400 @@
+-- #155 — Brand-level "Shopping mode" toggle + ChatGPT Shopping isolation
+--
+-- Two small additions on top of the existing schema, plus a refresh of the
+-- insights/visibility-trend RPCs so they exclude `platform = 'chatgpt-shopping'`
+-- from brand-level aggregations.
+--
+-- 1. `brands.shopping_mode_enabled` — bool, default false.
+-- Per-brand opt-in. Drives the Shopping sidebar entry's visibility (if
+-- any brand in the org has it on) and seeds new prompts under that brand
+-- with the chatgpt-shopping platform.
+--
+-- 2. `prompt_results.inline_products` — jsonb, default '[]'.
+-- Mirrors the existing `shopping_cards` column. ChatGPT Shopping's Cloro
+-- response returns both `shoppingCards` and `inlineProducts`; the cards go
+-- to the shared column, the inline products land here for the Shopping
+-- page to consume.
+--
+-- 3. RPC refresh — the three `*_aggregates` functions in
+-- `00006_insights_aggregates.sql` and `visibility_trend_aggregates` in
+-- `00008_visibility_trend_aggregates.sql` now exclude
+-- `platform = 'chatgpt-shopping'` rows. Reason: ChatGPT Shopping answers
+-- come from a different model (`gpt-5-3-mini`) — its visibility_score is
+-- not comparable to a normal ChatGPT text response, so mixing those rows
+-- into Insights would skew brand visibility/mentions/citations. Other
+-- providers' shopping cards are a side-payload of the same model's
+-- answer, so their rows stay in Insights.
+--
+-- The Shopping dashboard is the only surface that consumes
+-- `platform = 'chatgpt-shopping'` rows — it reads from the normalized
+-- `prompt_result_shopping_cards` table and is not affected.
+
+-- ── 1. brands.shopping_mode_enabled ───────────────────────────────────────
+ALTER TABLE public.brands
+ ADD COLUMN IF NOT EXISTS shopping_mode_enabled boolean NOT NULL DEFAULT false;
+
+
+-- ── 2. prompt_results.inline_products ─────────────────────────────────────
+ALTER TABLE public.prompt_results
+ ADD COLUMN IF NOT EXISTS inline_products jsonb NOT NULL DEFAULT '[]'::jsonb;
+
+
+-- ── 3. RPC refresh — exclude chatgpt-shopping from Insights aggregates ────
+--
+-- All four functions are `CREATE OR REPLACE` so this re-runs cleanly.
+-- The only change in each is the new `AND pr.platform <> 'chatgpt-shopping'`
+-- predicate inside the `filtered` CTE.
+
+CREATE OR REPLACE FUNCTION public.insights_aggregates(
+ p_brand_id uuid,
+ p_platform text DEFAULT NULL,
+ p_models text[] DEFAULT NULL,
+ p_region text DEFAULT NULL,
+ p_date_from timestamptz DEFAULT NULL,
+ p_date_to timestamptz DEFAULT NULL,
+ p_prompt_id uuid DEFAULT NULL,
+ p_topic_id uuid DEFAULT NULL
+)
+RETURNS jsonb
+LANGUAGE sql
+STABLE
+SECURITY DEFINER
+SET search_path = public
+AS $$
+ WITH filtered AS (
+ SELECT pr.visibility_score, pr.mention_count, pr.citation_count,
+ pr.sentiment, pr.model_used, pr.created_at
+ FROM public.prompt_results pr
+ WHERE pr.brand_id = p_brand_id
+ AND pr.platform <> 'chatgpt-shopping' -- #155 — isolate from Insights
+ AND (p_platform IS NULL OR pr.platform = p_platform)
+ AND (p_models IS NULL OR pr.model_used = ANY (p_models))
+ AND (p_region IS NULL OR pr.region = p_region)
+ AND (p_date_from IS NULL OR pr.created_at >= p_date_from)
+ AND (p_date_to IS NULL OR pr.created_at <= p_date_to)
+ AND (p_prompt_id IS NULL OR pr.prompt_id = p_prompt_id)
+ AND (p_topic_id IS NULL OR EXISTS (
+ SELECT 1 FROM public.prompts p
+ WHERE p.id = pr.prompt_id AND p.topic_id = p_topic_id))
+ ),
+ totals AS (
+ SELECT
+ COUNT(*) AS total_results,
+ COALESCE(SUM(visibility_score), 0) AS sum_visibility,
+ COALESCE(SUM(mention_count), 0) AS total_mentions,
+ COALESCE(SUM(citation_count), 0) AS total_citations,
+ COUNT(*) FILTER (WHERE sentiment = 'positive') AS positive_count,
+ MAX(created_at) AS last_checked_at
+ FROM filtered
+ ),
+ by_model AS (
+ SELECT
+ COALESCE(model_used, 'unknown') AS model_used,
+ SUM(visibility_score) AS sum_visibility,
+ COUNT(*) AS result_count
+ FROM filtered
+ GROUP BY COALESCE(model_used, 'unknown')
+ )
+ SELECT jsonb_build_object(
+ 'total_results', t.total_results,
+ 'sum_visibility', t.sum_visibility,
+ 'total_mentions', t.total_mentions,
+ 'total_citations', t.total_citations,
+ 'positive_count', t.positive_count,
+ 'last_checked_at', t.last_checked_at,
+ 'by_model', COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'model_used', bm.model_used,
+ 'sum_visibility', bm.sum_visibility,
+ 'result_count', bm.result_count)
+ ORDER BY bm.result_count DESC, bm.model_used)
+ FROM by_model bm),
+ '[]'::jsonb)
+ )
+ FROM totals t;
+$$;
+
+
+CREATE OR REPLACE FUNCTION public.competitor_aggregates(
+ p_brand_id uuid,
+ p_platform text DEFAULT NULL,
+ p_models text[] DEFAULT NULL,
+ p_region text DEFAULT NULL,
+ p_date_from timestamptz DEFAULT NULL,
+ p_date_to timestamptz DEFAULT NULL,
+ p_prompt_id uuid DEFAULT NULL,
+ p_topic_id uuid DEFAULT NULL
+)
+RETURNS jsonb
+LANGUAGE sql
+STABLE
+SECURITY DEFINER
+SET search_path = public
+AS $$
+ WITH filtered AS (
+ SELECT pr.visibility_score, pr.mention_count, pr.citation_count,
+ pr.model_used, pr.platform, pr.competitor_mentions
+ FROM public.prompt_results pr
+ WHERE pr.brand_id = p_brand_id
+ AND pr.platform <> 'chatgpt-shopping' -- #155 — isolate from Insights
+ AND (p_platform IS NULL OR pr.platform = p_platform)
+ AND (p_models IS NULL OR pr.model_used = ANY (p_models))
+ AND (p_region IS NULL OR pr.region = p_region)
+ AND (p_date_from IS NULL OR pr.created_at >= p_date_from)
+ AND (p_date_to IS NULL OR pr.created_at <= p_date_to)
+ AND (p_prompt_id IS NULL OR pr.prompt_id = p_prompt_id)
+ AND (p_topic_id IS NULL OR EXISTS (
+ SELECT 1 FROM public.prompts p
+ WHERE p.id = pr.prompt_id AND p.topic_id = p_topic_id))
+ ),
+ brand_totals AS (
+ SELECT
+ COUNT(*) AS row_count,
+ COALESCE(SUM(visibility_score), 0) AS sum_visibility,
+ COALESCE(SUM(mention_count), 0)::bigint AS total_mentions,
+ COALESCE(SUM(citation_count), 0)::bigint AS total_citations
+ FROM filtered
+ ),
+ by_brand_provider AS (
+ SELECT
+ model_used,
+ platform,
+ SUM(visibility_score) AS sum_visibility,
+ COUNT(*) AS row_count
+ FROM filtered
+ GROUP BY model_used, platform
+ ),
+ mentions_flat AS (
+ SELECT
+ f.model_used,
+ f.platform,
+ cm.value->>'competitor_id' AS competitor_id,
+ cm.value->>'name' AS competitor_name,
+ (cm.value->>'visibility_score')::numeric AS cm_visibility,
+ COALESCE((cm.value->>'mention_count')::int, 0) AS cm_mention_count,
+ COALESCE((cm.value->>'citation_count')::int, 0) AS cm_citation_count
+ FROM filtered f,
+ LATERAL jsonb_array_elements(
+ COALESCE(f.competitor_mentions, '[]'::jsonb)) cm
+ WHERE cm.value ? 'competitor_id'
+ ),
+ by_competitor AS (
+ SELECT
+ competitor_id,
+ MAX(competitor_name) AS name,
+ SUM(cm_visibility) AS sum_visibility,
+ COUNT(*) AS row_count,
+ SUM(cm_mention_count)::bigint AS total_mentions,
+ SUM(cm_citation_count)::bigint AS total_citations
+ FROM mentions_flat
+ GROUP BY competitor_id
+ ),
+ by_competitor_provider AS (
+ SELECT
+ model_used,
+ platform,
+ competitor_id,
+ MAX(competitor_name) AS competitor_name,
+ SUM(cm_visibility) AS sum_visibility,
+ COUNT(*) AS row_count
+ FROM mentions_flat
+ GROUP BY model_used, platform, competitor_id
+ )
+ SELECT jsonb_build_object(
+ 'brand_row_count', b.row_count,
+ 'brand_sum_visibility', b.sum_visibility,
+ 'brand_total_mentions', b.total_mentions,
+ 'brand_total_citations', b.total_citations,
+ 'by_competitor', COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'competitor_id', bc.competitor_id,
+ 'name', bc.name,
+ 'sum_visibility', bc.sum_visibility,
+ 'row_count', bc.row_count,
+ 'total_mentions', bc.total_mentions,
+ 'total_citations', bc.total_citations)
+ ORDER BY bc.row_count DESC, bc.competitor_id)
+ FROM by_competitor bc),
+ '[]'::jsonb),
+ 'by_brand_provider', COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'model_used', bbp.model_used,
+ 'platform', bbp.platform,
+ 'sum_visibility', bbp.sum_visibility,
+ 'row_count', bbp.row_count)
+ ORDER BY bbp.platform NULLS LAST, bbp.model_used NULLS LAST)
+ FROM by_brand_provider bbp),
+ '[]'::jsonb),
+ 'by_competitor_provider', COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'model_used', bcp.model_used,
+ 'platform', bcp.platform,
+ 'competitor_id', bcp.competitor_id,
+ 'competitor_name', bcp.competitor_name,
+ 'sum_visibility', bcp.sum_visibility,
+ 'row_count', bcp.row_count)
+ ORDER BY bcp.platform NULLS LAST, bcp.model_used NULLS LAST, bcp.competitor_id)
+ FROM by_competitor_provider bcp),
+ '[]'::jsonb)
+ )
+ FROM brand_totals b;
+$$;
+
+
+CREATE OR REPLACE FUNCTION public.visibility_trend_aggregates(
+ p_brand_id uuid,
+ p_models text[] DEFAULT NULL,
+ p_region text DEFAULT NULL,
+ p_date_from timestamptz DEFAULT NULL,
+ p_date_to timestamptz DEFAULT NULL,
+ p_topic_id uuid DEFAULT NULL,
+ p_granularity text DEFAULT 'day'
+)
+RETURNS jsonb
+LANGUAGE sql
+STABLE
+SECURITY DEFINER
+SET search_path = public
+AS $$
+ WITH filtered AS (
+ SELECT pr.visibility_score, pr.mention_count, pr.citation_count,
+ pr.created_at, pr.competitor_mentions
+ FROM public.prompt_results pr
+ WHERE pr.brand_id = p_brand_id
+ AND pr.platform <> 'chatgpt-shopping' -- #155 — isolate from Insights
+ AND (p_models IS NULL OR pr.model_used = ANY (p_models))
+ AND (p_region IS NULL OR pr.region = p_region)
+ AND (p_date_from IS NULL OR pr.created_at >= p_date_from)
+ AND (p_date_to IS NULL OR pr.created_at <= p_date_to)
+ AND (p_topic_id IS NULL OR EXISTS (
+ SELECT 1 FROM public.prompts p
+ WHERE p.id = pr.prompt_id AND p.topic_id = p_topic_id))
+ ),
+ buckets AS (
+ SELECT
+ to_char(
+ date_trunc(p_granularity, created_at AT TIME ZONE 'UTC'),
+ 'YYYY-MM-DD'
+ ) AS bucket_date,
+ COUNT(*) AS row_count,
+ COALESCE(SUM(visibility_score), 0) AS sum_visibility,
+ COALESCE(SUM(mention_count), 0)::bigint AS sum_mentions,
+ COALESCE(SUM(citation_count), 0)::bigint AS sum_citations,
+ COALESCE(SUM((
+ SELECT COALESCE(SUM((cm.value->>'visibility_score')::numeric), 0)
+ FROM jsonb_array_elements(COALESCE(competitor_mentions, '[]'::jsonb)) cm
+ )), 0) AS comp_sum_visibility,
+ COALESCE(SUM((
+ SELECT COUNT(*)
+ FROM jsonb_array_elements(COALESCE(competitor_mentions, '[]'::jsonb)) cm
+ )), 0)::bigint AS comp_count
+ FROM filtered
+ GROUP BY to_char(
+ date_trunc(p_granularity, created_at AT TIME ZONE 'UTC'),
+ 'YYYY-MM-DD'
+ )
+ )
+ SELECT COALESCE(
+ (SELECT jsonb_agg(
+ jsonb_build_object(
+ 'bucket_date', b.bucket_date,
+ 'row_count', b.row_count,
+ 'sum_visibility', b.sum_visibility,
+ 'sum_mentions', b.sum_mentions,
+ 'sum_citations', b.sum_citations,
+ 'comp_sum_visibility', b.comp_sum_visibility,
+ 'comp_count', b.comp_count
+ )
+ ORDER BY b.bucket_date)
+ FROM buckets b),
+ '[]'::jsonb);
+$$;
+
+
+CREATE OR REPLACE FUNCTION public.share_of_voice_aggregates(
+ p_brand_id uuid,
+ p_platform text DEFAULT NULL,
+ p_models text[] DEFAULT NULL,
+ p_region text DEFAULT NULL,
+ p_date_from timestamptz DEFAULT NULL,
+ p_date_to timestamptz DEFAULT NULL,
+ p_prompt_id uuid DEFAULT NULL,
+ p_topic_id uuid DEFAULT NULL
+)
+RETURNS jsonb
+LANGUAGE sql
+STABLE
+SECURITY DEFINER
+SET search_path = public
+AS $$
+ WITH filtered AS (
+ SELECT
+ pr.mention_count,
+ pr.model_used,
+ pr.platform,
+ pr.created_at,
+ pr.competitor_mentions,
+ COALESCE((
+ SELECT SUM((cm.value->>'mention_count')::int)
+ FROM jsonb_array_elements(
+ COALESCE(pr.competitor_mentions, '[]'::jsonb)) cm
+ ), 0)::int AS row_competitor_mentions
+ FROM public.prompt_results pr
+ WHERE pr.brand_id = p_brand_id
+ AND pr.platform <> 'chatgpt-shopping' -- #155 — isolate from Insights
+ AND (p_platform IS NULL OR pr.platform = p_platform)
+ AND (p_models IS NULL OR pr.model_used = ANY (p_models))
+ AND (p_region IS NULL OR pr.region = p_region)
+ AND (p_date_from IS NULL OR pr.created_at >= p_date_from)
+ AND (p_date_to IS NULL OR pr.created_at <= p_date_to)
+ AND (p_prompt_id IS NULL OR pr.prompt_id = p_prompt_id)
+ AND (p_topic_id IS NULL OR EXISTS (
+ SELECT 1 FROM public.prompts p
+ WHERE p.id = pr.prompt_id AND p.topic_id = p_topic_id))
+ ),
+ totals AS (
+ SELECT
+ COALESCE(SUM(mention_count), 0)::bigint AS total_brand_mentions,
+ COALESCE(SUM(row_competitor_mentions), 0)::bigint AS total_competitor_mentions
+ FROM filtered
+ ),
+ by_platform AS (
+ SELECT
+ model_used,
+ platform,
+ COALESCE(SUM(mention_count), 0)::bigint AS brand_mentions,
+ COALESCE(SUM(row_competitor_mentions), 0)::bigint AS competitor_mentions
+ FROM filtered
+ GROUP BY model_used, platform
+ ),
+ by_day AS (
+ SELECT
+ to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS day,
+ COALESCE(SUM(mention_count), 0)::bigint AS brand_mentions,
+ COALESCE(SUM(row_competitor_mentions), 0)::bigint AS competitor_mentions
+ FROM filtered
+ GROUP BY to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD')
+ )
+ SELECT jsonb_build_object(
+ 'total_brand_mentions', t.total_brand_mentions,
+ 'total_competitor_mentions', t.total_competitor_mentions,
+ 'by_platform', COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'model_used', bp.model_used,
+ 'platform', bp.platform,
+ 'brand_mentions', bp.brand_mentions,
+ 'competitor_mentions', bp.competitor_mentions)
+ ORDER BY bp.platform NULLS LAST, bp.model_used NULLS LAST)
+ FROM by_platform bp),
+ '[]'::jsonb),
+ 'by_day', COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'day', bd.day,
+ 'brand_mentions', bd.brand_mentions,
+ 'competitor_mentions', bd.competitor_mentions)
+ ORDER BY bd.day)
+ FROM by_day bd),
+ '[]'::jsonb)
+ )
+ FROM totals t;
+$$;
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.tsx
index 219f543c0..92de88b5b 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/page.tsx
@@ -4,7 +4,7 @@ import { use, useState, useEffect, useCallback } from 'react';
import { useTranslations } from 'next-intl';
import { useRouter, Link } from '@/i18n/navigation';
import { useBrandStore } from '@/stores/use-brand-store';
-import { updateBrand, deleteBrand } from '@/lib/actions/brand';
+import { updateBrand, deleteBrand, setBrandShoppingMode } from '@/lib/actions/brand';
import { syncDomains } from '@/lib/actions/brand-domain';
import { getCompetitors, addCompetitor, deleteCompetitor } from '@/lib/actions/competitor';
import { getFaviconUrl } from '@/lib/favicon';
@@ -26,7 +26,21 @@ import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { toast } from 'sonner';
-import { Check, Code, Copy, Globe, Loader2, Pencil, Plus, Save, Trash2, X } from 'lucide-react';
+import {
+ Check,
+ Code,
+ Copy,
+ Globe,
+ Loader2,
+ Pencil,
+ Plus,
+ Save,
+ ShoppingBag,
+ Trash2,
+ X,
+} from 'lucide-react';
+import { Checkbox } from '@/components/ui/checkbox';
+import { useUserRole } from '@/hooks/use-user-role';
import {
Dialog,
DialogContent,
@@ -78,8 +92,12 @@ export default function BrandSettingsPage({ params }: PageProps) {
</TabsTrigger>
</TabsList>
- <TabsContent value="general">
+ <TabsContent value="general" className="space-y-6">
<GeneralTab brand={brand} onUpdate={(updated) => updateBrandStore(brand.id, updated)} />
+ <ShoppingModeCard
+ brand={brand}
+ onUpdate={(updated) => updateBrandStore(brand.id, updated)}
+ />
</TabsContent>
<TabsContent value="domains">
@@ -201,6 +219,81 @@ function GeneralTab({
);
}
+// ─── Shopping mode (#155) ────────────────────────────────────────────────────
+
+function ShoppingModeCard({
+ brand,
+ onUpdate,
+}: {
+ brand: Brand;
+ onUpdate: (updates: Partial<Brand>) => void;
+}) {
+ const { canAdmin } = useUserRole();
+ const [enabled, setEnabled] = useState(brand.shoppingModeEnabled);
+ const [saving, setSaving] = useState(false);
+
+ async function handleToggle(next: boolean) {
+ if (!canAdmin) return;
+ const previous = enabled;
+ setEnabled(next);
+ setSaving(true);
+ try {
+ const { promptsUpdated } = await setBrandShoppingMode(brand.id, next);
+ onUpdate({ shoppingModeEnabled: next });
+ if (next && promptsUpdated > 0) {
+ toast.success(`Shopping mode on — ${promptsUpdated} prompt(s) updated`);
+ } else {
+ toast.success(next ? 'Shopping mode on' : 'Shopping mode off');
+ }
+ } catch (err) {
+ setEnabled(previous);
+ toast.error(err instanceof Error ? err.message : 'Failed to save');
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ <ShoppingBag className="h-4 w-4" />
+ Shopping mode
+ </CardTitle>
+ <CardDescription>
+ Turn this on if this brand is in e-commerce. We&rsquo;ll add ChatGPT Shopping to every
+ prompt under this brand and reveal the Shopping dashboard.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="flex items-start gap-3">
+ <Checkbox
+ id="shopping-mode"
+ checked={enabled}
+ disabled={saving || !canAdmin}
+ onCheckedChange={(v) => handleToggle(v === true)}
+ />
+ <div className="space-y-1">
+ <Label htmlFor="shopping-mode" className="font-medium">
+ This brand is in e-commerce / shopping
+ </Label>
+ <p className="text-xs text-muted-foreground">
+ Adds{' '}
+ <code className="rounded bg-muted px-1 py-0.5 text-[11px]">chatgpt-shopping</code> to
+ every existing prompt&apos;s platform list and enables the Shopping platform on this
+ brand.
+ </p>
+ {!canAdmin && (
+ <p className="text-xs text-muted-foreground">Only admins can change this setting.</p>
+ )}
+ </div>
+ {saving && <Loader2 className="ml-auto h-4 w-4 animate-spin text-muted-foreground" />}
+ </div>
+ </CardContent>
+ </Card>
+ );
+}
+
// ─── Domains Tab ──────────────────────────────────────────────────────────────
function DomainsTab({
diff --git a/web/src/app/[locale]/(dashboard)/layout.tsx b/web/src/app/[locale]/(dashboard)/layout.tsx
index f786dca98..3da90bf34 100644
--- a/web/src/app/[locale]/(dashboard)/layout.tsx
+++ b/web/src/app/[locale]/(dashboard)/layout.tsx
@@ -51,12 +51,16 @@ export default async function DashboardLayout({ children }: { children: React.Re
}
const planId = (org?.plan ?? 'starter') as PlanId;
+ // Sidebar reveals the Shopping entry when at least one brand has Shopping
+ // mode on (#155). Org-wide signal, derived from the brand list we already
+ // fetch here.
+ const shoppingModeEnabled = brands.some((b) => b.shoppingModeEnabled);
return (
<>
<AuthProvider user={user} />
<BrandLoader brands={brands} />
- <PlanProvider planId={planId}>
+ <PlanProvider planId={planId} shoppingModeEnabled={shoppingModeEnabled}>
<RoleProvider role={role}>
<div className="flex h-screen overflow-hidden">
{/* Desktop sidebar */}
diff --git a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx
index 642dc2747..7c89a3cd2 100644
--- a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx
+++ b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx
@@ -390,6 +390,7 @@ export default function OnboardingPage() {
description: b.description ?? undefined,
region: b.region ?? undefined,
language: b.language ?? undefined,
+ shoppingModeEnabled: !!b.shopping_mode_enabled,
domains: (b.brand_domains || []).map((d: Record<string, unknown>) => ({
id: d.id as string,
brandId: d.brand_id as string,
diff --git a/web/src/components/layout/sidebar.tsx b/web/src/components/layout/sidebar.tsx
index c74d2dc67..13f64f424 100644
--- a/web/src/components/layout/sidebar.tsx
+++ b/web/src/components/layout/sidebar.tsx
@@ -8,6 +8,7 @@ import { usePathname, Link } from '@/i18n/navigation';
import { dashboardNav } from '@/config/dashboard';
import { useSidebarStore } from '@/stores/use-sidebar-store';
import { useFeatureGate } from '@/hooks/use-feature-gate';
+import { usePlanContext } from '@/components/providers/plan-provider';
import { siteConfig } from '@/config/site';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
@@ -24,6 +25,11 @@ export function Sidebar() {
const t = useTranslations('nav');
const tBrands = useTranslations('brands');
const { canUse, requiredPlanFor, isCloud } = useFeatureGate();
+ const { shoppingModeEnabled } = usePlanContext();
+ // Map from a NavItem.requiresOrgPref key to its current value. Sidebar
+ // hides the item entirely when this returns false — see #155 for why
+ // Shopping uses this on top of the existing plan-feature gate.
+ const orgPrefs = { shoppingModeEnabled };
const { resolvedTheme } = useTheme();
const [mounted, setMounted] = useState(false);
// Hydration guard: SSR can't know the resolved theme, so we render the
@@ -94,6 +100,13 @@ export function Sidebar() {
{group.title && isCollapsed && i > 0 && <Separator className="my-2" />}
<nav className="space-y-0.5">
{group.items.map((item) => {
+ // Hide entirely if a required org preference is off — the
+ // user shouldn't see "Shopping (upgrade)" when they're
+ // simply not in e-commerce.
+ if (item.requiresOrgPref && !orgPrefs[item.requiresOrgPref]) {
+ return null;
+ }
+
const isActive =
item.href === '/dashboard'
? pathname === '/dashboard'
diff --git a/web/src/components/providers/plan-provider.tsx b/web/src/components/providers/plan-provider.tsx
index 5cea25843..dc904bd67 100644
--- a/web/src/components/providers/plan-provider.tsx
+++ b/web/src/components/providers/plan-provider.tsx
@@ -6,19 +6,29 @@ import type { PlanId } from '@/config/plans';
interface PlanContextValue {
planId: PlanId;
isCloud: boolean;
+ shoppingModeEnabled: boolean;
}
const PlanContext = createContext<PlanContextValue>({
planId: 'self_hosted',
isCloud: false,
+ shoppingModeEnabled: false,
});
-export function PlanProvider({ planId, children }: { planId: PlanId; children: React.ReactNode }) {
+export function PlanProvider({
+ planId,
+ shoppingModeEnabled,
+ children,
+}: {
+ planId: PlanId;
+ shoppingModeEnabled: boolean;
+ children: React.ReactNode;
+}) {
const isCloud = process.env.NEXT_PUBLIC_IS_CLOUD === 'true';
const effectivePlan: PlanId = isCloud ? planId : 'self_hosted';
return (
- <PlanContext.Provider value={{ planId: effectivePlan, isCloud }}>
+ <PlanContext.Provider value={{ planId: effectivePlan, isCloud, shoppingModeEnabled }}>
{children}
</PlanContext.Provider>
);
diff --git a/web/src/config/dashboard.ts b/web/src/config/dashboard.ts
index 42eb994af..b49babfbb 100644
--- a/web/src/config/dashboard.ts
+++ b/web/src/config/dashboard.ts
@@ -13,6 +13,16 @@ import {
} from 'lucide-react';
import type { Feature } from '@/config/plans';
+/**
+ * An org-level preference that, when present on a NavItem, must be `true`
+ * for the item to render at all. Distinct from plan-level `requiredFeature`
+ * which downgrades the item to a locked/disabled state when the plan
+ * doesn't include it — `requiresOrgPref` hides the item entirely so it
+ * doesn't appear as a "you could have this if you paid more" hint when the
+ * relevant org isn't supposed to see Shopping in the first place.
+ */
+export type OrgPrefKey = 'shoppingModeEnabled';
+
export interface NavItem {
title: string;
href: string;
@@ -20,6 +30,7 @@ export interface NavItem {
badge?: string;
disabled?: boolean;
requiredFeature?: Feature;
+ requiresOrgPref?: OrgPrefKey;
}
export interface NavGroup {
@@ -72,6 +83,7 @@ export const dashboardNav: NavGroup[] = [
href: '/dashboard/shopping',
icon: ShoppingBag,
requiredFeature: 'shopping_analytics',
+ requiresOrgPref: 'shoppingModeEnabled',
},
{
title: 'AI Traffic Analytics',
diff --git a/web/src/config/prompt-options.ts b/web/src/config/prompt-options.ts
index 91a547676..ad09eddc5 100644
--- a/web/src/config/prompt-options.ts
+++ b/web/src/config/prompt-options.ts
@@ -55,6 +55,7 @@ export const SCRAPER_GROUPS = [
provider: 'Cloro',
scrapers: [
{ id: 'chatgpt-web', label: 'ChatGPT (Web)', platform: 'chatgpt' },
+ { id: 'chatgpt-shopping', label: 'ChatGPT Shopping', platform: 'chatgpt-shopping' },
{ id: 'google-aio', label: 'Google AI Overview', platform: 'google-ai-overviews' },
{ id: 'google-aimode', label: 'Google AI Mode', platform: 'google-ai-mode' },
{ id: 'copilot-web', label: 'Microsoft Copilot', platform: 'copilot' },
diff --git a/web/src/lib/actions/brand.ts b/web/src/lib/actions/brand.ts
index 1a0c29f10..7d6341a1d 100644
--- a/web/src/lib/actions/brand.ts
+++ b/web/src/lib/actions/brand.ts
@@ -37,6 +37,7 @@ function mapBrandRow(brand: Record<string, unknown>, domains: Record<string, unk
region: (brand.region as string | null) ?? undefined,
language: (brand.language as string | null) ?? undefined,
trackingCode: (brand.tracking_code as string | null) ?? undefined,
+ shoppingModeEnabled: !!brand.shopping_mode_enabled,
domains: domains.map(mapDomainRow),
createdAt: brand.created_at as string,
updatedAt: brand.updated_at as string,
@@ -183,6 +184,85 @@ export async function deleteBrand(id: string): Promise<void> {
revalidatePath('/dashboard/brands');
}
+/**
+ * Toggle a brand's Shopping mode (#155).
+ *
+ * On `true`:
+ * - Set `brands.shopping_mode_enabled = true`
+ * - Add `chatgpt-shopping` to every prompt's `platforms` array (deduped)
+ * - Insert the `chatgpt-shopping` row into `brand_platforms` (idempotent)
+ * so the next tracking cycle picks it up alongside the prompt change.
+ *
+ * On `false`:
+ * - Set `brands.shopping_mode_enabled = false`
+ * - Leave existing prompt platforms and `brand_platforms` rows in place
+ * — historical opt-ins stay queryable, and any further per-prompt
+ * surgery is the operator's call.
+ */
+export async function setBrandShoppingMode(
+ brandId: string,
+ enabled: boolean,
+): Promise<{ promptsUpdated: number }> {
+ const supabase = await createClient();
+
+ // RLS gates this — the calling user must already have write access to
+ // the brand via their org membership.
+ const { error: updateErr } = await supabase
+ .from('brands')
+ .update({ shopping_mode_enabled: enabled })
+ .eq('id', brandId);
+ if (updateErr) throw new Error(updateErr.message);
+
+ let promptsUpdated = 0;
+
+ if (enabled) {
+ // Pull every prompt under this brand. Prompts hang off prompt_sets
+ // which hang off brands — one join via the !inner foreign key.
+ const { data: rows, error: readErr } = await supabase
+ .from('prompts')
+ .select('id, platforms, prompt_sets!inner(brand_id)')
+ .eq('prompt_sets.brand_id', brandId);
+ if (readErr) throw new Error(readErr.message);
+
+ const needsUpdate = (rows ?? []).filter((r) => {
+ const platforms = ((r as { platforms: string[] | null }).platforms ?? []) as string[];
+ return !platforms.includes('chatgpt-shopping');
+ });
+
+ for (const row of needsUpdate) {
+ const existing = ((row as { platforms: string[] | null }).platforms ?? []) as string[];
+ const next = [...existing, 'chatgpt-shopping'];
+ const { error: writeErr } = await supabase
+ .from('prompts')
+ .update({ platforms: next })
+ .eq('id', (row as { id: string }).id);
+ if (writeErr) {
+ // Best-effort: log and continue. If a few prompts fail to update
+ // (RLS oddity, race), the operator can toggle off+on or hit the
+ // per-prompt platforms picker. Don't half-roll-back the brand flag.
+ console.error('[shopping-mode] prompt update failed:', writeErr.message);
+ continue;
+ }
+ promptsUpdated += 1;
+ }
+
+ // Also surface chatgpt-shopping at the brand-platforms layer so the
+ // tracking worker actually fires the scraper. Idempotent.
+ const { error: bpErr } = await supabase
+ .from('brand_platforms')
+ .upsert(
+ { brand_id: brandId, platform: 'chatgpt-shopping', is_enabled: true },
+ { onConflict: 'brand_id,platform', ignoreDuplicates: true },
+ );
+ if (bpErr) {
+ console.error('[shopping-mode] brand_platforms upsert failed:', bpErr.message);
+ }
+ }
+
+ revalidatePath('/dashboard/brands');
+ return { promptsUpdated };
+}
+
export interface BrandCardSummary {
brandId: string;
visibility7d: number;
diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.ts
index 056aa4761..5b0fa5169 100644
--- a/web/src/lib/actions/prompt.ts
+++ b/web/src/lib/actions/prompt.ts
@@ -318,6 +318,19 @@ export async function addPromptToSet(input: AddPromptInput): Promise<Prompt> {
const topicId = await resolveTopicId(supabase, ps.brand_id as string, input.category);
+ // #155 — if the brand has Shopping mode on, every new prompt gets the
+ // chatgpt-shopping platform appended automatically so the user doesn't
+ // have to remember to flip it for each prompt. The caller's filtered
+ // platforms still take precedence; we just ensure inclusion.
+ const { data: brandRow } = await supabase
+ .from('brands')
+ .select('shopping_mode_enabled')
+ .eq('id', ps.brand_id as string)
+ .single();
+ const platforms = brandRow?.shopping_mode_enabled
+ ? Array.from(new Set([...filtered.platforms, 'chatgpt-shopping']))
+ : filtered.platforms;
+
const { data, error } = await supabase
.from('prompts')
.insert({
@@ -325,7 +338,7 @@ export async function addPromptToSet(input: AddPromptInput): Promise<Prompt> {
text: input.text,
category: input.category || null,
topic_id: topicId,
- platforms: filtered.platforms,
+ platforms,
regions: [brandRegion],
models: filtered.models,
is_active: true,
diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.ts
index 577af7d3b..3727e3e95 100644
--- a/web/src/lib/actions/tracking.ts
+++ b/web/src/lib/actions/tracking.ts
@@ -180,7 +180,15 @@ async function buildResultsQuery(
},
) {
const supabase = await createClient();
- let query = supabase.from('prompt_results').select('*').eq('brand_id', brandId);
+ // #155 — Insights aggregates exclude `chatgpt-shopping`. That model's
+ // visibility numbers aren't comparable to a normal ChatGPT answer and
+ // would skew brand-level visibility/mentions/citations. Shopping data
+ // is consumed by /dashboard/shopping only.
+ let query = supabase
+ .from('prompt_results')
+ .select('*')
+ .eq('brand_id', brandId)
+ .neq('platform', 'chatgpt-shopping');
if (opts?.platform) query = query.eq('platform', opts.platform);
query = applyModelFilter(query, opts?.model);
@@ -288,10 +296,14 @@ export async function getPromptResults(
export async function getPromptResultById(resultId: string): Promise<PromptResultWithText | null> {
const supabase = await createClient();
+ // #155 — Insights detail view; chatgpt-shopping is excluded here for the
+ // same reason the aggregates exclude it. Shopping rows are shown by the
+ // Shopping dashboard, not Insights.
const { data, error } = await supabase
.from('prompt_results')
.select('*')
.eq('id', resultId)
+ .neq('platform', 'chatgpt-shopping')
.single();
if (error || !data) return null;
@@ -368,10 +380,12 @@ export async function getPromptDetail(
topicName = prompt.category as string;
}
+ // #155 — same isolation rule as the other aggregating queries here.
const { data: resultRows, error: resultError } = await supabase
.from('prompt_results')
.select('*')
.eq('prompt_id', promptId)
+ .neq('platform', 'chatgpt-shopping')
.order('created_at', { ascending: false })
.limit(opts?.limit ?? 500);
@@ -710,10 +724,13 @@ export async function getPromptVisibilitySummaries(
const days = opts?.days ?? 30;
const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();
+ // #155 — visibility summary per prompt; exclude chatgpt-shopping to
+ // match the aggregate-RPC filters one level up.
const { data, error } = await supabase
.from('prompt_results')
.select('prompt_id, visibility_score, mention_count, created_at')
.eq('brand_id', brandId)
+ .neq('platform', 'chatgpt-shopping')
.gte('created_at', since);
if (error) throw new Error(error.message);
@@ -1217,10 +1234,14 @@ export async function getVisibilityTrend(
): Promise<VisibilityTrendPoint[]> {
const supabase = await createClient();
+ // #155 — visibility trend; exclude chatgpt-shopping to match the
+ // aggregate RPCs. (The RPC variant in 00012_shopping_mode.sql is what
+ // most callers hit; this JS path is used by the older codepath.)
let query = supabase
.from('prompt_results')
.select('created_at, visibility_score, competitor_mentions')
.eq('brand_id', brandId)
+ .neq('platform', 'chatgpt-shopping')
.order('created_at', { ascending: true });
query = applyModelFilter(query, opts?.model);
@@ -1345,10 +1366,13 @@ export async function getHeadToHeadComparison(
): Promise<HeadToHeadData> {
const supabase = await createClient();
+ // #155 — head-to-head comparisons are a Competitors-tab feature, which
+ // also lives under Insights — same isolation rule applies here.
const { data: results, error } = await supabase
.from('prompt_results')
.select('*')
.eq('brand_id', brandId)
+ .neq('platform', 'chatgpt-shopping')
.order('created_at', { ascending: false });
if (error) throw new Error(error.message);
diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.ts
index 18f5ed4cf..a08e82d37 100644
--- a/web/src/lib/mcp/data.ts
+++ b/web/src/lib/mcp/data.ts
@@ -83,12 +83,16 @@ export async function getVisibilitySummaryFor(
.maybeSingle();
if (!brand) return null;
+ // #155 — getVisibilitySummaryFor mirrors the insights_aggregates RPC and
+ // excludes chatgpt-shopping for the same reason: its model isn't
+ // comparable to a normal ChatGPT answer and would skew brand visibility.
let query = supabaseAdmin
.from('prompt_results')
.select(
'visibility_score, mention_count, citation_count, sentiment, model_used, competitor_mentions',
)
- .eq('brand_id', params.brandId);
+ .eq('brand_id', params.brandId)
+ .neq('platform', 'chatgpt-shopping');
if (params.dateFrom) query = query.gte('created_at', params.dateFrom);
const expandedDateTo = expandDateToEndOfDay(params.dateTo);
@@ -891,10 +895,13 @@ export async function listCitationsFor(
.filter(Boolean);
const classifyCtx = { brandDomains, competitorDomains };
+ // #155 — Citations summary is part of the Insights surface; chatgpt-shopping
+ // rows are isolated from these aggregations.
let query = supabaseAdmin
.from('prompt_results')
.select('id, prompt_id, platform, model_used, region, created_at, citations, citation_count')
- .eq('brand_id', params.brandId);
+ .eq('brand_id', params.brandId)
+ .neq('platform', 'chatgpt-shopping');
if (params.dateFrom) query = query.gte('created_at', params.dateFrom);
const expandedDateTo = expandDateToEndOfDay(params.dateTo);
diff --git a/web/src/types/index.ts b/web/src/types/index.ts
index 2b454110b..54ec48a1c 100644
--- a/web/src/types/index.ts
+++ b/web/src/types/index.ts
@@ -22,6 +22,7 @@ export interface Brand {
region?: string;
language?: string;
trackingCode?: string;
+ shoppingModeEnabled: boolean;
domains: BrandDomain[];
createdAt: string;
updatedAt: string;
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 53340abc5..56016ffd2 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -292,6 +292,7 @@ export type Database = {
name: string;
organization_id: string;
region: string | null;
+ shopping_mode_enabled: boolean;
slug: string;
tracking_code: string;
updated_at: string;
@@ -306,6 +307,7 @@ export type Database = {
name: string;
organization_id: string;
region?: string | null;
+ shopping_mode_enabled?: boolean;
slug: string;
tracking_code?: string;
updated_at?: string;
@@ -320,6 +322,7 @@ export type Database = {
name?: string;
organization_id?: string;
region?: string | null;
+ shopping_mode_enabled?: boolean;
slug?: string;
tracking_code?: string;
updated_at?: string;
@@ -651,6 +654,7 @@ export type Database = {
competitor_mentions: Json;
created_at: string;
id: string;
+ inline_products: Json;
mention_count: number;
model_used: string | null;
platform: string;
@@ -668,6 +672,7 @@ export type Database = {
competitor_mentions?: Json;
created_at?: string;
id?: string;
+ inline_products?: Json;
mention_count?: number;
model_used?: string | null;
platform: string;
@@ -685,6 +690,7 @@ export type Database = {
competitor_mentions?: Json;
created_at?: string;
id?: string;
+ inline_products?: Json;
mention_count?: number;
model_used?: string | null;
platform?: string;