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: GSC property mapping and daily query-stats sync (#647)

Gökhan Geyik04166b98deee
diff --git a/server/.env.example b/server/.env.example
index 8af4c7e71..8b0ea2df4 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -91,3 +91,5 @@ AI_VOLUME_MULTIPLIER=0.15
# these the Integrations card shows "not configured" and everything else works.
# COMPOSIO_API_KEY=
# COMPOSIO_GSC_AUTH_CONFIG_ID=
+# Pinned Search Console toolkit version for tool execution (optional override)
+# COMPOSIO_GSC_TOOLKIT_VERSION=20260721_00
diff --git a/server/src/lib/composio.js b/server/src/lib/composio.js
index 472a54b75..c75a5a5eb 100644
--- a/server/src/lib/composio.js
+++ b/server/src/lib/composio.js
@@ -53,3 +53,48 @@ export async function getActiveGscConnection(entityId) {
export async function deleteGscConnection(connectedAccountId) {
await getClient().connectedAccounts.delete(connectedAccountId);
}
+
+/**
+ * Composio requires a pinned toolkit version for manual tool execution
+ * ("latest" is rejected). Bump deliberately after checking the changelog;
+ * override per-deploy via env if a hotpin is ever needed.
+ */
+const GSC_TOOLKIT_VERSION = process.env.COMPOSIO_GSC_TOOLKIT_VERSION || '20260721_00';
+
+/**
+ * Properties visible to the entity's connected account (#642).
+ * Returns [{ siteUrl, permissionLevel }]. Requires the API key to have
+ * tool-execution permission (the connect flow only needs connected_accounts).
+ */
+export async function listGscSites(entityId) {
+ const result = await getClient().tools.execute('GOOGLE_SEARCH_CONSOLE_LIST_SITES', {
+ userId: entityId,
+ arguments: {},
+ version: GSC_TOOLKIT_VERSION,
+ });
+ if (result?.successful === false) {
+ throw new Error(result?.error || 'Failed to list Search Console properties');
+ }
+ const entries = result?.data?.siteEntry ?? result?.data?.sites ?? [];
+ return entries.map((e) => ({
+ siteUrl: e.siteUrl,
+ permissionLevel: e.permissionLevel ?? null,
+ }));
+}
+
+/**
+ * Search analytics rows for a property (#644). Parameters are deterministic —
+ * built by the caller, never by an LLM. Returns the raw GSC rows:
+ * [{ keys: [query, date], clicks, impressions, ctr, position }].
+ */
+export async function queryGscSearchAnalytics(entityId, args) {
+ const result = await getClient().tools.execute('GOOGLE_SEARCH_CONSOLE_SEARCH_ANALYTICS_QUERY', {
+ userId: entityId,
+ arguments: args,
+ version: GSC_TOOLKIT_VERSION,
+ });
+ if (result?.successful === false) {
+ throw new Error(result?.error || 'Search analytics query failed');
+ }
+ return result?.data?.rows ?? [];
+}
diff --git a/server/src/lib/gsc-sync.js b/server/src/lib/gsc-sync.js
new file mode 100644
index 000000000..61d491508
--- /dev/null
+++ b/server/src/lib/gsc-sync.js
@@ -0,0 +1,132 @@
+/**
+ * Daily Search Console sync (#644).
+ *
+ * For every active brand mapped to a GSC property (whose org connection is
+ * live), pulls the last SYNC_WINDOW_DAYS of per-query daily stats through
+ * Composio and upserts them into gsc_query_stats. Parameters are fully
+ * deterministic — no LLM anywhere in this path. Per-brand failures are
+ * logged and skipped; one broken property never aborts the run.
+ */
+
+import supabaseAdmin from '../config/supabase.js';
+import { isComposioConfigured, queryGscSearchAnalytics } from './composio.js';
+import { logger } from './logger.js';
+
+const SYNC_WINDOW_DAYS = 28;
+const ROW_LIMIT = 5000;
+// GSC returns rows sorted by clicks desc, so pagination walks the long tail
+// of low-volume queries. The page cap is a defensive ceiling (25k rows/brand)
+// — hitting it is logged, never silent.
+const MAX_PAGES = 5;
+const UPSERT_CHUNK = 500;
+
+/** YYYY-MM-DD in UTC, `daysAgo` days before now. */
+function utcDateString(daysAgo = 0) {
+ const d = new Date(Date.now() - daysAgo * 24 * 60 * 60 * 1000);
+ return d.toISOString().slice(0, 10);
+}
+
+/** Map raw GSC rows ({keys:[query,date],...}) to gsc_query_stats rows. */
+export function mapAnalyticsRows(brandId, rows) {
+ const mapped = [];
+ for (const r of rows || []) {
+ const [query, date] = r.keys || [];
+ if (!query || !date) continue;
+ mapped.push({
+ brand_id: brandId,
+ query,
+ date,
+ clicks: Math.round(r.clicks || 0),
+ impressions: Math.round(r.impressions || 0),
+ ctr: r.ctr || 0,
+ position: r.position || 0,
+ });
+ }
+ return mapped;
+}
+
+async function syncBrand(brand) {
+ const entityId = `org_${brand.organization_id}`;
+ let total = 0;
+
+ for (let page = 0; page < MAX_PAGES; page++) {
+ const rows = await queryGscSearchAnalytics(entityId, {
+ site_url: brand.gsc_property,
+ start_date: utcDateString(SYNC_WINDOW_DAYS),
+ end_date: utcDateString(0),
+ dimensions: ['query', 'date'],
+ search_type: 'web',
+ row_limit: ROW_LIMIT,
+ start_row: page * ROW_LIMIT,
+ aggregation_type: 'auto',
+ data_state: 'final',
+ dimension_filter_groups: [],
+ });
+
+ const mapped = mapAnalyticsRows(brand.id, rows);
+ for (let i = 0; i < mapped.length; i += UPSERT_CHUNK) {
+ const chunk = mapped.slice(i, i + UPSERT_CHUNK);
+ const { error } = await supabaseAdmin
+ .from('gsc_query_stats')
+ .upsert(chunk, { onConflict: 'brand_id,query,date' });
+ if (error) throw new Error(`Upsert failed: ${error.message}`);
+ }
+ total += mapped.length;
+
+ // A short page means we've reached the end of the result set.
+ if (rows.length < ROW_LIMIT) return total;
+ }
+
+ logger.warn(
+ { brandId: brand.id, total, maxRows: MAX_PAGES * ROW_LIMIT },
+ '[gsc-sync] page cap reached — result set truncated',
+ );
+ return total;
+}
+
+/**
+ * Sync every eligible brand; optionally scoped to one organization (the
+ * manual trigger). Returns per-brand counts.
+ */
+export async function runGscSync({ organizationId } = {}) {
+ if (!isComposioConfigured()) return { synced: 0, skipped: 0, results: [] };
+
+ // Orgs with a live connection…
+ let connQuery = supabaseAdmin
+ .from('integration_connections')
+ .select('organization_id')
+ .eq('provider', 'google-search-console')
+ .eq('status', 'connected');
+ if (organizationId) connQuery = connQuery.eq('organization_id', organizationId);
+ const { data: connections, error: connError } = await connQuery;
+ if (connError) throw new Error(connError.message);
+ const connectedOrgIds = [...new Set((connections || []).map((c) => c.organization_id))];
+ if (connectedOrgIds.length === 0) return { synced: 0, skipped: 0, results: [] };
+
+ // …and their active brands with a mapped property.
+ const { data: brands, error: brandError } = await supabaseAdmin
+ .from('brands')
+ .select('id, organization_id, gsc_property')
+ .eq('is_active', true)
+ .not('gsc_property', 'is', null)
+ .in('organization_id', connectedOrgIds);
+ if (brandError) throw new Error(brandError.message);
+
+ const results = [];
+ let synced = 0;
+ let skipped = 0;
+ for (const brand of brands || []) {
+ try {
+ const count = await syncBrand(brand);
+ results.push({ brandId: brand.id, rows: count });
+ synced++;
+ } catch (err) {
+ logger.error({ err, brandId: brand.id }, '[gsc-sync] brand sync failed');
+ results.push({ brandId: brand.id, error: err.message });
+ skipped++;
+ }
+ }
+
+ logger.info({ synced, skipped, total: (brands || []).length }, '[gsc-sync] completed');
+ return { synced, skipped, results };
+}
diff --git a/server/src/lib/gsc-sync.test.js b/server/src/lib/gsc-sync.test.js
new file mode 100644
index 000000000..213c68024
--- /dev/null
+++ b/server/src/lib/gsc-sync.test.js
@@ -0,0 +1,75 @@
+import { describe, expect, it, vi } from 'vitest';
+
+// gsc-sync imports the supabase admin client, whose config module hard-exits
+// when SUPABASE_* env is absent (as in CI) — stub it before the import chain.
+vi.mock('../config/supabase.js', () => ({ default: {} }));
+
+import { mapAnalyticsRows } from './gsc-sync.js';
+
+describe('mapAnalyticsRows', () => {
+ it('maps GSC rows keyed by [query, date] into table rows', () => {
+ const rows = mapAnalyticsRows('brand-1', [
+ {
+ keys: ['best aeo tool', '2026-08-01'],
+ clicks: 3,
+ impressions: 120,
+ ctr: 0.025,
+ position: 7.4,
+ },
+ { keys: ['ai visibility', '2026-08-02'], clicks: 0, impressions: 40, ctr: 0, position: 12.1 },
+ ]);
+ expect(rows).toEqual([
+ {
+ brand_id: 'brand-1',
+ query: 'best aeo tool',
+ date: '2026-08-01',
+ clicks: 3,
+ impressions: 120,
+ ctr: 0.025,
+ position: 7.4,
+ },
+ {
+ brand_id: 'brand-1',
+ query: 'ai visibility',
+ date: '2026-08-02',
+ clicks: 0,
+ impressions: 40,
+ ctr: 0,
+ position: 12.1,
+ },
+ ]);
+ });
+
+ it('drops malformed rows and defaults missing metrics to zero', () => {
+ const rows = mapAnalyticsRows('brand-1', [
+ { keys: ['only-query'] },
+ { keys: [] },
+ {},
+ { keys: ['ok', '2026-08-01'] },
+ ]);
+ expect(rows).toEqual([
+ {
+ brand_id: 'brand-1',
+ query: 'ok',
+ date: '2026-08-01',
+ clicks: 0,
+ impressions: 0,
+ ctr: 0,
+ position: 0,
+ },
+ ]);
+ });
+
+ it('rounds fractional click/impression counts from aggregated responses', () => {
+ const rows = mapAnalyticsRows('b', [
+ { keys: ['q', '2026-08-01'], clicks: 2.6, impressions: 99.4, ctr: 0.1, position: 3 },
+ ]);
+ expect(rows[0].clicks).toBe(3);
+ expect(rows[0].impressions).toBe(99);
+ });
+
+ it('handles an empty or missing rows array', () => {
+ expect(mapAnalyticsRows('b', [])).toEqual([]);
+ expect(mapAnalyticsRows('b', undefined)).toEqual([]);
+ });
+});
diff --git a/server/src/routes/integrations.js b/server/src/routes/integrations.js
index 10e510153..dc3d2df80 100644
--- a/server/src/routes/integrations.js
+++ b/server/src/routes/integrations.js
@@ -5,7 +5,9 @@ import {
initiateGscConnection,
getActiveGscConnection,
deleteGscConnection,
+ listGscSites,
} from '../lib/composio.js';
+import { runGscSync } from '../lib/gsc-sync.js';
const router = Router();
@@ -93,6 +95,33 @@ router.get('/google-search-console/status', async (req, res) => {
}
});
+/**
+ * GET /api/integrations/google-search-console/properties
+ * Properties visible to the org's connected account (#642). Member-readable —
+ * the mapping UI is shown to the whole org; writes stay role-gated elsewhere.
+ */
+router.get('/google-search-console/properties', async (req, res) => {
+ try {
+ if (!isComposioConfigured()) {
+ return res.status(503).json({ error: 'Search Console integration is not configured.' });
+ }
+
+ const profile = await getProfile(req.user.id);
+ const entityId = entityIdFor(profile.organization_id);
+
+ const active = await getActiveGscConnection(entityId);
+ if (!active) {
+ return res.status(409).json({ error: 'Google Search Console is not connected.' });
+ }
+
+ const properties = await listGscSites(entityId);
+ return res.json({ properties });
+ } catch (err) {
+ req.log.error({ err }, 'integrations properties error');
+ return res.status(err.status || 500).json({ error: err.message });
+ }
+});
+
/**
* POST /api/integrations/google-search-console/connect
* Body: { callbackUrl } — where Composio sends the browser after consent.
@@ -143,6 +172,30 @@ router.post('/google-search-console/connect', async (req, res) => {
}
});
+/**
+ * POST /api/integrations/google-search-console/sync
+ * Runs the query-stats sync for the caller's org immediately (#644) —
+ * testing and first-time backfill; the daily cycle runs the same sync.
+ */
+router.post('/google-search-console/sync', async (req, res) => {
+ try {
+ if (!isComposioConfigured()) {
+ return res.status(503).json({ error: 'Search Console integration is not configured.' });
+ }
+
+ const profile = await getProfile(req.user.id);
+ if (!WRITE_ROLES.includes(profile.role)) {
+ return res.status(403).json({ error: 'Only admins and managers can trigger a sync.' });
+ }
+
+ const result = await runGscSync({ organizationId: profile.organization_id });
+ return res.json(result);
+ } catch (err) {
+ req.log.error({ err }, 'integrations sync error');
+ return res.status(err.status || 500).json({ error: err.message });
+ }
+});
+
/**
* DELETE /api/integrations/google-search-console
* Removes the connected account on Composio and resets our row.
diff --git a/server/src/server.js b/server/src/server.js
index ab4758270..18e8d4c34 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -30,6 +30,7 @@ import { recountBrandCitations } from './lib/citation-recount.js';
import supabaseAdmin from './config/supabase.js';
import { getPlan, hasFeature, isCloud, isSubscriptionActive } from './config/plans.js';
import { analyzeBrandVolumes } from './lib/volume-analysis.js';
+import { runGscSync } from './lib/gsc-sync.js';
const app = express();
app.set('trust proxy', 1);
@@ -170,6 +171,13 @@ async function runDailyTracking() {
}
logger.info({ triggered, total: brands.length }, 'daily tracking triggered');
+
+ // Search Console sync (#644) — independent follow-up step; never blocks or
+ // fails the tracking run. No-ops when Composio isn't configured.
+ runGscSync().catch((err) => {
+ logger.error({ err }, '[gsc-sync] daily run failed');
+ });
+
return { triggered, total: brands.length };
}
diff --git a/supabase/migrations/00046_brand_gsc_property.sql b/supabase/migrations/00046_brand_gsc_property.sql
new file mode 100644
index 000000000..b96768b61
--- /dev/null
+++ b/supabase/migrations/00046_brand_gsc_property.sql
@@ -0,0 +1,10 @@
+-- Brand → Search Console property mapping (#642).
+--
+-- The GSC connection is org-level (integration_connections); the property
+-- choice is brand-level. Exactly one property per brand, so a column beats a
+-- mapping table. Values are GSC siteUrl strings: either a URL-prefix
+-- ("https://example.com/") or a domain property ("sc-domain:example.com").
+-- Kept on disconnect so reconnecting restores functionality without
+-- re-picking.
+
+ALTER TABLE public.brands ADD COLUMN gsc_property text;
diff --git a/supabase/migrations/00047_gsc_query_stats.sql b/supabase/migrations/00047_gsc_query_stats.sql
new file mode 100644
index 000000000..9b8a64968
--- /dev/null
+++ b/supabase/migrations/00047_gsc_query_stats.sql
@@ -0,0 +1,35 @@
+-- Search Console query stats (#644) — daily per-query rows pulled through
+-- the Composio connection for every brand mapped to a GSC property.
+--
+-- The sync (service role) writes with upserts on (brand_id, query, date);
+-- org members read. Retention/pruning comes with the first consumer.
+
+CREATE TABLE public.gsc_query_stats (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ brand_id uuid NOT NULL REFERENCES public.brands(id) ON DELETE CASCADE,
+ query text NOT NULL,
+ date date NOT NULL,
+ clicks integer NOT NULL DEFAULT 0,
+ impressions integer NOT NULL DEFAULT 0,
+ ctr double precision NOT NULL DEFAULT 0,
+ position double precision NOT NULL DEFAULT 0,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (brand_id, query, date)
+);
+
+CREATE INDEX gsc_query_stats_brand_date_idx
+ ON public.gsc_query_stats (brand_id, date DESC);
+
+ALTER TABLE public.gsc_query_stats ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "gsc_query_stats: member select" ON public.gsc_query_stats
+ FOR SELECT USING (
+ brand_id IN (
+ SELECT b.id
+ FROM public.brands b
+ JOIN public.profiles p ON p.organization_id = b.organization_id
+ WHERE p.id = auth.uid()
+ )
+ );
+
+GRANT SELECT ON public.gsc_query_stats TO authenticated;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 968e18d43..153f18f81 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -4954,3 +4954,56 @@ CREATE POLICY "integration_connections: admin write" ON public.integration_conne
GRANT SELECT ON public.integration_connections TO authenticated;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00046_brand_gsc_property.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Brand → Search Console property mapping (#642).
+--
+-- The GSC connection is org-level (integration_connections); the property
+-- choice is brand-level. Exactly one property per brand, so a column beats a
+-- mapping table. Values are GSC siteUrl strings: either a URL-prefix
+-- ("https://example.com/") or a domain property ("sc-domain:example.com").
+-- Kept on disconnect so reconnecting restores functionality without
+-- re-picking.
+
+ALTER TABLE public.brands ADD COLUMN gsc_property text;
+
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00047_gsc_query_stats.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Search Console query stats (#644) — daily per-query rows pulled through
+-- the Composio connection for every brand mapped to a GSC property.
+--
+-- The sync (service role) writes with upserts on (brand_id, query, date);
+-- org members read. Retention/pruning comes with the first consumer.
+
+CREATE TABLE public.gsc_query_stats (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ brand_id uuid NOT NULL REFERENCES public.brands(id) ON DELETE CASCADE,
+ query text NOT NULL,
+ date date NOT NULL,
+ clicks integer NOT NULL DEFAULT 0,
+ impressions integer NOT NULL DEFAULT 0,
+ ctr double precision NOT NULL DEFAULT 0,
+ position double precision NOT NULL DEFAULT 0,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (brand_id, query, date)
+);
+
+CREATE INDEX gsc_query_stats_brand_date_idx
+ ON public.gsc_query_stats (brand_id, date DESC);
+
+ALTER TABLE public.gsc_query_stats ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "gsc_query_stats: member select" ON public.gsc_query_stats
+ FOR SELECT USING (
+ brand_id IN (
+ SELECT b.id
+ FROM public.brands b
+ JOIN public.profiles p ON p.organization_id = b.organization_id
+ WHERE p.id = auth.uid()
+ )
+ );
+
+GRANT SELECT ON public.gsc_query_stats TO authenticated;
+
diff --git a/web/src/components/settings/integrations-section.tsx b/web/src/components/settings/integrations-section.tsx
index c2ad3f024..7610d784f 100644
--- a/web/src/components/settings/integrations-section.tsx
+++ b/web/src/components/settings/integrations-section.tsx
@@ -16,13 +16,26 @@ import {
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
import { Loader2, Search, Unplug } from 'lucide-react';
import {
getGscStatus,
connectGsc,
disconnectGsc,
+ getGscProperties,
+ getGscBrandMappings,
+ setBrandGscProperty,
type GscStatus,
+ type GscProperty,
+ type GscBrandMapping,
} from '@/lib/actions/integrations';
+import { matchGscProperty } from '@/lib/gsc';
/**
* Settings → Integrations (#577). One card per integration — only Google
@@ -212,7 +225,152 @@ export function IntegrationsSection() {
environment to enable integrations.
</p>
)}
+
+ {status === 'connected' && <GscPropertyMapping />}
</CardContent>
</Card>
);
}
+
+/**
+ * Brand → property mapping (#642). The connection is org-level; each brand
+ * picks exactly one Search Console property. Brands whose domain matches a
+ * property unambiguously are premapped automatically.
+ */
+const NONE_VALUE = '__none__';
+
+function GscPropertyMapping() {
+ const [properties, setProperties] = useState<GscProperty[] | null>(null);
+ const [mappings, setMappings] = useState<GscBrandMapping[] | null>(null);
+ const [loadFailed, setLoadFailed] = useState<string | null>(null);
+ const [savingBrandId, setSavingBrandId] = useState<string | null>(null);
+ const autoMatched = useRef(false);
+
+ const load = useCallback(async () => {
+ setLoadFailed(null);
+ try {
+ const [props, brands] = await Promise.all([getGscProperties(), getGscBrandMappings()]);
+ setProperties(props);
+ setMappings(brands);
+ } catch (err) {
+ setLoadFailed(err instanceof Error ? err.message : 'Failed to load properties');
+ }
+ }, []);
+
+ useEffect(() => {
+ load();
+ }, [load]);
+
+ // Auto-match: premap unmapped brands whose domains match exactly one
+ // property. Runs once per mount; a failed save (e.g. member role) just
+ // leaves the brand unmapped for a manual pick by an admin.
+ useEffect(() => {
+ if (!properties || !mappings || autoMatched.current) return;
+ autoMatched.current = true;
+ const propertyUrls = properties.map((p) => p.siteUrl);
+ (async () => {
+ for (const m of mappings) {
+ if (m.gscProperty) continue;
+ const match = matchGscProperty(propertyUrls, m.domains);
+ if (!match) continue;
+ try {
+ await setBrandGscProperty(m.brandId, match);
+ setMappings((prev) =>
+ (prev ?? []).map((row) =>
+ row.brandId === m.brandId ? { ...row, gscProperty: match } : row,
+ ),
+ );
+ } catch (err) {
+ console.error('GSC auto-map failed:', err);
+ return; // likely a permissions error — no point retrying the rest
+ }
+ }
+ })();
+ }, [properties, mappings]);
+
+ const handlePick = async (brandId: string, value: string) => {
+ const property = value === NONE_VALUE ? null : value;
+ const previous = mappings;
+ setSavingBrandId(brandId);
+ setMappings((prev) =>
+ (prev ?? []).map((row) =>
+ row.brandId === brandId ? { ...row, gscProperty: property } : row,
+ ),
+ );
+ try {
+ await setBrandGscProperty(brandId, property);
+ } catch (err) {
+ setMappings(previous);
+ toast.error(err instanceof Error ? err.message : 'Failed to save property');
+ } finally {
+ setSavingBrandId(null);
+ }
+ };
+
+ if (loadFailed) {
+ return (
+ <div className="rounded-lg border p-4 text-sm">
+ <p className="text-muted-foreground">Couldn&apos;t load Search Console properties.</p>
+ <p className="mt-1 text-xs text-muted-foreground">{loadFailed}</p>
+ <Button variant="outline" size="sm" className="mt-3" onClick={load}>
+ Retry
+ </Button>
+ </div>
+ );
+ }
+
+ if (!properties || !mappings) {
+ return <Skeleton className="h-24 w-full" />;
+ }
+
+ const mappedCount = mappings.filter((m) => m.gscProperty).length;
+
+ return (
+ <div className="rounded-lg border p-4 space-y-3">
+ <div className="flex items-center justify-between gap-2">
+ <p className="text-sm font-medium">Property mapping</p>
+ <span className="text-xs text-muted-foreground">
+ {mappedCount} of {mappings.length} brand{mappings.length !== 1 ? 's' : ''} mapped
+ </span>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ Pick which Search Console property each brand&apos;s data comes from. Brands matching a
+ property by domain are mapped automatically.
+ </p>
+ <div className="space-y-2">
+ {mappings.map((m) => (
+ <div key={m.brandId} className="flex items-center justify-between gap-3">
+ <span className="truncate text-sm">{m.brandName}</span>
+ <div className="flex items-center gap-2">
+ {savingBrandId === m.brandId && (
+ <Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" />
+ )}
+ <Select
+ value={m.gscProperty ?? null}
+ onValueChange={(v) => handlePick(m.brandId, v ?? NONE_VALUE)}
+ >
+ <SelectTrigger className="h-8 w-64 text-xs">
+ <SelectValue placeholder="Select a property" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={NONE_VALUE}>Not mapped</SelectItem>
+ {properties.map((p) => (
+ <SelectItem key={p.siteUrl} value={p.siteUrl}>
+ {p.siteUrl}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+ ))}
+ </div>
+ {properties.length === 0 && (
+ <p className="text-xs text-muted-foreground">
+ The connected account has no Search Console properties. Add your site in Search Console
+ first, then retry.
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/lib/actions/integrations.ts b/web/src/lib/actions/integrations.ts
index 4fdb5816f..7c0f8f18a 100644
--- a/web/src/lib/actions/integrations.ts
+++ b/web/src/lib/actions/integrations.ts
@@ -52,3 +52,53 @@ export async function disconnectGsc(): Promise<void> {
const body = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(body.error || `Server error: ${res.status}`);
}
+
+// ─── Property mapping (#642) ─────────────────────────────────────────────────
+
+export interface GscProperty {
+ siteUrl: string;
+ permissionLevel: string | null;
+}
+
+export async function getGscProperties(): Promise<GscProperty[]> {
+ const res = await fetch(`${API_BASE_URL}/api/integrations/google-search-console/properties`, {
+ headers: await authHeaders(),
+ cache: 'no-store',
+ });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(body.error || `Server error: ${res.status}`);
+ return (body.properties ?? []) as GscProperty[];
+}
+
+export interface GscBrandMapping {
+ brandId: string;
+ brandName: string;
+ gscProperty: string | null;
+ domains: string[];
+}
+
+/** Org brands with their domains and current property picks (RLS-scoped). */
+export async function getGscBrandMappings(): Promise<GscBrandMapping[]> {
+ const supabase = await createClient();
+ const { data, error } = await supabase
+ .from('brands')
+ .select('id, name, gsc_property, brand_domains(domain)')
+ .order('created_at', { ascending: true });
+ if (error) throw new Error(error.message);
+ return (data ?? []).map((b) => ({
+ brandId: b.id,
+ brandName: b.name,
+ gscProperty: b.gsc_property,
+ domains: (b.brand_domains ?? []).map((d) => d.domain),
+ }));
+}
+
+/** Persist a brand's property pick (null clears it). RLS: admin/manager. */
+export async function setBrandGscProperty(brandId: string, property: string | null): Promise<void> {
+ const supabase = await createClient();
+ const { error } = await supabase
+ .from('brands')
+ .update({ gsc_property: property })
+ .eq('id', brandId);
+ if (error) throw new Error(error.message);
+}
diff --git a/web/src/lib/gsc.test.ts b/web/src/lib/gsc.test.ts
new file mode 100644
index 000000000..e603d84ab
--- /dev/null
+++ b/web/src/lib/gsc.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest';
+import { matchGscProperty, propertyMatchesDomain } from './gsc';
+
+describe('propertyMatchesDomain', () => {
+ it('matches a domain property against the apex and subdomains', () => {
+ expect(propertyMatchesDomain('sc-domain:example.com', 'example.com')).toBe(true);
+ expect(propertyMatchesDomain('sc-domain:example.com', 'app.example.com')).toBe(true);
+ expect(propertyMatchesDomain('sc-domain:example.com', 'other.com')).toBe(false);
+ // Suffix must be a label boundary, not a substring.
+ expect(propertyMatchesDomain('sc-domain:example.com', 'notexample.com')).toBe(false);
+ });
+
+ it('matches a URL-prefix property by host, ignoring scheme, www and paths', () => {
+ expect(propertyMatchesDomain('https://www.example.com/', 'example.com')).toBe(true);
+ expect(propertyMatchesDomain('https://example.com/', 'https://www.example.com')).toBe(true);
+ expect(propertyMatchesDomain('https://blog.example.com/', 'example.com')).toBe(false);
+ });
+});
+
+describe('matchGscProperty', () => {
+ const properties = ['sc-domain:acme.dev', 'https://www.example.com/', 'https://docs.other.io/'];
+
+ it('returns the single matching property', () => {
+ expect(matchGscProperty(properties, ['example.com'])).toBe('https://www.example.com/');
+ expect(matchGscProperty(properties, ['app.acme.dev'])).toBe('sc-domain:acme.dev');
+ });
+
+ it('returns null when nothing matches', () => {
+ expect(matchGscProperty(properties, ['unrelated.com'])).toBeNull();
+ });
+
+ it('returns null when several properties match (human pick required)', () => {
+ expect(
+ matchGscProperty(['sc-domain:example.com', 'https://example.com/'], ['example.com']),
+ ).toBeNull();
+ });
+});
diff --git a/web/src/lib/gsc.ts b/web/src/lib/gsc.ts
new file mode 100644
index 000000000..75485eb97
--- /dev/null
+++ b/web/src/lib/gsc.ts
@@ -0,0 +1,42 @@
+/**
+ * Google Search Console property matching (#642).
+ *
+ * A GSC property is either a URL-prefix ("https://www.example.com/") or a
+ * domain property ("sc-domain:example.com"). A brand knows its domains
+ * (brand_domains). Auto-mapping picks the property that matches a brand
+ * domain — and only auto-applies when the match is unambiguous.
+ */
+
+function normalizeHost(value: string): string {
+ return value
+ .trim()
+ .toLowerCase()
+ .replace(/^https?:\/\//, '')
+ .replace(/\/.*$/, '')
+ .replace(/^www\./, '');
+}
+
+/** True when the property covers the given (normalized) brand domain. */
+export function propertyMatchesDomain(siteUrl: string, domain: string): boolean {
+ const host = normalizeHost(domain);
+ if (!host) return false;
+
+ if (siteUrl.startsWith('sc-domain:')) {
+ // Domain properties cover the apex and every subdomain.
+ const apex = siteUrl.slice('sc-domain:'.length).trim().toLowerCase();
+ return host === apex || host.endsWith(`.${apex}`);
+ }
+
+ return normalizeHost(siteUrl) === host;
+}
+
+/**
+ * The single property matching any of the brand's domains, or null when
+ * none or several match (ambiguity needs a human pick).
+ */
+export function matchGscProperty(propertyUrls: string[], brandDomains: string[]): string | null {
+ const matches = propertyUrls.filter((siteUrl) =>
+ brandDomains.some((domain) => propertyMatchesDomain(siteUrl, domain)),
+ );
+ return matches.length === 1 ? matches[0] : null;
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index d626e2bed..8dd0930df 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -286,6 +286,7 @@ export type Database = {
created_at: string;
description: string | null;
id: string;
+ gsc_property: string | null;
industry: string | null;
is_active: boolean;
language: string | null;
@@ -303,6 +304,7 @@ export type Database = {
created_at?: string;
description?: string | null;
id?: string;
+ gsc_property?: string | null;
industry?: string | null;
is_active?: boolean;
language?: string | null;
@@ -320,6 +322,7 @@ export type Database = {
created_at?: string;
description?: string | null;
id?: string;
+ gsc_property?: string | null;
industry?: string | null;
is_active?: boolean;
language?: string | null;
@@ -441,6 +444,50 @@ export type Database = {
},
];
};
+ gsc_query_stats: {
+ Row: {
+ brand_id: string;
+ clicks: number;
+ created_at: string;
+ ctr: number;
+ date: string;
+ id: string;
+ impressions: number;
+ position: number;
+ query: string;
+ };
+ Insert: {
+ brand_id: string;
+ clicks?: number;
+ created_at?: string;
+ ctr?: number;
+ date: string;
+ id?: string;
+ impressions?: number;
+ position?: number;
+ query: string;
+ };
+ Update: {
+ brand_id?: string;
+ clicks?: number;
+ created_at?: string;
+ ctr?: number;
+ date?: string;
+ id?: string;
+ impressions?: number;
+ position?: number;
+ query?: string;
+ };
+ Relationships: [
+ {
+ foreignKeyName: 'gsc_query_stats_brand_id_fkey';
+ columns: ['brand_id'];
+ isOneToOne: false;
+ referencedRelation: 'brands';
+ referencedColumns: ['id'];
+ },
+ ];
+ };
integration_connections: {
Row: {
composio_account_id: string | null;