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(traffic): turn conversions on in brand settings, with what to install and the Shopify pixel (CE-017, part 3) (#1529)
Cihancd307a97dda5
diff --git a/web/messages/en.json b/web/messages/en.jsonindex a98a04a9a..2c4621c12 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -7993,6 +7993,59 @@"deleteButton": "Delete Brand Permanently","managersOnlyEdit": "Only admins and managers can change these settings.","adminsOnlyDelete": "Only admins can delete a brand.",+ "conversions": {+ "title": "Conversions from AI visits",+ "description": "Follow visitors who came from an AI assistant to a signup, a demo form or an order, so the Content Editor shows what each page earns.",+ "label": "Track conversions from AI visits",+ "help": "Off, with the tag without them, the snippet keeps nothing in the browser. On, it keeps a random id for AI visitors only, never a name or an email.",+ "managersOnly": "Only admins and managers can change this.",+ "on": "Conversions are on. Use the tag below on your site.",+ "off": "Conversions are off. Put the tag without them back on your site: until then it still keeps the id in visitors' browsers.",+ "saveFailed": "Couldn't save it. Try again.",+ "copyTag": "Copy the tag",+ "copyConsent": "Copy the consent call",+ "copyDeny": "Copy the refusal call",+ "copyCall": "Copy the conversion call",+ "copyOrderCall": "Copy the order call",+ "copyPixel": "Copy the Shopify pixel",+ "copyBridge": "Copy the Shopify consent script",+ "copied": "Copied",+ "noTag": "There's no tag to show yet: the server URL or the brand's tracking code is missing.",+ "consent": {+ "label": "Consent",+ "wait": "Wait for the visitor's consent (recommended)",+ "always": "Don't wait: our own banner covers it",+ "waitHint": "No id is kept and no journey is sent until your site says the visitor agreed. AI visits themselves are counted as before.",+ "alwaysHint": "Use this only if your cookie banner already asks for analytics storage, or where no consent is needed."+ },+ "steps": {+ "tag": "Use this tag",+ "tagHelp": "It replaces the tag you have, before the closing <code>{tag}</code> tag of every page. The first line lets your site call ansvisor() before the tag has loaded.",+ "consent": "When the visitor agrees",+ "consentHelp": "Call this from your cookie banner once the visitor agrees, and on every page after.",+ "refuse": "When the visitor refuses",+ "denyHelp": "Call this when the visitor says no, or takes consent back, and on every page after, while they say no: the id kept in their browser is deleted, and nothing more is sent.",+ "consentMode": "Google Consent Mode works on its own: the snippet follows <code>{name}</code>. A banner set up inside Google Tag Manager needs a tag for each line above, run when the visitor chooses.",+ "forms": "Forms",+ "formsHelp": "A form with an email field counts as a signup, contact and newsletter forms too: add <code>{goal}</code> to name its goal (demo, newsletter, booking), or <code>{off}</code> to leave it out. A login with a password doesn't count. Don't also call a signup from your own code for the same form, or it counts twice.",+ "calls": "Other conversions",+ "callsHelp": "Call these from your own code, on a thank-you page or after a purchase. The tag's first line keeps them until it loads.",+ "shopify": "Shopify store",+ "shopifyHelp": "In Shopify admin, open Settings › Customer events › Add custom pixel and name it Ansvisor. Under Customer privacy, set Permission to Analytics and Data sale to \"Data collected does not qualify as data sale\". Paste this code, save, then connect it.",+ "shopifyConsent": "Your store asks for consent: add this to your theme (theme.liquid, after the tag) so Shopify's cookie banner gives its answer.",+ "shopifyHeadless": "A headless store whose checkout is on another domain can't link its orders this way.",+ "showPixel": "Show the Shopify pixel"+ },+ "limits": {+ "title": "What it can't see",+ "consent": "Visitors who refuse cookies, in the EU for example.",+ "direct": "AI visits that arrive without a referrer: they count as Direct.",+ "estimate": "Google's AI Overviews and AI Mode, which stay an estimate.",+ "domains": "Journeys from one subdomain to another, www to app for example: each keeps its own id.",+ "iframes": "Forms inside an iframe, like a Typeform or Calendly embed.",+ "personal": "No name, email or IP address is stored with a conversion."+ }+ },"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 show Product Visibility in the menu.",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/_conversions-card.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/_conversions-card.test.tsxnew file mode 100644index 000000000..49b3f378a--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/_conversions-card.test.tsx@@ -0,0 +1,198 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../../../messages/en.json';+import type { Brand } from '@/types';+import { ConversionsCard } from './_conversions-card';++const updateBrand = vi.hoisted(() => vi.fn());+vi.mock('@/lib/actions/brand', () => ({+ updateBrand: (...args: unknown[]) => updateBrand(...args),+}));+const role = vi.hoisted(() => ({ canManage: true }));+vi.mock('@/hooks/use-user-role', () => ({ useUserRole: () => role }));+vi.mock('@/config/api', () => ({ getPublicApiBaseUrl: () => 'https://api.ansvisor.test' }));+const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));+vi.mock('sonner', () => ({ toast }));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++/**+ * Brand settings › Tracking › Conversions from AI visits (CE-017): on or off+ * and the consent mode, saved at once; once on, what the site adds.+ */++const brand = (over: Partial<Brand> = {}): Brand => ({+ id: 'b1',+ organizationId: 'o1',+ name: 'Acme',+ slug: 'acme',+ trackingCode: 'abc123',+ shoppingModeEnabled: false,+ industry: 'Technology',+ isActive: true,+ domains: [],+ createdAt: '2026-10-01T00:00:00Z',+ updatedAt: '2026-10-01T00:00:00Z',+ ...over,+});++let container: HTMLDivElement;+let root: Root;+const onUpdate = vi.fn();++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ updateBrand.mockReset().mockResolvedValue({});+ onUpdate.mockReset();+ toast.error.mockReset();+ toast.success.mockReset();+ role.canManage = true;+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++async function render(over: Partial<Brand> = {}) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <ConversionsCard brand={brand(over)} onUpdate={onUpdate} />+ </NextIntlClientProvider>,+ );+ });+}++const click = async (el: Element | undefined) => {+ await act(async () => {+ el!.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));+ (el as HTMLElement).click();+ });+};+const checkbox = () => container.querySelector<HTMLElement>('#conversions-on')!;+const button = (label: string) =>+ [...container.querySelectorAll('button')].find((b) => b.textContent === label);+const codes = () => [...container.querySelectorAll('pre')].map((pre) => pre.textContent);++describe('ConversionsCard', () => {+ it('says what it does and shows nothing to install while it’s off', async () => {+ await render();+ expect(container.textContent).toContain('Track conversions from AI visits');+ expect(container.textContent).toContain(+ 'Off, with the tag without them, the snippet keeps nothing',+ );+ expect(codes()).toEqual([]);+ });++ it('turns them on at once, then shows the tag with conversions and what the site adds', async () => {+ await render();+ await click(checkbox());+ expect(updateBrand).toHaveBeenCalledWith('b1', { conversionsEnabled: true });+ expect(onUpdate).toHaveBeenCalledWith({ conversionsEnabled: true });+ expect(toast.success).toHaveBeenCalledWith(+ 'Conversions are on. Use the tag below on your site.',+ );+ expect(codes()).toEqual([+ // The queue stub and the tag, copied together: calls before it loads are kept.+ expect.stringMatching(+ /^<script>window\.ansvisor=window\.ansvisor\|\|.*<\/script>\n<script src="https:\/\/api\.ansvisor\.test\/t\.js" data-t="abc123" data-c="1" data-consent="wait" defer><\/script>$/,+ ),+ "ansvisor('consent', 'granted');",+ // And the refusal: an id kept earlier is taken as consent until it's called.+ "ansvisor('consent', 'denied');",+ "ansvisor('conversion', { type: 'demo' });",+ expect.stringContaining("type: 'order'"),+ ]);+ // The refusal under its own line, below the grant.+ expect(container.textContent).toContain('When the visitor agrees');+ expect(container.textContent).toContain('When the visitor refuses');+ // Each copy button says what it copies.+ expect(container.querySelector('button[aria-label="Copy the tag"]')).not.toBeNull();+ expect(container.textContent).toContain("What it can't see");+ });++ it('turns back what it couldn’t save, and says so', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ updateBrand.mockRejectedValue(new Error('offline'));+ await render();+ await click(checkbox());+ expect(toast.error).toHaveBeenCalledWith("Couldn't save it. Try again.");+ expect(checkbox().getAttribute('aria-checked') ?? checkbox().dataset.checked).not.toBe('true');+ expect(codes()).toEqual([]);+ });++ it('saves the consent mode, and the tag and steps follow it', async () => {+ await render({ conversionsEnabled: true });+ const label = [...container.querySelectorAll('label')].find(+ (l) => l.textContent === 'Consent',+ )!;+ await click(container.querySelector(`[id="${label.htmlFor}"]`)!);+ const always = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(+ (o) => o.textContent === "Don't wait: our own banner covers it",+ )!;+ await act(async () => {+ always.dispatchEvent(new MouseEvent('mousemove', { bubbles: true }));+ });+ await click(always);+ expect(updateBrand).toHaveBeenCalledWith('b1', { conversionsConsent: 'always' });+ expect(codes()[0]).toContain('data-consent="always"');+ // Nothing to wait for: no grant, but a visitor who refuses still says so.+ expect(codes()).not.toContain("ansvisor('consent', 'granted');");+ expect(codes()).toContain("ansvisor('consent', 'denied');");+ expect(container.textContent).toContain('When the visitor refuses');+ });++ it('turns the consent mode back when it couldn’t save it', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ updateBrand.mockRejectedValue(new Error('offline'));+ await render({ conversionsEnabled: true });+ const label = [...container.querySelectorAll('label')].find(+ (l) => l.textContent === 'Consent',+ )!;+ await click(container.querySelector(`[id="${label.htmlFor}"]`)!);+ const always = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(+ (o) => o.textContent === "Don't wait: our own banner covers it",+ )!;+ await act(async () => {+ always.dispatchEvent(new MouseEvent('mousemove', { bubbles: true }));+ });+ await click(always);+ expect(toast.error).toHaveBeenCalledWith("Couldn't save it. Try again.");+ expect(codes()[0]).toContain('data-consent="wait"');+ });++ it('shows what the brand says now, after another admin changed it', async () => {+ await render();+ expect(codes()).toEqual([]);+ await render({ conversionsEnabled: true, conversionsConsent: 'always' });+ expect(codes()[0]).toContain('data-consent="always"');+ });++ it('shows the Shopify pixel at once for a shop, with the consent script its banner needs', async () => {+ await render({ conversionsEnabled: true, siteType: 'ecommerce' });+ expect(codes().some((code) => code?.includes('checkout_completed'))).toBe(true);+ expect(codes().some((code) => code?.includes('visitorConsentCollected'))).toBe(true);++ // Another brand: a card of its own.+ act(() => root.unmount());+ root = createRoot(container);+ await render({ conversionsEnabled: true, siteType: 'b2b' });+ expect(codes().some((code) => code?.includes('checkout_completed'))).toBe(false);+ await click(button('Show the Shopify pixel'));+ expect(codes().some((code) => code?.includes('checkout_completed'))).toBe(true);+ });++ it('lets only admins and managers change it', async () => {+ role.canManage = false;+ await render({ conversionsEnabled: true });+ expect(container.textContent).toContain('Only admins and managers can change this.');+ await click(checkbox());+ expect(updateBrand).not.toHaveBeenCalled();+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/_conversions-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/_conversions-card.tsxnew file mode 100644index 000000000..ff298492e--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/settings/_conversions-card.tsx@@ -0,0 +1,288 @@+'use client';++import { useState, type ReactNode } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { Check, Copy, Target } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';+import { Checkbox } from '@/components/ui/checkbox';+import { Label } from '@/components/ui/label';+import { LoadingDots } from '@/components/ui/loading-dots';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';+import { getPublicApiBaseUrl } from '@/config/api';+import { useUserRole } from '@/hooks/use-user-role';+import { updateBrand } from '@/lib/actions/brand';+import {+ CONSENT_CALL,+ CONSENT_MODES,+ CONVERSION_CALL,+ DENY_CALL,+ FORM_GOAL_ATTRIBUTE,+ FORM_OFF_ATTRIBUTE,+ ORDER_CALL,+ SHOPIFY_CONSENT_BRIDGE,+ isConversionsConsent,+ shopifyPixelCode,+ trackingSnippetTag,+ type ConversionsConsent,+} from '@/lib/conversion-tracking';+import { siteTypeOf } from '@/lib/content/page-types';+import type { Brand } from '@/types';++const code = (chunks: ReactNode) => (+ <code className="rounded bg-muted px-1 py-0.5 text-[11px]">{chunks}</code>+);++/**+ * Code to copy, wrapping in its box so a long line never widens the card;+ * its button says what it copies.+ */+function CopyBlock({ text, label }: { text: string; label: string }) {+ const t = useTranslations('brands.settings.conversions');+ const [copied, setCopied] = useState(false);+ const copy = () => {+ void navigator.clipboard.writeText(text);+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ };+ return (+ <div className="relative min-w-0">+ <pre className="whitespace-pre-wrap break-all rounded-md bg-muted py-3 pr-10 pl-4 font-mono text-[12px] leading-relaxed">+ {text}+ </pre>+ <Button+ variant="ghost"+ size="icon"+ className="absolute top-2 right-2 h-7 w-7"+ onClick={copy}+ aria-label={copied ? t('copied') : label}+ >+ {copied ? (+ <Check className="h-3.5 w-3.5 text-emerald-600 dark:text-emerald-400" />+ ) : (+ <Copy className="h-3.5 w-3.5" />+ )}+ </Button>+ </div>+ );+}++/** One step of the set-up: its title, what it says, and its code. */+function Step({ title, children }: { title: string; children: ReactNode }) {+ return (+ <div className="min-w-0 space-y-2">+ <p className="text-sm font-medium">{title}</p>+ {children}+ </div>+ );+}++/**+ * Brand settings › Tracking › Conversions from AI visits (CE-017): turns the+ * snippet's conversions on or off and sets its consent mode, then says what+ * the site adds: the tag with conversions, the consent call, forms' goals,+ * the site's own calls, and the Shopify pixel (shown at once for an+ * e-commerce site, behind a button for others). Off, the snippet keeps+ * nothing in the browser. Admins and managers change it, as the brands+ * writes allow; the rest read it.+ */+export function ConversionsCard({+ brand,+ onUpdate,+}: {+ brand: Brand;+ onUpdate: (updates: Partial<Brand>) => void;+}) {+ const t = useTranslations('brands.settings.conversions');+ const { canManage } = useUserRole();+ const [enabled, setEnabled] = useState(brand.conversionsEnabled === true);+ const [consent, setConsent] = useState<ConversionsConsent>(brand.conversionsConsent ?? 'wait');+ // As the brand reads now: another admin's change, or the store read again.+ const [read, setRead] = useState({+ on: brand.conversionsEnabled,+ consent: brand.conversionsConsent,+ });+ if (read.on !== brand.conversionsEnabled || read.consent !== brand.conversionsConsent) {+ setRead({ on: brand.conversionsEnabled, consent: brand.conversionsConsent });+ setEnabled(brand.conversionsEnabled === true);+ setConsent(brand.conversionsConsent ?? 'wait');+ }+ const [saving, setSaving] = useState(false);+ const [showPixel, setShowPixel] = useState(siteTypeOf(brand) === 'ecommerce');+ const apiUrl = getPublicApiBaseUrl();+ const tag = trackingSnippetTag(apiUrl, brand.trackingCode, consent);+ const pixel = shopifyPixelCode(apiUrl, brand.trackingCode);+ const consentItems = CONSENT_MODES.map((value) => ({+ value,+ label: t(`consent.${value}`),+ }));++ const save = async (updates: Pick<Brand, 'conversionsEnabled' | 'conversionsConsent'>) => {+ if (!canManage) return false;+ setSaving(true);+ try {+ await updateBrand(brand.id, updates);+ onUpdate(updates);+ return true;+ } catch (err) {+ console.error('Failed to save the conversions setting:', err);+ toast.error(t('saveFailed'));+ return false;+ } finally {+ setSaving(false);+ }+ };++ const toggle = async (next: boolean) => {+ setEnabled(next);+ if (await save({ conversionsEnabled: next })) toast.success(t(next ? 'on' : 'off'));+ else setEnabled(!next);+ };++ const pickConsent = async (next: ConversionsConsent) => {+ if (next === consent) return;+ const before = consent;+ setConsent(next);+ if (!(await save({ conversionsConsent: next }))) setConsent(before);+ };++ return (+ <Card>+ <CardHeader>+ <CardTitle className="flex items-center gap-2">+ <Target className="h-4 w-4" />+ {t('title')}+ </CardTitle>+ <CardDescription>{t('description')}</CardDescription>+ </CardHeader>+ <CardContent className="min-w-0 space-y-6">+ <div className="flex items-start gap-3">+ <Checkbox+ id="conversions-on"+ checked={enabled}+ disabled={saving || !canManage}+ onCheckedChange={(v) => void toggle(v === true)}+ />+ <div className="min-w-0 space-y-1">+ <Label htmlFor="conversions-on" className="font-medium">+ {t('label')}+ </Label>+ <p className="text-xs text-muted-foreground">{t('help')}</p>+ {!canManage && <p className="text-xs text-muted-foreground">{t('managersOnly')}</p>}+ </div>+ {saving && <LoadingDots className="ml-auto" />}+ </div>++ {enabled && (+ <>+ <div className="space-y-2">+ <Label htmlFor="conversions-consent">{t('consent.label')}</Label>+ <Select+ items={consentItems}+ value={consent}+ disabled={saving || !canManage}+ onValueChange={(v) => {+ if (isConversionsConsent(v)) void pickConsent(v);+ }}+ >+ <SelectTrigger id="conversions-consent" className="w-full sm:w-96">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {consentItems.map((item) => (+ <SelectItem key={item.value} value={item.value}>+ {item.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <p className="text-xs text-muted-foreground">{t(`consent.${consent}Hint`)}</p>+ </div>++ {tag ? (+ <div className="space-y-5 border-t pt-5">+ <Step title={t('steps.tag')}>+ <p className="text-xs text-muted-foreground">+ {t.rich('steps.tagHelp', { tag: '</head>', code })}+ </p>+ <CopyBlock text={tag} label={t('copyTag')} />+ </Step>+ {/* Waiting: the grant and the refusal; not waiting, the refusal only. */}+ <Step title={t(consent === 'wait' ? 'steps.consent' : 'steps.refuse')}>+ {consent === 'wait' && (+ <>+ <p className="text-xs text-muted-foreground">{t('steps.consentHelp')}</p>+ <CopyBlock text={CONSENT_CALL} label={t('copyConsent')} />+ <p className="pt-1 text-xs font-medium">{t('steps.refuse')}</p>+ </>+ )}+ <p className="text-xs text-muted-foreground">{t('steps.denyHelp')}</p>+ <CopyBlock text={DENY_CALL} label={t('copyDeny')} />+ <p className="text-xs text-muted-foreground">+ {t.rich('steps.consentMode', { name: 'analytics_storage', code })}+ </p>+ </Step>+ <Step title={t('steps.forms')}>+ <p className="text-xs text-muted-foreground">+ {t.rich('steps.formsHelp', {+ goal: FORM_GOAL_ATTRIBUTE,+ off: FORM_OFF_ATTRIBUTE,+ code,+ })}+ </p>+ </Step>+ <Step title={t('steps.calls')}>+ <p className="text-xs text-muted-foreground">{t('steps.callsHelp')}</p>+ <CopyBlock text={CONVERSION_CALL} label={t('copyCall')} />+ <CopyBlock text={ORDER_CALL} label={t('copyOrderCall')} />+ </Step>+ <Step title={t('steps.shopify')}>+ {showPixel && pixel ? (+ <>+ <p className="text-xs text-muted-foreground">{t('steps.shopifyHelp')}</p>+ <CopyBlock text={pixel} label={t('copyPixel')} />+ {consent === 'wait' && (+ <>+ <p className="text-xs text-muted-foreground">+ {t('steps.shopifyConsent')}+ </p>+ <CopyBlock text={SHOPIFY_CONSENT_BRIDGE} label={t('copyBridge')} />+ </>+ )}+ <p className="text-xs text-muted-foreground">{t('steps.shopifyHeadless')}</p>+ </>+ ) : (+ <Button variant="outline" size="sm" onClick={() => setShowPixel(true)}>+ {t('steps.showPixel')}+ </Button>+ )}+ </Step>+ </div>+ ) : (+ <p className="text-xs text-muted-foreground">{t('noTag')}</p>+ )}++ <div className="space-y-1.5 rounded-lg border p-4">+ <p className="text-sm font-medium">{t('limits.title')}</p>+ <ul className="list-disc space-y-1 pl-4 text-xs text-muted-foreground">+ <li>{t('limits.consent')}</li>+ <li>{t('limits.direct')}</li>+ <li>{t('limits.estimate')}</li>+ <li>{t('limits.domains')}</li>+ <li>{t('limits.iframes')}</li>+ <li>{t('limits.personal')}</li>+ </ul>+ </div>+ </>+ )}+ </CardContent>+ </Card>+ );+}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.tsxindex 47f54d0d6..d3967baa2 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@@ -60,6 +60,8 @@ import { getPublicApiBaseUrl } from '@/config/api';import { SITE_TYPES, guessSiteType, isSiteType, type SiteType } from '@/lib/content/page-types';import { qualityPhase } from '@/lib/content/quality';import { BrandFactsTab } from './_brand-facts-tab';+import { ConversionsCard } from './_conversions-card';+import { trackingSnippetTag } from '@/lib/conversion-tracking';interface PageProps {params: Promise<{ id: string }>;@@ -130,8 +132,12 @@ export default function BrandSettingsPage({ params, searchParams }: PageProps) {<DomainsTab brand={brand} onUpdate={(updated) => updateBrandStore(brand.id, updated)} /></TabsContent>- <TabsContent value="tracking">+ <TabsContent value="tracking" className="space-y-6"><TrackingTab brand={brand} />+ <ConversionsCard+ brand={brand}+ onUpdate={(updated) => updateBrandStore(brand.id, updated)}+ /></TabsContent><TabsContent value="competitors">@@ -911,9 +917,13 @@ function CompetitorsTab({ brandId }: { brandId: string }) {function TrackingTab({ brand }: { brand: Brand }) {const [copied, setCopied] = useState<'code' | 'snippet' | null>(null);const apiUrl = getPublicApiBaseUrl();- const snippet = apiUrl- ? `<script src="${apiUrl}/t.js" data-t="${brand.trackingCode || ''}" defer></script>`- : '';+ // With conversions on, the tag that follows AI visitors to them (CE-017).+ const snippet =+ trackingSnippetTag(+ apiUrl,+ brand.trackingCode,+ brand.conversionsEnabled ? (brand.conversionsConsent ?? 'wait') : null,+ ) ?? '';const copyToClipboard = (text: string, key: 'code' | 'snippet') => {navigator.clipboard.writeText(text);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_snippet-code.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_snippet-code.test.tsxindex 4acf3b9c6..b1b5c7bfb 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_snippet-code.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_snippet-code.test.tsx@@ -54,4 +54,17 @@ describe('SnippetDialog', () => {await act(async () => copy.click());expect(writeText).toHaveBeenCalledWith(tag);});++ it('shows the tag with conversions for a brand that has them on (CE-017)', async () => {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <SnippetDialog trackingCode="t_abc123" conversions="wait" open onOpenChange={() => {}} />+ </NextIntlClientProvider>,+ );+ });+ expect(document.body.querySelector('pre')!.textContent).toMatch(+ /window\.ansvisor=window\.ansvisor\|\|[\s\S]*<script src="https:\/\/api\.example\.com\/t\.js" data-t="t_abc123" data-c="1" data-consent="wait" defer><\/script>$/,+ );+ });});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_snippet-code.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_snippet-code.tsxindex d6707873f..800c3b412 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_snippet-code.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_snippet-code.tsx@@ -7,12 +7,14 @@ import { Card, CardContent } from '@/components/ui/card';import { Button } from '@/components/ui/button';import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';import { getPublicApiBaseUrl } from '@/config/api';+import { trackingSnippetTag, type ConversionsConsent } from '@/lib/conversion-tracking';-/** The tracking snippet tag for a brand, or null without a code or an API URL. */-function snippetTag(trackingCode?: string): string | null {- const apiUrl = getPublicApiBaseUrl();- if (!trackingCode || !apiUrl) return null;- return `<script src="${apiUrl}/t.js" data-t="${trackingCode}" defer></script>`;+/**+ * The tracking snippet tag for a brand, with conversions when it has them on+ * (CE-017), or null without a code or an API URL.+ */+function snippetTag(trackingCode?: string, conversions?: ConversionsConsent | null): string | null {+ return trackingSnippetTag(getPublicApiBaseUrl(), trackingCode, conversions ?? null);}/**@@ -65,9 +67,16 @@ function SnippetCode({ snippet }: { snippet: string }) {* visit in the last week (AT-001). Once it has, the code sits behind the* sources strip's Code button instead of staying at the top for good.*/-export function SnippetBanner({ trackingCode }: { trackingCode?: string }) {+export function SnippetBanner({+ trackingCode,+ conversions,+}: {+ trackingCode?: string;+ /** The brand's consent mode when it has conversions on, else null. */+ conversions?: ConversionsConsent | null;+}) {const t = useTranslations('traffic');- const snippet = snippetTag(trackingCode);+ const snippet = snippetTag(trackingCode, conversions);if (!snippet) return null;return (@@ -86,15 +95,18 @@ export function SnippetBanner({ trackingCode }: { trackingCode?: string }) {/** The snippet's code in a dialog, from the sources strip's Code or Install button. */export function SnippetDialog({trackingCode,+ conversions,open,onOpenChange,}: {trackingCode?: string;+ /** The brand's consent mode when it has conversions on, else null. */+ conversions?: ConversionsConsent | null;open: boolean;onOpenChange: (open: boolean) => void;}) {const t = useTranslations('traffic');- const snippet = snippetTag(trackingCode);+ const snippet = snippetTag(trackingCode, conversions);if (!snippet) return null;return (diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsxindex 1dd421fbf..6770d53ac 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx@@ -414,6 +414,8 @@ export default function TrafficPage() {function TrafficPageContent({ brand }: { brand: Brand }) {const t = useTranslations('traffic');+ // The tag follows AI visitors to conversions once the brand turned them on (CE-017).+ const conversions = brand.conversionsEnabled ? (brand.conversionsConsent ?? 'wait') : null;const tCommon = useTranslations('common');const tVisits = useTranslations('traffic.visits');const tTrend = useTranslations('traffic.trend');@@ -743,10 +745,11 @@ function TrafficPageContent({ brand }: { brand: Brand }) {)}{/* The code stays open only while the snippet sends nothing (F3). */}{(sourcesFailed || (sources && !snippetDetected(sources.snippetLastVisitAt))) && (- <SnippetBanner trackingCode={brand.trackingCode} />+ <SnippetBanner trackingCode={brand.trackingCode} conversions={conversions} />)}<SnippetDialogtrackingCode={brand.trackingCode}+ conversions={conversions}open={codeOpen}onOpenChange={setCodeOpen}/>diff --git a/web/src/lib/actions/brand.test.ts b/web/src/lib/actions/brand.test.tsindex 3faa227d4..931dfb168 100644--- a/web/src/lib/actions/brand.test.ts+++ b/web/src/lib/actions/brand.test.ts@@ -106,3 +106,24 @@ describe('updateBrand site type (Content Editor CE-023)', () => {expect(updates).toEqual([]);});});++describe('updateBrand conversions (CE-017)', () => {+ beforeEach(() => {+ updates = [];+ });++ it('saves conversions on or off and the consent mode', async () => {+ await updateBrand('b1', { conversionsEnabled: true });+ await updateBrand('b1', { conversionsConsent: 'always' });+ expect(updates).toEqual([{ conversions_enabled: true }, { conversions_consent: 'always' }]);+ });++ it('refuses a consent mode it doesn’t know, before writing', async () => {+ await expect(+ updateBrand('b1', {+ conversionsConsent: 'sometimes' as Parameters<typeof updateBrand>[1]['conversionsConsent'],+ }),+ ).rejects.toThrow('Unknown consent mode');+ expect(updates).toEqual([]);+ });+});diff --git a/web/src/lib/actions/brand.ts b/web/src/lib/actions/brand.tsindex 40791ebce..d33e7f215 100644--- a/web/src/lib/actions/brand.ts+++ b/web/src/lib/actions/brand.ts@@ -9,6 +9,7 @@ import { API_BASE_URL } from '@/config/api';import type { Brand, BrandDomain, Industry } from '@/types';import { MAX_PINNED_COMPETITORS } from '@/lib/insights-trend';import { isSiteType, type SiteType } from '@/lib/content/page-types';+import { isConversionsConsent, type ConversionsConsent } from '@/lib/conversion-tracking';function mapDomainRow(d: Record<string, unknown>): BrandDomain {return {@@ -35,6 +36,8 @@ function mapBrandRow(brand: Record<string, unknown>, domains: Record<string, unktrackingCode: (brand.tracking_code as string | null) ?? undefined,shoppingModeEnabled: !!brand.shopping_mode_enabled,siteType: (brand.site_type as string | null) ?? undefined,+ conversionsEnabled: brand.conversions_enabled === true,+ conversionsConsent: brand.conversions_consent === 'always' ? 'always' : 'wait',isActive: brand.is_active === undefined ? true : !!brand.is_active,domains: domains.map(mapDomainRow),createdAt: brand.created_at as string,@@ -166,6 +169,9 @@ interface UpdateBrandInput {language?: string;/** The kind of site, for the Content Editor's page types (CE-023). */siteType?: SiteType | null;+ /** Conversions from AI visits (CE-017): on or off, and the snippet's consent mode. */+ conversionsEnabled?: boolean;+ conversionsConsent?: ConversionsConsent;}export async function updateBrand(id: string, updates: UpdateBrandInput): Promise<Brand> {@@ -190,6 +196,13 @@ export async function updateBrand(id: string, updates: UpdateBrandInput): Promis}payload.site_type = updates.siteType ?? null;}+ if (updates.conversionsEnabled !== undefined) {+ payload.conversions_enabled = updates.conversionsEnabled === true;+ }+ if (updates.conversionsConsent !== undefined) {+ if (!isConversionsConsent(updates.conversionsConsent)) throw new Error('Unknown consent mode');+ payload.conversions_consent = updates.conversionsConsent;+ }const { data, error } = await supabase.from('brands')diff --git a/web/src/lib/conversion-tracking.test.ts b/web/src/lib/conversion-tracking.test.tsnew file mode 100644index 000000000..171a268ac--- /dev/null+++ b/web/src/lib/conversion-tracking.test.ts@@ -0,0 +1,122 @@+import { runInNewContext } from 'vm';+import { describe, expect, it } from 'vitest';+import { QUEUE_STUB, shopifyPixelCode, trackingSnippetTag } from './conversion-tracking';++const API = 'https://api.ansvisor.test';+const VISITOR = {+ id: 'Vq3xT0mZ8kLp2RwYbN5sQa',+ f: { s: 'chatgpt.com', u: 'https://shop.example/products/mug', at: 1_790_000_000_000 },+};++describe('trackingSnippetTag', () => {+ it('is the tag as it always was without conversions, and follows AI visitors with them', () => {+ expect(trackingSnippetTag(API, 'abc123')).toBe(+ '<script src="https://api.ansvisor.test/t.js" data-t="abc123" defer></script>',+ );+ // With the queue stub above it: the tag is deferred, the site's calls come first.+ expect(trackingSnippetTag(API, 'abc123', 'wait')).toBe(+ `${QUEUE_STUB}\n<script src="https://api.ansvisor.test/t.js" data-t="abc123" data-c="1" data-consent="wait" defer></script>`,+ );+ expect(trackingSnippetTag(null, 'abc123')).toBeNull();+ expect(trackingSnippetTag(API, undefined)).toBeNull();+ });+});++/**+ * Runs the pixel as Shopify would (its analytics and browser APIs), fires a+ * checkout_completed event, and returns what it sent to the API.+ */+async function completeCheckout({+ stored = VISITOR as unknown,+ checkout = {} as Record<string, unknown>,+} = {}) {+ const code = shopifyPixelCode(API, 'abc123')!;+ const handlers: Record<string, (event: unknown) => Promise<void>> = {};+ const sent: { url: string; body: Record<string, unknown> }[] = [];+ runInNewContext(code, {+ analytics: {+ subscribe: (name: string, fn: (event: unknown) => Promise<void>) => (handlers[name] = fn),+ },+ browser: {+ localStorage: {+ getItem: async (key: string) =>+ key === 'ansvisor_v' && stored ? JSON.stringify(stored) : null,+ },+ },+ fetch: (url: string, init: { body: string }) => {+ sent.push({ url, body: JSON.parse(init.body) });+ return Promise.resolve();+ },+ JSON,+ Number,+ String,+ });+ await handlers.checkout_completed({+ data: {+ checkout: {+ totalPrice: { amount: 129.5, currencyCode: 'EUR' },+ lineItems: [{ quantity: 2 }, { quantity: 1 }],+ order: { id: 'gid://shopify/OrderIdentity/1001' },+ token: 'tok-1',+ ...checkout,+ },+ },+ context: { document: { location: { origin: 'https://shop.example' } } },+ });+ return sent;+}++describe('shopifyPixelCode', () => {+ it('sends the order, its value, currency and units, by the visitor id the snippet kept', async () => {+ expect(await completeCheckout()).toEqual([+ {+ url: 'https://api.ansvisor.test/track/abc123',+ body: {+ k: 'cv',+ g: 'order',+ o: 'shopify',+ id: VISITOR.id,+ f: VISITOR.f,+ // Never the thank-you page's own address: its path carries the order's token.+ u: 'https://shop.example/checkout',+ q: 3,+ val: 129.5,+ cur: 'EUR',+ ref: 'gid://shopify/OrderIdentity/1001',+ },+ },+ ]);+ });++ it('sends nothing for a visitor the snippet didn’t follow', async () => {+ expect(await completeCheckout({ stored: null })).toEqual([]);+ expect(await completeCheckout({ stored: { id: VISITOR.id } })).toEqual([]);+ });++ it('leaves out an amount that isn’t a number, and an order ref without the order’s id: never the token', async () => {+ const [{ body }] = await completeCheckout({+ checkout: { totalPrice: { amount: 'n/a' }, order: undefined },+ });+ expect(body).not.toHaveProperty('val');+ expect(body).not.toHaveProperty('cur');+ expect(body).not.toHaveProperty('ref');+ expect(JSON.stringify(body)).not.toContain('tok-1');+ });++ it('leaves out an amount or units the server wouldn’t take, and still sends the order', async () => {+ const [{ body }] = await completeCheckout({+ checkout: {+ totalPrice: { amount: 2e9, currencyCode: 'IDR' },+ lineItems: [{ quantity: 200000 }],+ },+ });+ expect(body).not.toHaveProperty('val');+ expect(body).not.toHaveProperty('q');+ expect(body).toMatchObject({ g: 'order', cur: 'IDR', ref: 'gid://shopify/OrderIdentity/1001' });+ });++ it('is null without an API URL or a tracking code', () => {+ expect(shopifyPixelCode(null, 'abc123')).toBeNull();+ expect(shopifyPixelCode(API, '')).toBeNull();+ });+});diff --git a/web/src/lib/conversion-tracking.ts b/web/src/lib/conversion-tracking.tsnew file mode 100644index 000000000..a35547994--- /dev/null+++ b/web/src/lib/conversion-tracking.ts@@ -0,0 +1,129 @@+/**+ * What a brand installs to see conversions from AI visits (CE-017): the+ * tracking snippet's tag, with conversions on (data-c, data-consent), the+ * lines the site adds, and the Shopify Customer events pixel. Built here, as+ * the snippet's tag always was, from the public API URL and the brand's+ * tracking code; the snippet itself is the server's (tracking-script.js).+ */++export type ConversionsConsent = 'wait' | 'always';++export const CONSENT_MODES: readonly ConversionsConsent[] = ['wait', 'always'];++export function isConversionsConsent(value: unknown): value is ConversionsConsent {+ return value === 'wait' || value === 'always';+}++/**+ * Lets the page call ansvisor() before t.js has run: the tag is deferred, so+ * a banner's or a thank-you page's call always comes first, and t.js runs+ * what it queued.+ */+export const QUEUE_STUB =+ '<script>window.ansvisor=window.ansvisor||function(){(ansvisor.q=ansvisor.q||[]).push(arguments)};</script>';++/**+ * The snippet's tag for a brand, or null without an API URL or a tracking+ * code. With conversions (the brand's consent mode), it follows AI visitors+ * to conversions, the queue stub on the line above it; without, it is the+ * tag as it always was.+ */+export function trackingSnippetTag(+ apiUrl: string | null | undefined,+ trackingCode: string | null | undefined,+ conversions: ConversionsConsent | null = null,+): string | null {+ if (!apiUrl || !trackingCode) return null;+ if (!conversions) return `<script src="${apiUrl}/t.js" data-t="${trackingCode}" defer></script>`;+ return `${QUEUE_STUB}\n<script src="${apiUrl}/t.js" data-t="${trackingCode}" data-c="1" data-consent="${conversions}" defer></script>`;+}++/** What the site calls once the visitor agrees (its cookie banner), on every page. */+export const CONSENT_CALL = "ansvisor('consent', 'granted');";++/**+ * What the site calls when the visitor says no or takes consent back: the+ * snippet takes an id kept earlier as consent given, so without it a+ * visitor who changes their mind is still followed.+ */+export const DENY_CALL = "ansvisor('consent', 'denied');";++/**+ * Shopify's own cookie banner, told to the snippet (Customer Privacy API):+ * the answer when the visitor gives it, and on each page the one given+ * before (or that none is needed where they are).+ */+export const SHOPIFY_CONSENT_BRIDGE = `<script>+document.addEventListener('visitorConsentCollected', function (e) {+ ansvisor('consent', e.detail.analyticsAllowed ? 'granted' : 'denied');+});+window.Shopify && Shopify.loadFeatures && Shopify.loadFeatures(+ [{ name: 'consent-tracking-api', version: '0.1' }],+ function (error) {+ if (!error && Shopify.customerPrivacy.analyticsProcessingAllowed()) ansvisor('consent', 'granted');+ }+);+</script>`;++/** The site's own conversion, and an order with its value and units. */+export const CONVERSION_CALL = "ansvisor('conversion', { type: 'demo' });";+export const ORDER_CALL =+ "ansvisor('conversion', { type: 'order', value: 129.5, currency: 'EUR', units: 2, order: '1001' });";++/** What a form adds to say its goal, or to stay out. */+export const FORM_GOAL_ATTRIBUTE = 'data-ansvisor-goal="demo"';+export const FORM_OFF_ATTRIBUTE = 'data-ansvisor="off"';++/**+ * The Shopify Customer events custom pixel (Web Pixels API): Shopify runs no+ * theme code on checkout, so the order is sent from here, with its value,+ * currency and units, by the visitor id the snippet kept on the storefront+ * (the checkout is on the shop's domain; a headless store's checkout on+ * another domain can't read it). A visitor the snippet didn't follow (no AI+ * visit, no consent) sends nothing; the server credits the rest as the+ * snippet's events, and counts an order sent twice once, by its id; one+ * Shopify gives no id for goes without, as the checkout's token isn't an+ * order's id (it's in the thank-you page's path). Only an amount and+ * units the server takes go. The checkout's address goes as /checkout: its+ * path carries the order's token. Null without an API URL or a tracking+ * code.+ */+export function shopifyPixelCode(+ apiUrl: string | null | undefined,+ trackingCode: string | null | undefined,+): string | null {+ if (!apiUrl || !trackingCode) return null;+ return `// Ansvisor: orders from AI visits+const ANSVISOR_TRACK = ${JSON.stringify(`${apiUrl}/track/${trackingCode}`)};+analytics.subscribe("checkout_completed", async (event) => {+ let visitor = null;+ try {+ visitor = JSON.parse((await browser.localStorage.getItem("ansvisor_v")) || "null");+ } catch (e) {}+ if (!visitor || !visitor.id || !visitor.f) return;+ const checkout = event.data.checkout || {};+ const total = checkout.totalPrice || {};+ const units = (checkout.lineItems || []).reduce((sum, item) => sum + (item.quantity || 0), 0);+ const order = {+ k: "cv",+ g: "order",+ o: "shopify",+ id: visitor.id,+ f: visitor.f,+ u: event.context.document.location.origin + "/checkout",+ };+ if (Number.isInteger(units) && units >= 0 && units <= 100000) order.q = units;+ const value = Number(total.amount);+ if (Number.isFinite(value) && value >= 0 && value <= 1e9) order.val = value;+ if (typeof total.currencyCode === "string") order.cur = total.currencyCode;+ const ref = checkout.order && checkout.order.id;+ if (ref) order.ref = String(ref);+ fetch(ANSVISOR_TRACK, {+ method: "POST",+ body: JSON.stringify(order),+ headers: { "Content-Type": "text/plain;charset=UTF-8" },+ keepalive: true,+ }).catch(() => {});+});+`;+}diff --git a/web/src/types/index.ts b/web/src/types/index.tsindex d19cc70f8..6c2fdab61 100644--- a/web/src/types/index.ts+++ b/web/src/types/index.ts@@ -27,6 +27,10 @@ export interface Brand {shoppingModeEnabled: boolean;/** b2b, ecommerce or b2c (Content Editor page types); unset = guessed (siteTypeOf). */siteType?: string;+ /** The snippet follows AI visitors to conversions (CE-017, 00286); off by default. */+ conversionsEnabled?: boolean;+ /** 'wait' keeps the snippet's visitor id only after the site's consent, 'always' at once. */+ conversionsConsent?: 'wait' | 'always';isActive: boolean;domains: BrandDomain[];createdAt: string;diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 8e16bc277..df2992228 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -647,6 +647,8 @@ export type Database = {Row: {content_byline: booleancontent_quality_handoff: boolean+ conversions_consent: string+ conversions_enabled: booleancreated_at: stringdescription: string | nullga_property_id: string | null@@ -674,6 +676,8 @@ export type Database = {Insert: {content_byline?: booleancontent_quality_handoff?: boolean+ conversions_consent?: string+ conversions_enabled?: booleancreated_at?: stringdescription?: string | nullga_property_id?: string | null@@ -701,6 +705,8 @@ export type Database = {Update: {content_byline?: booleancontent_quality_handoff?: boolean+ conversions_consent?: string+ conversions_enabled?: booleancreated_at?: stringdescription?: string | nullga_property_id?: string | null