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(onboarding): turn on Product Visibility for brands that sell online (#1213)
Cihan65e5643082fd
diff --git a/docs/guides/reports.mdx b/docs/guides/reports.mdxindex 30b1a031c..7d9458aa8 100644--- a/docs/guides/reports.mdx+++ b/docs/guides/reports.mdx@@ -25,10 +25,10 @@ Then set:- **Report title** — optional; a name for the library list.- **Brand** — the brand to snapshot.- **Date range** — `7d`, `30d`, `90d` presets or a custom from/to range.-- **Sections** — the full picker offers: KPIs, Trend, Share of Voice, Competitors, Topics, Prompts, Mention Evidence, Fan-out, AI Traffic, Shopping, Audit Score, Citations and Citation Evidence.+- **Sections** — the full picker offers: KPIs, Trend, Share of Voice, Competitors, Topics, Prompts, Mention Evidence, Fan-out, AI Traffic, Product Visibility, Audit Score, Citations and Citation Evidence.<Note>-The **Shopping** section only appears for brands with Shopping mode enabled. The AI executive summary is always included — it isn't a pickable section.+The **Product Visibility** section only appears for brands with Shopping mode enabled. The AI executive summary is always included — it isn't a pickable section.</Note>Generated reports land in the library list on the same page, newest first.diff --git a/server/src/routes/competitors.js b/server/src/routes/competitors.jsindex 2546544e6..6a9c941ae 100644--- a/server/src/routes/competitors.js+++ b/server/src/routes/competitors.js@@ -18,6 +18,13 @@ const competitorSchema = z.object({).min(3).max(10),+ // Optional: a verdict the model leaves out mustn't fail the competitors.+ isEcommerce: z+ .boolean()+ .optional()+ .describe(+ 'True only when the brand itself sells products shoppers buy online: an online store, a direct-to-consumer brand or a retailer, with product pages and a checkout. False for software, services, agencies, media, restaurants and B2B-only sellers.',+ ),});/** English country name for a region code ("TR" → "Turkey"), or null. */@@ -36,11 +43,13 @@ function countryName(region) {/*** POST /api/competitors/suggest* Body: { brandName, industry, description?, website?, region?, language? }- * Returns: { competitors: [{ name, domain }] }+ * Returns: { competitors: [{ name, domain }], isEcommerce }** Researches the brand with the model's web search, then structures the* results with generateObject. The website pins down which company the name- * means, and the region which market its competitors come from.+ * means, and the region which market its competitors come from. The same+ * look at the site says whether the brand sells products online+ * (isEcommerce), which setup uses to turn on Shopping mode.*/router.post('/suggest', async (req, res) => {try {@@ -62,7 +71,9 @@ Industry: ${industry || 'Not specified'}Description: ${description || 'Not specified'}Market: ${country || 'Not specified'}, language ${langName}-${website ? `First look up ${website} to understand exactly what "${brandName}" sells and to whom — the name alone may refer to other companies.\n\n` : ''}Then find REAL companies that compete directly with it — selling similar products/services to similar audiences ${market}. Prefer companies a customer ${market} would actually compare it with over global brands outside that market. For each competitor, provide the company name and their actual website domain.`;+${website ? `First look up ${website} to understand exactly what "${brandName}" sells and to whom — the name alone may refer to other companies.\n\n` : ''}Then find REAL companies that compete directly with it — selling similar products/services to similar audiences ${market}. Prefer companies a customer ${market} would actually compare it with over global brands outside that market. For each competitor, provide the company name and their actual website domain.++Finally, say whether "${brandName}" itself sells products that shoppers buy online, through an online store with product pages and a checkout.`;// #379 — retry the WHOLE two-phase flow: the schema's .min(3) means a// Phase-2 under-count throws NoObjectGeneratedError, and re-running the@@ -79,14 +90,14 @@ ${website ? `First look up ${website} to understand exactly what "${brandName}"return generateObject({model: resolveModel(competitorModel),schema: competitorSchema,- system: `Extract competitor information from the research below. Only include companies with REAL, verified domains. Return the root domain (e.g. "monday.com"), not full URLs. Do NOT include "${brandName}"${website ? ` (${website})` : ''} itself.`,+ system: `Extract competitor information from the research below. Only include companies with REAL, verified domains. Return the root domain (e.g. "monday.com"), not full URLs. Do NOT include "${brandName}"${website ? ` (${website})` : ''} itself. Set isEcommerce from what the research says "${brandName}" sells, and false when it doesn't say.`,prompt: research.text,});},{ attempts: 3, baseDelayMs: 500, label: 'competitor-suggest' },);- return res.json({ competitors: object.competitors });+ return res.json({ competitors: object.competitors, isEcommerce: object.isEcommerce === true });} catch (error) {req.log.error({ err: error }, 'competitor suggestion error');return res.status(500).json({diff --git a/server/src/routes/competitors.test.js b/server/src/routes/competitors.test.jsnew file mode 100644index 000000000..ce2e4507e--- /dev/null+++ b/server/src/routes/competitors.test.js@@ -0,0 +1,85 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * POST /api/competitors/suggest: the brand's competitors from a web search+ * of its site and market, and whether the brand itself sells products+ * online, which setup uses to turn on Shopping mode.+ */++const generateObject = vi.fn();+const webResearch = vi.fn();+vi.mock('ai', () => ({ generateObject }));+vi.mock('../lib/ai-provider.js', () => ({ resolveModel: vi.fn(() => 'model') }));+vi.mock('../lib/web-research.js', () => ({ webResearch }));+vi.mock('../lib/retry.js', () => ({ withRetry: (fn) => fn() }));++const { default: router } = await import('./competitors.js');++const competitors = [+ { name: 'Blue Bottle', domain: 'bluebottlecoffee.com' },+ { name: 'Trade', domain: 'drinktrade.com' },+ { name: 'Atlas Coffee Club', domain: 'atlascoffeeclub.com' },+];++let server;+let baseUrl;++beforeEach(async () => {+ vi.clearAllMocks();+ webResearch.mockResolvedValue({ text: 'research', searched: true, sources: 3 });+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => {+ req.log = { error: vi.fn(), info: vi.fn() };+ next();+ });+ app.use('/api/competitors', router);+ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}`;+});++afterEach(() => new Promise((resolve) => server.close(resolve)));++const suggest = (body) =>+ fetch(`${baseUrl}/api/competitors/suggest`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });++describe('POST /api/competitors/suggest', () => {+ it('returns the competitors and whether the brand sells online', async () => {+ generateObject.mockResolvedValue({ object: { competitors, isEcommerce: true } });+ const res = await suggest({+ brandName: 'Acme Coffee',+ website: 'acmecoffee.com',+ region: 'US',+ });+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ competitors, isEcommerce: true });++ // The research asks it, and the structuring step reads it from there.+ const [, researchPrompt] = webResearch.mock.calls[0];+ expect(researchPrompt).toContain(+ '"Acme Coffee" itself sells products that shoppers buy online',+ );+ // Optional, so an answer without it still structures the competitors.+ const { schema } = generateObject.mock.calls[0][0];+ expect(schema.safeParse({ competitors }).success).toBe(true);+ expect(schema.shape.isEcommerce.safeParse(true).success).toBe(true);+ });++ it('says no when the answer has no verdict', async () => {+ generateObject.mockResolvedValue({ object: { competitors } });+ const res = await suggest({ brandName: 'Acme Analytics' });+ expect(await res.json()).toEqual({ competitors, isEcommerce: false });+ });++ it('needs a brand name', async () => {+ expect((await suggest({})).status).toBe(400);+ expect(webResearch).not.toHaveBeenCalled();+ });+});diff --git a/web/messages/en.json b/web/messages/en.jsonindex 7fbf68f17..72b0b7afd 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -56,7 +56,7 @@"competitors": "Competitors","citations": "Citations","mentions": "Mentions",- "shopping": "Shopping",+ "shopping": "Product Visibility","reports": "Reports","settings": "Settings","analytics": "Analytics",@@ -4281,7 +4281,7 @@"noBrandDescription": "Select or create a brand to see the citations AI platforms use when answering about it."},"shopping": {- "title": "Shopping",+ "title": "Product Visibility","description": "Product cards AI engines surface — your products versus the competitive set.","kpiCardRate": "Shopping card rate","kpiCardRateSub": "Tracked prompts that returned ≥1 card",@@ -4389,7 +4389,7 @@"promptPerformance": "Prompts","queryFanout": "Fan-out","aiTraffic": "AI Traffic",- "shoppingVisibility": "Shopping",+ "shoppingVisibility": "Product Visibility","auditScore": "Audit Score","citations": "Citations","mentionEvidence": "Mention Evidence",@@ -4440,11 +4440,11 @@"aiTrafficNew": "new","aiTrafficLowSample": "Low sample","aiTrafficLowSampleHint": "Fewer than 30 visits in this period or the one before, so a % change would mislead.",- "shoppingVisibility": "Shopping Visibility",+ "shoppingVisibility": "Product Visibility","auditScore": "Site Audit Score","auditedOn": "Audited on","shopping": {- "sov": "Shopping SoV",+ "sov": "Product SoV","products": "Products Surfaced","cardRate": "Card Rate","topMerchant": "Top Merchant"@@ -4717,7 +4717,8 @@"created": "Brand created successfully!","back": "Back","next": "Next",- "finish": "Finish Setup"+ "finish": "Finish Setup",+ "ecommerceDetected": "{brand} looks like an online store, so we turned on Product Visibility: ChatGPT Shopping is tracked for your prompts on plans that include it. You can turn it off in brand settings."},"settings": {"title": "Brand Settings",@@ -4737,7 +4738,7 @@"deleteButton": "Delete Brand Permanently","shopping": {"title": "Shopping mode",- "description": "Turn this on if this brand is in e-commerce. We’ll add ChatGPT Shopping to every prompt under this brand and reveal the Shopping dashboard.",+ "description": "Turn this on if this brand is in e-commerce. We’ll add ChatGPT Shopping to every prompt under this brand and show Product Visibility in the menu.","label": "This brand is in e-commerce / shopping","help": "Adds <code>chatgpt-shopping</code> to every existing prompt's platform list and enables the Shopping platform on this brand.","managersOnly": "Only admins and managers can change this setting.",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsxindex c5f7a61a4..dc8ca011e 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsx@@ -3,7 +3,8 @@import { useState, useEffect, useRef } from 'react';import { useRouter } from '@/i18n/navigation';import { createClient } from '@/lib/supabase/client';-import { createBrand, updateBrand } from '@/lib/actions/brand';+import { createBrand, markBrandAsEcommerce, updateBrand } from '@/lib/actions/brand';+import { EcommerceNote } from '@/components/onboarding/ecommerce-note';import { syncDomains } from '@/lib/actions/brand-domain';import { createTopics } from '@/lib/actions/topic';import { getPromptCapacity, savePromptSet } from '@/lib/actions/prompt';@@ -288,6 +289,8 @@ export default function NewBrandPage() {const [suggestedCompetitors, setSuggestedCompetitors] = useState<CompetitorItem[]>([]);const [loadingCompetitors, setLoadingCompetitors] = useState(false);const [competitorSuggestError, setCompetitorSuggestError] = useState(false);+ const [ecommerceDetected, setEcommerceDetected] = useState(false);+ const ecommerceSetup = useRef<Promise<void> | null>(null);const [competitorName, setCompetitorName] = useState('');const [competitorDomain, setCompetitorDomain] = useState('');const [savingCompetitors, setSavingCompetitors] = useState(false);@@ -589,7 +592,7 @@ export default function NewBrandPage() {setLoadingCompetitors(true);setCompetitorSuggestError(false);try {- const { competitors } = await suggestCompetitors({+ const { competitors, isEcommerce } = await suggestCompetitors({brandName: brandName.trim(),description: description.trim(),website: domain,@@ -597,6 +600,8 @@ export default function NewBrandPage() {region,});setSuggestedCompetitors((prev) => mergeCompetitorSuggestions(prev, competitors));+ // Kept, so Finish waits for it: it updates the prompts one by one.+ if (isEcommerce) ecommerceSetup.current = turnOnProductVisibility();} catch (err) {console.error('Competitor suggestion error:', err);setCompetitorSuggestError(true);@@ -605,6 +610,22 @@ export default function NewBrandPage() {}};+ // The research found an online store: Shopping mode goes on, so Product+ // Visibility shows in the menu. Best effort: it can be turned on in the+ // brand's settings too.+ const turnOnProductVisibility = async () => {+ if (!createdBrand || createdBrand.shoppingModeEnabled) return;+ try {+ const { industry } = await markBrandAsEcommerce(createdBrand.id);+ const updates = { industry: industry ?? undefined, shoppingModeEnabled: true };+ setCreatedBrand({ ...createdBrand, ...updates });+ updateBrandInStore(createdBrand.id, updates);+ setEcommerceDetected(true);+ } catch (err) {+ console.error('E-commerce setup error:', err);+ }+ };+const toggleCompetitor = (index: number) => {setSuggestedCompetitors((prev) =>prev.map((c, i) => (i === index ? { ...c, selected: !c.selected } : c)),@@ -649,6 +670,9 @@ export default function NewBrandPage() {if (!createdBrand) return;setSavingCompetitors(true);try {+ // Shopping mode first, if it is still going on: the first run should+ // track ChatGPT Shopping on every prompt, not some of them.+ await ecommerceSetup.current;const selected = takePendingCompetitor().filter((c) => c.selected);if (selected.length > 0) {await Promise.all(@@ -1172,6 +1196,8 @@ export default function NewBrandPage() {</p></div>+ {ecommerceDetected && <EcommerceNote brandName={brandName.trim()} />}+{/* First, and outside the loading state: people arrive knowing theirrivals and should not have to wait for, or scroll past, ours. */}<div className="mb-6 space-y-2">diff --git a/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/_report-pdf.tsx b/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/_report-pdf.tsxindex d00c39f24..18fa5a3ac 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/_report-pdf.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/reports/[id]/_report-pdf.tsx@@ -578,13 +578,13 @@ export function ReportPdfDocument({ report }: { report: Report }) {</View>)}- {/* Shopping visibility */}+ {/* Product Visibility */}{payload.shoppingVisibility && (<View style={styles.section} wrap={false}>- <Text style={styles.sectionTitle}>Shopping Visibility</Text>+ <Text style={styles.sectionTitle}>Product Visibility</Text><View style={styles.kpiRow}><View style={styles.kpiBox}>- <Text style={styles.kpiLabel}>Shopping SoV</Text>+ <Text style={styles.kpiLabel}>Product SoV</Text><View style={styles.kpiValueRow}><Text style={styles.kpiValue}>{payload.shoppingVisibility.shoppingSovPct}%</Text><DeltaText value={payload.shoppingVisibility.sovChange} />diff --git a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsxindex 7e6b55d44..aaadeae3d 100644--- a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx+++ b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx@@ -3,7 +3,8 @@import { useState, useEffect, useRef } from 'react';import { useRouter } from '@/i18n/navigation';import { createClient } from '@/lib/supabase/client';-import { createBrand } from '@/lib/actions/brand';+import { createBrand, markBrandAsEcommerce } from '@/lib/actions/brand';+import { EcommerceNote } from '@/components/onboarding/ecommerce-note';import { createTopics, getTopics } from '@/lib/actions/topic';import { getPromptCapacity, savePromptSet } from '@/lib/actions/prompt';import { triggerTrackingCheck } from '@/lib/actions/tracking';@@ -262,7 +263,7 @@ const COMPETITOR_LOADING_MESSAGES = [export default function OnboardingPage() {const router = useRouter();- const { addBrand, setActiveBrand } = useBrandStore();+ const { addBrand, setActiveBrand, updateBrand: updateBrandInStore } = useBrandStore();const [step, setStep] = useState(1);const [isLoading, setIsLoading] = useState(false);@@ -328,6 +329,8 @@ export default function OnboardingPage() {const [suggestedCompetitors, setSuggestedCompetitors] = useState<CompetitorItem[]>([]);const [loadingCompetitors, setLoadingCompetitors] = useState(false);const [competitorSuggestError, setCompetitorSuggestError] = useState(false);+ const [ecommerceDetected, setEcommerceDetected] = useState(false);+ const ecommerceSetup = useRef<Promise<void> | null>(null);const [competitorName, setCompetitorName] = useState('');const [competitorDomain, setCompetitorDomain] = useState('');const [savingCompetitors, setSavingCompetitors] = useState(false);@@ -828,7 +831,7 @@ export default function OnboardingPage() {setLoadingCompetitors(true);setCompetitorSuggestError(false);try {- const { competitors } = await suggestCompetitors({+ const { competitors, isEcommerce } = await suggestCompetitors({brandName: brandName.trim(),description: description.trim(),website: domain,@@ -836,6 +839,8 @@ export default function OnboardingPage() {region,});setSuggestedCompetitors((prev) => mergeCompetitorSuggestions(prev, competitors));+ // Kept, so Finish waits for it: it updates the prompts one by one.+ if (isEcommerce) ecommerceSetup.current = turnOnProductVisibility();} catch (err) {console.error('Competitor suggestion error:', err);setCompetitorSuggestError(true);@@ -844,6 +849,23 @@ export default function OnboardingPage() {}};+ // The research found an online store: Shopping mode goes on, so Product+ // Visibility shows in the menu. Best effort: it can be turned on in the+ // brand's settings too.+ const turnOnProductVisibility = async () => {+ if (!createdBrand || createdBrand.shoppingModeEnabled) return;+ try {+ const { industry } = await markBrandAsEcommerce(createdBrand.id);+ const updates = { industry: industry ?? undefined, shoppingModeEnabled: true };+ setCreatedBrand({ ...createdBrand, ...updates });+ updateBrandInStore(createdBrand.id, updates);+ setEcommerceDetected(true);+ track('onboarding_ecommerce_detected');+ } catch (err) {+ console.error('E-commerce setup error:', err);+ }+ };+const toggleCompetitor = (index: number) => {setSuggestedCompetitors((prev) =>prev.map((c, i) => (i === index ? { ...c, selected: !c.selected } : c)),@@ -894,6 +916,9 @@ export default function OnboardingPage() {setSavingCompetitors(true);try {+ // Shopping mode first, if it is still going on: the first run should+ // track ChatGPT Shopping on every prompt, not some of them.+ await ecommerceSetup.current;// Save selected competitorsawait Promise.all(selected.map((c) => addCompetitor(createdBrand.id, { name: c.name, domain: c.domain })),@@ -1544,6 +1569,8 @@ export default function OnboardingPage() {</p></div>+ {ecommerceDetected && <EcommerceNote brandName={brandName.trim()} />}+{/* First, and outside the loading state: people arrive knowing theirrivals and should not have to wait for, or scroll past, ours. */}<div className="mb-6 space-y-2">diff --git a/web/src/components/onboarding/ecommerce-note.test.tsx b/web/src/components/onboarding/ecommerce-note.test.tsxnew file mode 100644index 000000000..d7653105c--- /dev/null+++ b/web/src/components/onboarding/ecommerce-note.test.tsx@@ -0,0 +1,29 @@+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { describe, expect, it } from 'vitest';+import messages from '../../../messages/en.json';+import { EcommerceNote } from './ecommerce-note';++/** The competitors step says why Product Visibility is on when setup found an online store. */++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++describe('EcommerceNote', () => {+ it('names the brand, what was turned on, and where to turn it off', async () => {+ const container = document.createElement('div');+ const root = createRoot(container);+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <EcommerceNote brandName="Acme Coffee" />+ </NextIntlClientProvider>,+ );+ });+ expect(container.textContent).toBe(+ 'Acme Coffee looks like an online store, so we turned on Product Visibility: ChatGPT Shopping is tracked for your prompts on plans that include it. You can turn it off in brand settings.',+ );+ act(() => root.unmount());+ });+});diff --git a/web/src/components/onboarding/ecommerce-note.tsx b/web/src/components/onboarding/ecommerce-note.tsxnew file mode 100644index 000000000..80bff6b4e--- /dev/null+++ b/web/src/components/onboarding/ecommerce-note.tsx@@ -0,0 +1,19 @@+'use client';++import { ShoppingBag } from 'lucide-react';+import { useTranslations } from 'next-intl';++/**+ * Said on the competitors step when setup found the brand sells online and+ * turned on Shopping mode, so Product Visibility appearing in the menu isn't+ * a surprise, with where to turn it off.+ */+export function EcommerceNote({ brandName }: { brandName: string }) {+ const t = useTranslations('brands.wizard');+ return (+ <div className="mb-6 flex items-start gap-3 rounded-md border bg-muted/40 p-3 text-sm">+ <ShoppingBag className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />+ <p className="text-muted-foreground">{t('ecommerceDetected', { brand: brandName })}</p>+ </div>+ );+}diff --git a/web/src/lib/actions/brand-ecommerce.test.ts b/web/src/lib/actions/brand-ecommerce.test.tsnew file mode 100644index 000000000..ec57fb7ae--- /dev/null+++ b/web/src/lib/actions/brand-ecommerce.test.ts@@ -0,0 +1,112 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * markBrandAsEcommerce: setup found the brand sells online, so its industry+ * becomes E-commerce & Retail when it has none and Shopping mode goes on+ * (ChatGPT Shopping on every prompt, the brand_platforms row), which shows+ * Product Visibility in the menu.+ */++let brand: { industry: string | null; shopping_mode_enabled: boolean };+let prompts: { id: string; platforms: string[] }[];+let writes: { table: string; op: string; value: unknown }[];+// RLS lets a write through, or matches no row without an error (an analyst).+let denied: boolean;++vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }));+vi.mock('@/lib/guards/plan-guard', () => ({ getOrgPlan: vi.fn() }));++vi.mock('@/lib/supabase/server', () => ({+ createClient: vi.fn(async () => ({+ from: (table: string) => {+ let op = 'select';+ let value: unknown = null;+ const settle = async () => {+ if (op !== 'select') {+ if (op === 'update' && denied) return { data: [], error: null };+ writes.push({ table, op, value });+ return { data: [{ id: 'row' }], error: null };+ }+ return { data: table === 'prompts' ? prompts : brand, error: null };+ };+ const chain: Record<string, unknown> = {+ select: () => chain,+ eq: () => chain,+ single: settle,+ update: (patch: unknown) => {+ op = 'update';+ value = patch;+ return chain;+ },+ upsert: (row: unknown) => {+ op = 'upsert';+ value = row;+ return settle();+ },+ then: (resolve: (v: unknown) => unknown) => settle().then(resolve),+ };+ return chain;+ },+ })),+}));++const { markBrandAsEcommerce, setBrandShoppingMode } = await import('./brand');++beforeEach(() => {+ brand = { industry: null, shopping_mode_enabled: false };+ prompts = [+ { id: 'p1', platforms: ['chatgpt-web'] },+ { id: 'p2', platforms: ['chatgpt-web', 'chatgpt-shopping'] },+ ];+ writes = [];+ denied = false;+});++describe('markBrandAsEcommerce', () => {+ it('sets the industry and turns Shopping mode on', async () => {+ expect(await markBrandAsEcommerce('b1')).toEqual({+ industry: 'E-commerce & Retail',+ promptsUpdated: 1,+ });+ expect(writes).toEqual([+ { table: 'brands', op: 'update', value: { industry: 'E-commerce & Retail' } },+ { table: 'brands', op: 'update', value: { shopping_mode_enabled: true } },+ { table: 'prompts', op: 'update', value: { platforms: ['chatgpt-web', 'chatgpt-shopping'] } },+ {+ table: 'brand_platforms',+ op: 'upsert',+ value: { brand_id: 'b1', platform: 'chatgpt-shopping', is_enabled: true },+ },+ ]);+ });++ it('keeps an industry the brand already has', async () => {+ brand.industry = 'Food & Beverage';+ expect(await markBrandAsEcommerce('b1')).toMatchObject({ industry: 'Food & Beverage' });+ expect(writes.some((w) => (w.value as { industry?: string })?.industry)).toBe(false);+ });++ it('leaves a brand already in Shopping mode as it is, industry included', async () => {+ brand = { industry: null, shopping_mode_enabled: true };+ expect(await markBrandAsEcommerce('b1')).toEqual({ industry: null, promptsUpdated: 0 });+ expect(writes).toEqual([]);+ });++ it('fails, writing nothing, when RLS denies the brand update', async () => {+ denied = true;+ await expect(markBrandAsEcommerce('b1')).rejects.toThrow(+ 'Brand not found or you do not have permission to update it.',+ );+ expect(writes).toEqual([]);+ });+});++describe('setBrandShoppingMode', () => {+ it('fails when RLS denies the brand update, adding no prompt platform or brand_platforms row', async () => {+ denied = true;+ await expect(setBrandShoppingMode('b1', true)).rejects.toThrow(+ 'Brand not found or you do not have permission to update it.',+ );+ expect(writes).toEqual([]);+ });+});diff --git a/web/src/lib/actions/brand.ts b/web/src/lib/actions/brand.tsindex ac7846ab7..983586546 100644--- a/web/src/lib/actions/brand.ts+++ b/web/src/lib/actions/brand.ts@@ -6,7 +6,7 @@ import { getOrgPlan } from '@/lib/guards/plan-guard';import { isWithinLimit } from '@/config/plans';import { slugify } from '@/lib/slug';import { API_BASE_URL } from '@/config/api';-import type { Brand, BrandDomain } from '@/types';+import type { Brand, BrandDomain, Industry } from '@/types';import { MAX_PINNED_COMPETITORS } from '@/lib/insights-trend';function mapDomainRow(d: Record<string, unknown>): BrandDomain {@@ -252,12 +252,18 @@ export async function setBrandShoppingMode(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+ // the brand via their org membership. The updated row comes back, as in+ // setBrandActive, so a write RLS denied (an analyst) fails instead of+ // reporting success, and nothing below runs.+ const { data: updated, error: updateErr } = await supabase.from('brands').update({ shopping_mode_enabled: enabled })- .eq('id', brandId);+ .eq('id', brandId)+ .select('id');if (updateErr) throw new Error(updateErr.message);+ if (!updated || updated.length === 0) {+ throw new Error('Brand not found or you do not have permission to update it.');+ }let promptsUpdated = 0;@@ -278,15 +284,16 @@ export async function setBrandShoppingMode(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+ const { data: written, error: writeErr } = await supabase.from('prompts').update({ platforms: next })- .eq('id', (row as { id: string }).id);- if (writeErr) {+ .eq('id', (row as { id: string }).id)+ .select('id');+ if (writeErr || !written?.length) {// 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);+ console.error('[shopping-mode] prompt update failed:', writeErr?.message ?? 'no row');continue;}promptsUpdated += 1;@@ -309,6 +316,43 @@ export async function setBrandShoppingMode(return { promptsUpdated };}+/**+ * Setup found the brand sells products online (competitor research's+ * isEcommerce): its industry becomes E-commerce & Retail when it has none,+ * and Shopping mode goes on, so Product Visibility shows in the menu. A+ * brand already in Shopping mode is left as it is.+ */+export async function markBrandAsEcommerce(+ brandId: string,+): Promise<{ industry: string | null; promptsUpdated: number }> {+ const supabase = await createClient();+ const { data: brand, error } = await supabase+ .from('brands')+ .select('industry, shopping_mode_enabled')+ .eq('id', brandId)+ .single();+ if (error || !brand) throw new Error(error?.message ?? 'Brand not found');++ if (brand.shopping_mode_enabled) return { industry: brand.industry ?? null, promptsUpdated: 0 };++ let industry: string | null = brand.industry ?? null;+ if (!industry) {+ const ecommerce: Industry = 'E-commerce & Retail';+ const { data: updated, error: updateErr } = await supabase+ .from('brands')+ .update({ industry: ecommerce })+ .eq('id', brandId)+ .select('id');+ if (updateErr) throw new Error(updateErr.message);+ if (!updated || updated.length === 0) {+ throw new Error('Brand not found or you do not have permission to update it.');+ }+ industry = ecommerce;+ }+ const { promptsUpdated } = await setBrandShoppingMode(brandId, true);+ return { industry, promptsUpdated };+}+/*** Pause / resume a brand (#286).*diff --git a/web/src/lib/ai-brand-setup.ts b/web/src/lib/ai-brand-setup.tsindex a3b97f177..d20ac45ed 100644--- a/web/src/lib/ai-brand-setup.ts+++ b/web/src/lib/ai-brand-setup.ts@@ -125,13 +125,15 @@ export interface SuggestedCompetitor {export interface SuggestCompetitorsResult {competitors: SuggestedCompetitor[];+ /** Whether the research found the brand sells products online (an online store). */+ isEcommerce: boolean;}/*** POST /api/competitors/suggest*- * Returns the list of suggested competitors (name + domain).- * Throws if the request fails.+ * Returns the list of suggested competitors (name + domain), and whether the+ * brand itself sells products online. Throws if the request fails.*/export async function suggestCompetitors(params: BrandSetupParams & { region?: string },@@ -161,5 +163,5 @@ export async function suggestCompetitors(name: c.name,domain: c.domain,}));- return { competitors };+ return { competitors, isEcommerce: data.isEcommerce === true };}