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(integrations): map each brand to a GA4 property (#703)

Gökhan Geyika60c09923ce7
diff --git a/server/.env.example b/server/.env.example
index 9796cb1db..f2dcbaab8 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -94,8 +94,15 @@ AI_VOLUME_MULTIPLIER=0.15
# COMPOSIO_API_KEY=
# COMPOSIO_GSC_AUTH_CONFIG_ID=
# COMPOSIO_GA_AUTH_CONFIG_ID=
-# Pinned Search Console toolkit version for tool execution (optional override)
+# Pinned toolkit versions for tool execution (optional overrides)
# COMPOSIO_GSC_TOOLKIT_VERSION=20260721_00
+# COMPOSIO_GA_TOOLKIT_VERSION=20260721_00
+# GA4 property listing limits (#694). Listing is one call; resolving each
+# property's web data streams for the domain auto-match is one call per
+# property, so the second limit bounds how long the mapping UI waits.
+# Properties past it stay listed and manually selectable.
+# COMPOSIO_GA_MAX_PROPERTIES=500
+# COMPOSIO_GA_STREAM_LOOKUPS=100
# Drain-stall tolerance: consecutive 15s polls with no new Cloro result before
# a run stops waiting (default 100 ≈ 25 min; hard deadline is 60 min).
diff --git a/server/src/lib/composio.js b/server/src/lib/composio.js
index 7f3ce9aea..7fe98fd07 100644
--- a/server/src/lib/composio.js
+++ b/server/src/lib/composio.js
@@ -131,3 +131,106 @@ export async function queryGscSearchAnalytics(entityId, args) {
}
return result?.data?.rows ?? [];
}
+
+// ─── Google Analytics ────────────────────────────────────────────────────────
+
+/**
+ * Same pinning rule as Search Console — manual tool execution rejects
+ * "latest". Kept separate so the two toolkits can be bumped independently.
+ */
+const GA_TOOLKIT_VERSION = process.env.COMPOSIO_GA_TOOLKIT_VERSION || '20260721_00';
+
+/** Hard ceiling on how many properties the picker lists. */
+const GA_MAX_PROPERTIES = Number(process.env.COMPOSIO_GA_MAX_PROPERTIES) || 500;
+/**
+ * Properties we resolve data streams for. Listing them is a couple of calls
+ * regardless of size, but streams are one call per property (~1s each), so
+ * this bounds how long the mapping UI waits. Properties past the limit are
+ * still listed and still selectable by hand — they just don't take part in
+ * the domain auto-match.
+ */
+const GA_STREAM_LOOKUP_LIMIT = Number(process.env.COMPOSIO_GA_STREAM_LOOKUPS) || 100;
+/** Stream lookups in flight at once. */
+const GA_STREAM_CONCURRENCY = 8;
+
+async function executeGaTool(slug, entityId, args) {
+ const result = await getClient().tools.execute(slug, {
+ userId: entityId,
+ arguments: args,
+ version: GA_TOOLKIT_VERSION,
+ });
+ if (result?.successful === false) {
+ throw new Error(result?.error || `${slug} failed`);
+ }
+ return result?.data ?? {};
+}
+
+/** Site URLs served by a property's web data streams (app streams have none). */
+async function gaPropertySiteUrls(entityId, propertyId) {
+ const data = await executeGaTool('GOOGLE_ANALYTICS_LIST_DATA_STREAMS', entityId, {
+ parent: `properties/${propertyId}`,
+ pageSize: 200,
+ });
+ return (data.dataStreams ?? [])
+ .map((stream) => stream.webStreamData?.defaultUri)
+ .filter((uri) => typeof uri === 'string' && uri.length > 0);
+}
+
+/**
+ * GA4 properties visible to the entity's connected account (#694).
+ *
+ * `LIST_ACCOUNT_SUMMARIES` returns every account with its properties, but a
+ * GA4 property is a numeric id plus a free-text display name — nothing a brand
+ * domain can be matched against. The site URL lives on the property's web data
+ * streams, so those are resolved too (bounded concurrency and count, best
+ * effort): a property whose streams fail to load, or that falls past the
+ * lookup limit, simply arrives with no site URLs and stays manually
+ * selectable.
+ *
+ * Returns [{ propertyId, displayName, accountName, siteUrls }].
+ */
+export async function listGaProperties(entityId) {
+ const properties = [];
+ let pageToken = null;
+
+ do {
+ const args = { pageSize: 200 };
+ if (pageToken) args.pageToken = pageToken;
+ const data = await executeGaTool('GOOGLE_ANALYTICS_LIST_ACCOUNT_SUMMARIES', entityId, args);
+
+ for (const account of data.accountSummaries ?? []) {
+ for (const summary of account.propertySummaries ?? []) {
+ // "properties/365372770" → "365372770"; the prefix is constant and is
+ // added back by the callers that hit the Admin / Data APIs.
+ const propertyId = String(summary.property ?? '').split('/')[1];
+ if (!propertyId) continue;
+ properties.push({
+ propertyId,
+ displayName: summary.displayName ?? propertyId,
+ accountName: account.displayName ?? null,
+ siteUrls: [],
+ });
+ }
+ }
+
+ pageToken = data.nextPageToken ?? null;
+ } while (pageToken && properties.length < GA_MAX_PROPERTIES);
+
+ const capped = properties.slice(0, GA_MAX_PROPERTIES);
+ const withStreams = capped.slice(0, GA_STREAM_LOOKUP_LIMIT);
+
+ for (let i = 0; i < withStreams.length; i += GA_STREAM_CONCURRENCY) {
+ const batch = withStreams.slice(i, i + GA_STREAM_CONCURRENCY);
+ await Promise.all(
+ batch.map(async (property) => {
+ try {
+ property.siteUrls = await gaPropertySiteUrls(entityId, property.propertyId);
+ } catch {
+ // Best effort — the property stays listed, just without auto-match.
+ }
+ }),
+ );
+ }
+
+ return capped;
+}
diff --git a/server/src/routes/integrations.js b/server/src/routes/integrations.js
index 4327f677c..cb660a02b 100644
--- a/server/src/routes/integrations.js
+++ b/server/src/routes/integrations.js
@@ -8,12 +8,14 @@ import {
getActiveConnection,
deleteConnection,
listGscSites,
+ listGaProperties,
} from '../lib/composio.js';
import { runGscSync } from '../lib/gsc-sync.js';
const router = Router();
const GSC = 'google-search-console';
+const GA = 'google-analytics';
const WRITE_ROLES = ['admin', 'manager'];
/** Entity id: one connection per organization per provider (#577). */
@@ -216,10 +218,10 @@ router.delete('/:provider', async (req, res) => {
}
});
-// ─── Search Console specific ─────────────────────────────────────────────────
-// Property listing and the query-stats sync have no Analytics equivalent yet
-// (that arrives with the GA data phase), so they stay on explicit paths
-// rather than under :provider.
+// ─── Provider specific ───────────────────────────────────────────────────────
+// Property listing differs per provider (a GSC property is a URL, a GA4
+// property is a numeric id), and the query-stats sync has no Analytics
+// equivalent yet, so these stay on explicit paths rather than under :provider.
/**
* GET /api/integrations/google-search-console/properties
@@ -268,4 +270,29 @@ router.post('/google-search-console/sync', async (req, res) => {
}
});
+/**
+ * GET /api/integrations/google-analytics/properties
+ * GA4 properties visible to the org's connected account (#694). Member-
+ * readable, like the Search Console listing above.
+ */
+router.get('/google-analytics/properties', async (req, res) => {
+ try {
+ if (!isComposioConfigured(GA)) return notConfigured(res, GA);
+
+ const profile = await getProfile(req.user.id);
+ const entityId = entityIdFor(profile.organization_id);
+
+ const active = await getActiveConnection(GA, entityId);
+ if (!active) {
+ return res.status(409).json({ error: 'Google Analytics is not connected.' });
+ }
+
+ const properties = await listGaProperties(entityId);
+ return res.json({ properties });
+ } catch (err) {
+ req.log.error({ err }, 'integrations GA properties error');
+ return res.status(err.status || 500).json({ error: err.message });
+ }
+});
+
export default router;
diff --git a/supabase/migrations/00051_brand_ga_property.sql b/supabase/migrations/00051_brand_ga_property.sql
new file mode 100644
index 000000000..0488b530a
--- /dev/null
+++ b/supabase/migrations/00051_brand_ga_property.sql
@@ -0,0 +1,11 @@
+-- Brand → Google Analytics property mapping (#694).
+--
+-- Mirrors gsc_property (00046): the Analytics connection is org-level
+-- (integration_connections), the property choice is brand-level, and exactly
+-- one property per brand means a column beats a mapping table. Values are the
+-- bare GA4 numeric property id ("365372770") rather than the API's
+-- "properties/365372770" resource name — the prefix is constant and is added
+-- back when calling the Admin/Data APIs. Kept on disconnect so reconnecting
+-- restores functionality without re-picking.
+
+ALTER TABLE public.brands ADD COLUMN ga_property_id text;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 94961d9e2..4c7958539 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -5149,3 +5149,18 @@ GRANT EXECUTE ON FUNCTION public.content_opportunity_aggregates(
text
) TO authenticated;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00051_brand_ga_property.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Brand → Google Analytics property mapping (#694).
+--
+-- Mirrors gsc_property (00046): the Analytics connection is org-level
+-- (integration_connections), the property choice is brand-level, and exactly
+-- one property per brand means a column beats a mapping table. Values are the
+-- bare GA4 numeric property id ("365372770") rather than the API's
+-- "properties/365372770" resource name — the prefix is constant and is added
+-- back when calling the Admin/Data APIs. Kept on disconnect so reconnecting
+-- restores functionality without re-picking.
+
+ALTER TABLE public.brands ADD COLUMN ga_property_id text;
+
diff --git a/web/src/components/settings/integrations-section.tsx b/web/src/components/settings/integrations-section.tsx
index df38f3e8c..c23d7cbc6 100644
--- a/web/src/components/settings/integrations-section.tsx
+++ b/web/src/components/settings/integrations-section.tsx
@@ -31,12 +31,13 @@ import {
getGscProperties,
getGscBrandMappings,
setBrandGscProperty,
+ getGaProperties,
+ getGaBrandMappings,
+ setBrandGaProperty,
type IntegrationProvider,
type IntegrationStatus,
- type GscProperty,
- type GscBrandMapping,
} from '@/lib/actions/integrations';
-import { matchGscProperty } from '@/lib/gsc';
+import { matchProperty } from '@/lib/property-match';
/**
* Settings → Integrations (#577, Google Analytics added in #658).
@@ -72,7 +73,9 @@ export function IntegrationsSection() {
description="Sessions and conversions from your GA4 property — the basis for AI traffic history without installing the tracking snippet."
icon={<BarChart3 className="h-5 w-5 text-muted-foreground" />}
authConfigEnv="COMPOSIO_GA_AUTH_CONFIG_ID"
- />
+ >
+ <GaPropertyMapping />
+ </IntegrationCard>
</CardContent>
</Card>
);
@@ -275,15 +278,50 @@ function IntegrationCard({
}
/**
- * 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.
+ * Brand → property mapping (#642, generalised for Analytics in #694).
+ *
+ * The connection is org-level; each brand picks exactly one property from it.
+ * Search Console and Analytics differ only in where a property's site URLs
+ * come from — a GSC property *is* a URL, a GA4 property is a numeric id whose
+ * URLs live on its web data streams — so both providers render this component
+ * and supply their own loaders. Brands whose domain matches exactly one
+ * property are premapped automatically; the picker always overrides.
*/
const NONE_VALUE = '__none__';
-function GscPropertyMapping() {
- const [properties, setProperties] = useState<GscProperty[] | null>(null);
- const [mappings, setMappings] = useState<GscBrandMapping[] | null>(null);
+interface PropertyOption {
+ /** Value persisted on the brand row. */
+ value: string;
+ /** Plain-text label — the trigger renders the selected item's text. */
+ label: string;
+ /** URLs this property covers, used for the domain auto-match. */
+ siteUrls: string[];
+}
+
+interface BrandPropertyRow {
+ brandId: string;
+ brandName: string;
+ value: string | null;
+ domains: string[];
+}
+
+function PropertyMapping({
+ sourceName,
+ description,
+ emptyMessage,
+ loadOptions,
+ loadRows,
+ save,
+}: {
+ sourceName: string;
+ description: string;
+ emptyMessage: string;
+ loadOptions: () => Promise<PropertyOption[]>;
+ loadRows: () => Promise<BrandPropertyRow[]>;
+ save: (brandId: string, value: string | null) => Promise<void>;
+}) {
+ const [options, setOptions] = useState<PropertyOption[] | null>(null);
+ const [rows, setRows] = useState<BrandPropertyRow[] | null>(null);
const [loadFailed, setLoadFailed] = useState<string | null>(null);
const [savingBrandId, setSavingBrandId] = useState<string | null>(null);
const autoMatched = useRef(false);
@@ -291,13 +329,13 @@ function GscPropertyMapping() {
const load = useCallback(async () => {
setLoadFailed(null);
try {
- const [props, brands] = await Promise.all([getGscProperties(), getGscBrandMappings()]);
- setProperties(props);
- setMappings(brands);
+ const [properties, brands] = await Promise.all([loadOptions(), loadRows()]);
+ setOptions(properties);
+ setRows(brands);
} catch (err) {
setLoadFailed(err instanceof Error ? err.message : 'Failed to load properties');
}
- }, []);
+ }, [loadOptions, loadRows]);
useEffect(() => {
load();
@@ -307,42 +345,35 @@ function GscPropertyMapping() {
// 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;
+ if (!options || !rows || 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);
+ for (const row of rows) {
+ if (row.value) continue;
+ const match = matchProperty(options, row.domains);
if (!match) continue;
try {
- await setBrandGscProperty(m.brandId, match);
- setMappings((prev) =>
- (prev ?? []).map((row) =>
- row.brandId === m.brandId ? { ...row, gscProperty: match } : row,
- ),
+ await save(row.brandId, match);
+ setRows((prev) =>
+ (prev ?? []).map((r) => (r.brandId === row.brandId ? { ...r, value: match } : r)),
);
} catch (err) {
- console.error('GSC auto-map failed:', err);
+ console.error(`${sourceName} auto-map failed:`, err);
return; // likely a permissions error — no point retrying the rest
}
}
})();
- }, [properties, mappings]);
+ }, [options, rows, save, sourceName]);
- const handlePick = async (brandId: string, value: string) => {
- const property = value === NONE_VALUE ? null : value;
- const previous = mappings;
+ const handlePick = async (brandId: string, picked: string) => {
+ const value = picked === NONE_VALUE ? null : picked;
+ const previous = rows;
setSavingBrandId(brandId);
- setMappings((prev) =>
- (prev ?? []).map((row) =>
- row.brandId === brandId ? { ...row, gscProperty: property } : row,
- ),
- );
+ setRows((prev) => (prev ?? []).map((r) => (r.brandId === brandId ? { ...r, value } : r)));
try {
- await setBrandGscProperty(brandId, property);
+ await save(brandId, value);
} catch (err) {
- setMappings(previous);
+ setRows(previous);
toast.error(err instanceof Error ? err.message : 'Failed to save property');
} finally {
setSavingBrandId(null);
@@ -352,7 +383,7 @@ function GscPropertyMapping() {
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="text-muted-foreground">Couldn&apos;t load {sourceName} properties.</p>
<p className="mt-1 text-xs text-muted-foreground">{loadFailed}</p>
<Button variant="outline" size="sm" className="mt-3" onClick={load}>
Retry
@@ -361,44 +392,49 @@ function GscPropertyMapping() {
);
}
- if (!properties || !mappings) {
+ if (!options || !rows) {
return <Skeleton className="h-24 w-full" />;
}
- const mappedCount = mappings.filter((m) => m.gscProperty).length;
+ const mappedCount = rows.filter((r) => r.value).length;
+ // The trigger renders the *value* unless the Select knows the value → label
+ // mapping. Search Console values are the label (a URL), but a GA4 value is a
+ // numeric id, which would otherwise show as a bare number once picked.
+ const selectItems = [
+ { value: NONE_VALUE, label: 'Not mapped' },
+ ...options.map((option) => ({ value: option.value, label: option.label })),
+ ];
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
+ {mappedCount} of {rows.length} brand{rows.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>
+ <p className="text-xs text-muted-foreground">{description}</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>
+ {rows.map((row) => (
+ <div key={row.brandId} className="flex items-center justify-between gap-3">
+ <span className="truncate text-sm">{row.brandName}</span>
<div className="flex items-center gap-2">
- {savingBrandId === m.brandId && (
+ {savingBrandId === row.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)}
+ items={selectItems}
+ value={row.value ?? null}
+ onValueChange={(v) => handlePick(row.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}
+ {options.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
</SelectItem>
))}
</SelectContent>
@@ -407,12 +443,73 @@ function GscPropertyMapping() {
</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>
- )}
+ {options.length === 0 && <p className="text-xs text-muted-foreground">{emptyMessage}</p>}
</div>
);
}
+
+// Loaders live at module scope so their identity is stable across renders —
+// PropertyMapping's effects depend on them.
+
+async function loadGscOptions(): Promise<PropertyOption[]> {
+ const properties = await getGscProperties();
+ return properties.map((p) => ({ value: p.siteUrl, label: p.siteUrl, siteUrls: [p.siteUrl] }));
+}
+
+async function loadGscRows(): Promise<BrandPropertyRow[]> {
+ const mappings = await getGscBrandMappings();
+ return mappings.map((m) => ({
+ brandId: m.brandId,
+ brandName: m.brandName,
+ value: m.gscProperty,
+ domains: m.domains,
+ }));
+}
+
+function GscPropertyMapping() {
+ return (
+ <PropertyMapping
+ sourceName="Search Console"
+ description="Pick which Search Console property each brand's data comes from. Brands matching a property by domain are mapped automatically."
+ emptyMessage="The connected account has no Search Console properties. Add your site in Search Console first, then retry."
+ loadOptions={loadGscOptions}
+ loadRows={loadGscRows}
+ save={setBrandGscProperty}
+ />
+ );
+}
+
+async function loadGaOptions(): Promise<PropertyOption[]> {
+ const properties = await getGaProperties();
+ return properties.map((p) => ({
+ value: p.propertyId,
+ // Display names repeat across accounts ("GA4"), so the id disambiguates.
+ label: p.accountName
+ ? `${p.displayName} · ${p.accountName} (${p.propertyId})`
+ : `${p.displayName} (${p.propertyId})`,
+ siteUrls: p.siteUrls,
+ }));
+}
+
+async function loadGaRows(): Promise<BrandPropertyRow[]> {
+ const mappings = await getGaBrandMappings();
+ return mappings.map((m) => ({
+ brandId: m.brandId,
+ brandName: m.brandName,
+ value: m.gaPropertyId,
+ domains: m.domains,
+ }));
+}
+
+function GaPropertyMapping() {
+ return (
+ <PropertyMapping
+ sourceName="Analytics"
+ description="Pick which GA4 property each brand's data comes from. Brands whose domain matches a property's web data stream are mapped automatically."
+ emptyMessage="The connected account has no GA4 properties. Create one in Google Analytics first, then retry."
+ loadOptions={loadGaOptions}
+ loadRows={loadGaRows}
+ save={setBrandGaProperty}
+ />
+ );
+}
diff --git a/web/src/lib/actions/integrations.ts b/web/src/lib/actions/integrations.ts
index ec93264eb..1545c6f63 100644
--- a/web/src/lib/actions/integrations.ts
+++ b/web/src/lib/actions/integrations.ts
@@ -110,3 +110,60 @@ export async function setBrandGscProperty(brandId: string, property: string | nu
.eq('id', brandId);
if (error) throw new Error(error.message);
}
+
+// ─── Google Analytics property mapping (#694) ────────────────────────────────
+
+export interface GaProperty {
+ /** Bare GA4 numeric id — the "properties/" prefix is added by the API layer. */
+ propertyId: string;
+ displayName: string;
+ accountName: string | null;
+ /** Site URLs from the property's web data streams; empty for app-only ones. */
+ siteUrls: string[];
+}
+
+export async function getGaProperties(): Promise<GaProperty[]> {
+ const res = await fetch(`${API_BASE_URL}/api/integrations/google-analytics/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 GaProperty[];
+}
+
+export interface GaBrandMapping {
+ brandId: string;
+ brandName: string;
+ gaPropertyId: string | null;
+ domains: string[];
+}
+
+/** Org brands with their domains and current GA property picks (RLS-scoped). */
+export async function getGaBrandMappings(): Promise<GaBrandMapping[]> {
+ const supabase = await createClient();
+ const { data, error } = await supabase
+ .from('brands')
+ .select('id, name, ga_property_id, 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,
+ gaPropertyId: b.ga_property_id,
+ domains: (b.brand_domains ?? []).map((d) => d.domain),
+ }));
+}
+
+/** Persist a brand's GA property pick (null clears it). RLS: admin/manager. */
+export async function setBrandGaProperty(
+ brandId: string,
+ propertyId: string | null,
+): Promise<void> {
+ const supabase = await createClient();
+ const { error } = await supabase
+ .from('brands')
+ .update({ ga_property_id: propertyId })
+ .eq('id', brandId);
+ if (error) throw new Error(error.message);
+}
diff --git a/web/src/lib/gsc.ts b/web/src/lib/gsc.ts
index 75485eb97..5707f1738 100644
--- a/web/src/lib/gsc.ts
+++ b/web/src/lib/gsc.ts
@@ -5,38 +5,22 @@
* 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.
+ *
+ * The matching itself is shared with the Google Analytics mapping (#694);
+ * this module only adapts GSC's "the property is the URL" shape to it.
*/
-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;
+import { matchProperty } from './property-match';
- 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;
-}
+export { propertyMatchesDomain } from './property-match';
/**
* 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 matchProperty(
+ propertyUrls.map((siteUrl) => ({ value: siteUrl, siteUrls: [siteUrl] })),
+ brandDomains,
);
- return matches.length === 1 ? matches[0] : null;
}
diff --git a/web/src/lib/property-match.test.ts b/web/src/lib/property-match.test.ts
new file mode 100644
index 000000000..dc8f38d56
--- /dev/null
+++ b/web/src/lib/property-match.test.ts
@@ -0,0 +1,37 @@
+import { describe, it, expect } from 'vitest';
+import { matchProperty } from './property-match';
+
+// propertyMatchesDomain is covered through the GSC adapter in gsc.test.ts;
+// these cases exercise what GA4 adds — a property carrying several site URLs.
+
+describe('matchProperty', () => {
+ it('matches a property through any of its site URLs', () => {
+ const properties = [
+ { value: '111', siteUrls: ['https://example.com', 'https://shop.example.com'] },
+ { value: '222', siteUrls: ['http://other.com'] },
+ ];
+ expect(matchProperty(properties, ['shop.example.com'])).toBe('111');
+ expect(matchProperty(properties, ['other.com'])).toBe('222');
+ });
+
+ it('ignores properties with no site URLs (app-only GA4 properties)', () => {
+ const properties = [
+ { value: '111', siteUrls: [] },
+ { value: '222', siteUrls: ['https://example.com'] },
+ ];
+ expect(matchProperty(properties, ['example.com'])).toBe('222');
+ expect(matchProperty(properties, ['nothing.com'])).toBeNull();
+ });
+
+ it('returns null when several properties match the same domain', () => {
+ const properties = [
+ { value: '111', siteUrls: ['https://example.com'] },
+ { value: '222', siteUrls: ['http://www.example.com'] },
+ ];
+ expect(matchProperty(properties, ['example.com'])).toBeNull();
+ });
+
+ it('returns null for a brand with no domains', () => {
+ expect(matchProperty([{ value: '111', siteUrls: ['https://example.com'] }], [])).toBeNull();
+ });
+});
diff --git a/web/src/lib/property-match.ts b/web/src/lib/property-match.ts
new file mode 100644
index 000000000..02247f7cf
--- /dev/null
+++ b/web/src/lib/property-match.ts
@@ -0,0 +1,55 @@
+/**
+ * Brand ↔ analytics property matching (#642, generalised for GA4 in #694).
+ *
+ * Both Search Console and Google Analytics let a brand be mapped to exactly
+ * one property, and both can guess that mapping from the brand's domains — the
+ * only difference is where the property's URL comes from. GSC properties *are*
+ * URLs ("https://www.example.com/" or "sc-domain:example.com"); a GA4 property
+ * is a numeric id whose site URLs live on its web data streams. Once both are
+ * expressed as a list of URLs per property, the matching is identical.
+ */
+
+function normalizeHost(value: string): string {
+ return value
+ .trim()
+ .toLowerCase()
+ .replace(/^https?:\/\//, '')
+ .replace(/\/.*$/, '')
+ .replace(/^www\./, '');
+}
+
+/** True when the property URL covers the given brand domain. */
+export function propertyMatchesDomain(siteUrl: string, domain: string): boolean {
+ const host = normalizeHost(domain);
+ if (!host) return false;
+
+ if (siteUrl.startsWith('sc-domain:')) {
+ // GSC 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;
+}
+
+/** A property reduced to what matching needs: its stored value and its URLs. */
+export interface MatchableProperty {
+ value: string;
+ siteUrls: string[];
+}
+
+/**
+ * The single property whose URLs match any of the brand's domains, or null
+ * when none or several match — ambiguity needs a human pick.
+ */
+export function matchProperty(
+ properties: MatchableProperty[],
+ brandDomains: string[],
+): string | null {
+ const matches = properties.filter((property) =>
+ property.siteUrls.some((siteUrl) =>
+ brandDomains.some((domain) => propertyMatchesDomain(siteUrl, domain)),
+ ),
+ );
+ return matches.length === 1 ? matches[0].value : null;
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index e90c78f79..32c677a58 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;
+ ga_property_id: string | null;
gsc_property: string | null;
industry: string | null;
is_active: boolean;
@@ -304,6 +305,7 @@ export type Database = {
created_at?: string;
description?: string | null;
id?: string;
+ ga_property_id?: string | null;
gsc_property?: string | null;
industry?: string | null;
is_active?: boolean;
@@ -322,6 +324,7 @@ export type Database = {
created_at?: string;
description?: string | null;
id?: string;
+ ga_property_id?: string | null;
gsc_property?: string | null;
industry?: string | null;
is_active?: boolean;