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): sync AI-sourced traffic, conversions and revenue from GA4 (#718)

Gökhan Geyik4a5fc81b90a2
diff --git a/server/src/lib/composio.js b/server/src/lib/composio.js
index 7fe98fd07..55d025545 100644
--- a/server/src/lib/composio.js
+++ b/server/src/lib/composio.js
@@ -234,3 +234,18 @@ export async function listGaProperties(entityId) {
return capped;
}
+
+/**
+ * Run a GA4 Data API report for a property (#704).
+ *
+ * `body` is a runReport request minus `property`, built by the caller — the
+ * dimensions, metrics and filters are deterministic, never model-generated.
+ * Returns the report as GA4 shapes it (`dimensionHeaders`, `metricHeaders`,
+ * `rows`, `rowCount`); parsing rows into storage is the sync's job.
+ */
+export async function runGaReport(entityId, propertyId, body) {
+ return executeGaTool('GOOGLE_ANALYTICS_RUN_REPORT', entityId, {
+ property: `properties/${propertyId}`,
+ ...body,
+ });
+}
diff --git a/server/src/lib/ga-sources.js b/server/src/lib/ga-sources.js
new file mode 100644
index 000000000..0e7260719
--- /dev/null
+++ b/server/src/lib/ga-sources.js
@@ -0,0 +1,72 @@
+/**
+ * GA4 session-source classification (#704).
+ *
+ * Deliberately an explicit list rather than a pattern. Real data from a
+ * connected property shows why both halves of that matter:
+ *
+ * - One engine arrives under several source strings. `chatgpt.com`,
+ * `chatgpt` and `openai` are the same product; a list keyed on the exact
+ * string collapses them without guessing.
+ * - Substring matching is actively wrong. A `*.workers.dev` subdomain with
+ * "claude" in its name showed up as an ordinary referrer — a `includes()`
+ * check would have booked it as AI traffic and inflated the number nobody
+ * can then verify.
+ *
+ * Values are the same host-style identifiers the tracking snippet records in
+ * ai_traffic_logs.source_platform, so the two origins name the same engine the
+ * same way. They are still counted separately everywhere — matching names is
+ * for comparison, never for summing.
+ */
+
+/**
+ * Raw GA4 `sessionSource` → platform. Keys are matched exactly after
+ * lowercasing and trimming; add observed variants here rather than loosening
+ * the match.
+ */
+export const GA_SOURCE_PLATFORMS = {
+ // OpenAI
+ 'chatgpt.com': 'chatgpt.com',
+ 'chat.openai.com': 'chatgpt.com',
+ 'search.chatgpt.com': 'chatgpt.com',
+ chatgpt: 'chatgpt.com',
+ openai: 'chatgpt.com',
+ 'openai.com': 'chatgpt.com',
+ // Perplexity
+ 'perplexity.ai': 'perplexity.ai',
+ 'www.perplexity.ai': 'perplexity.ai',
+ perplexity: 'perplexity.ai',
+ // Anthropic
+ 'claude.ai': 'claude.ai',
+ claude: 'claude.ai',
+ // Google
+ 'gemini.google.com': 'gemini.google.com',
+ gemini: 'gemini.google.com',
+ 'bard.google.com': 'gemini.google.com',
+ // Microsoft
+ 'copilot.microsoft.com': 'copilot.microsoft.com',
+ copilot: 'copilot.microsoft.com',
+ // Others the snippet already knows about
+ 'you.com': 'you.com',
+ 'phind.com': 'phind.com',
+ 'meta.ai': 'meta.ai',
+ 'poe.com': 'poe.com',
+ // Newer assistants, listed before they show up rather than after
+ 'grok.com': 'grok.com',
+ grok: 'grok.com',
+ 'deepseek.com': 'deepseek.com',
+ 'chat.deepseek.com': 'deepseek.com',
+ deepseek: 'deepseek.com',
+};
+
+/** Every raw source string worth asking GA4 for. */
+export const GA_AI_SOURCE_VALUES = Object.keys(GA_SOURCE_PLATFORMS);
+
+/**
+ * The platform behind a raw GA4 source string, or null when unrecognised.
+ * Unrecognised is a normal outcome — the caller stores the raw value so the
+ * list above can grow from what customers actually receive.
+ */
+export function classifyGaSource(raw) {
+ if (typeof raw !== 'string') return null;
+ return GA_SOURCE_PLATFORMS[raw.trim().toLowerCase()] ?? null;
+}
diff --git a/server/src/lib/ga-sync.js b/server/src/lib/ga-sync.js
new file mode 100644
index 000000000..157e1ec2f
--- /dev/null
+++ b/server/src/lib/ga-sync.js
@@ -0,0 +1,460 @@
+/**
+ * Daily Google Analytics sync (#704).
+ *
+ * For every active brand mapped to a GA4 property (#694) whose org connection
+ * is live, pulls three reports through Composio and upserts them:
+ *
+ * ga_ai_traffic_stats AI-sourced sessions per landing page
+ * ga_page_stats landing-page totals across every source
+ * ga_item_stats product rows, when the property has ecommerce
+ *
+ * Parameters are fully deterministic — no LLM anywhere in this path. Per-brand
+ * failures are logged and skipped; one broken property never aborts the run.
+ *
+ * Unlike Search Console, GA4 has no multi-day reporting lag, so there is no
+ * fixed offset to wait out. It does revise recent figures, which is why every
+ * run rewrites the last few days rather than only appending yesterday.
+ */
+
+import supabaseAdmin from '../config/supabase.js';
+import { isComposioConfigured, runGaReport } from './composio.js';
+import { GA_AI_SOURCE_VALUES, classifyGaSource } from './ga-sources.js';
+import { logger } from './logger.js';
+
+/** First sync pulls this much history; later runs only refresh the tail. */
+const BACKFILL_DAYS = 90;
+/** GA4 revises recent data, so each run rewrites this many days. */
+const REFRESH_DAYS = 3;
+const UPSERT_CHUNK = 500;
+/**
+ * Long enough for year-over-year comparisons once a surface wants them, while
+ * still bounding growth.
+ */
+const RETENTION_DAYS = 400;
+
+/**
+ * Pages kept per day. A large shop can have tens of thousands of pages taking
+ * traffic daily; storing all of them would mean millions of rows per brand,
+ * almost all of it single-session noise that no ranking of commercial value
+ * would surface. The ordering below makes the cut safe rather than arbitrary.
+ */
+const PAGE_DAILY_LIMIT = 5000;
+/** Same reasoning for a catalogue with tens of thousands of SKUs. */
+const ITEM_DAILY_LIMIT = 5000;
+/** Days fetched at once during a backfill. GA4 allows 10 concurrent requests. */
+const DAY_CONCURRENCY = 4;
+
+/**
+ * Order pages so the daily ceiling can never drop a page that earns money.
+ *
+ * Sorting by sessions alone would cut a page with three sessions and two
+ * purchases the moment five thousand busier pages exist — and that page is
+ * precisely the one worth finding. Transactions rank first, then other key
+ * events, and only then volume.
+ */
+const PAGE_ORDER = [
+ { desc: true, metric: { metricName: 'transactions' } },
+ { desc: true, metric: { metricName: 'keyEvents' } },
+ { desc: true, metric: { metricName: 'sessions' } },
+];
+
+/** Same guarantee for products: whatever sold outranks whatever was browsed. */
+const ITEM_ORDER = [
+ { desc: true, metric: { metricName: 'itemsPurchased' } },
+ { desc: true, metric: { metricName: 'itemsViewed' } },
+];
+
+const TRAFFIC_METRICS = [
+ 'sessions',
+ 'engagedSessions',
+ 'keyEvents',
+ 'totalUsers',
+ 'transactions',
+ 'purchaseRevenue',
+ 'userEngagementDuration',
+];
+
+const ITEM_METRICS = ['itemsViewed', 'itemsAddedToCart', 'itemsPurchased', 'itemRevenue'];
+
+/** YYYY-MM-DD in UTC, `daysAgo` days before now. */
+export function utcDateString(daysAgo = 0) {
+ return new Date(Date.now() - daysAgo * 86_400_000).toISOString().slice(0, 10);
+}
+
+/** GA4 returns dates as "20260721"; storage wants "2026-07-21". */
+export function gaDateToIso(raw) {
+ const value = String(raw ?? '');
+ if (!/^\d{8}$/.test(value)) return null;
+ return `${value.slice(0, 4)}-${value.slice(4, 6)}-${value.slice(6, 8)}`;
+}
+
+function toInt(value) {
+ const n = Number(value);
+ return Number.isFinite(n) ? Math.round(n) : 0;
+}
+
+function toFloat(value) {
+ const n = Number(value);
+ return Number.isFinite(n) ? n : 0;
+}
+
+/**
+ * Rows as `{ dimensionName: value, metricName: value }` objects.
+ *
+ * Reading by header name rather than by position: GA4 is documented to echo
+ * the requested order, but a silently reordered response would otherwise
+ * write sessions into the revenue column, and nothing downstream could tell.
+ */
+export function readReportRows(report) {
+ const dimNames = (report?.dimensionHeaders ?? []).map((h) => h.name);
+ const metricNames = (report?.metricHeaders ?? []).map((h) => h.name);
+
+ return (report?.rows ?? []).map((row) => {
+ const out = {};
+ (row.dimensionValues ?? []).forEach((v, i) => {
+ if (dimNames[i]) out[dimNames[i]] = v?.value ?? '';
+ });
+ (row.metricValues ?? []).forEach((v, i) => {
+ if (metricNames[i]) out[metricNames[i]] = v?.value ?? '0';
+ });
+ return out;
+ });
+}
+
+function trafficMetricColumns(row) {
+ return {
+ sessions: toInt(row.sessions),
+ engaged_sessions: toInt(row.engagedSessions),
+ key_events: toInt(row.keyEvents),
+ total_users: toInt(row.totalUsers),
+ transactions: toInt(row.transactions),
+ purchase_revenue: toFloat(row.purchaseRevenue),
+ engagement_duration_seconds: toInt(row.userEngagementDuration),
+ };
+}
+
+/** AI-sourced rows → ga_ai_traffic_stats. Rows without a date are dropped. */
+export function mapAiTrafficRows(brandId, report) {
+ const mapped = [];
+ for (const row of readReportRows(report)) {
+ const date = gaDateToIso(row.date);
+ if (!date) continue;
+ const source = row.sessionSource ?? '';
+ mapped.push({
+ brand_id: brandId,
+ date,
+ source,
+ platform: classifyGaSource(source),
+ // Path for joining the page totals, full URL for attribution.
+ landing_page: row.landingPage ?? '',
+ landing_page_query: row.landingPagePlusQueryString ?? '',
+ ...trafficMetricColumns(row),
+ });
+ }
+ return mapped;
+}
+
+/** Landing-page totals → ga_page_stats. */
+export function mapPageRows(brandId, report) {
+ const mapped = [];
+ for (const row of readReportRows(report)) {
+ const date = gaDateToIso(row.date);
+ if (!date) continue;
+ mapped.push({
+ brand_id: brandId,
+ date,
+ landing_page: row.landingPage ?? '',
+ ...trafficMetricColumns(row),
+ });
+ }
+ return mapped;
+}
+
+/** Product rows → ga_item_stats. */
+export function mapItemRows(brandId, report) {
+ const mapped = [];
+ for (const row of readReportRows(report)) {
+ const date = gaDateToIso(row.date);
+ if (!date) continue;
+ mapped.push({
+ brand_id: brandId,
+ date,
+ item_id: row.itemId ?? '',
+ item_name: row.itemName ?? '',
+ item_category: row.itemCategory ?? '',
+ items_viewed: toInt(row.itemsViewed),
+ items_added_to_cart: toInt(row.itemsAddedToCart),
+ items_purchased: toInt(row.itemsPurchased),
+ item_revenue: toFloat(row.itemRevenue),
+ });
+ }
+ return mapped;
+}
+
+/**
+ * Sources GA4 reported that the classification list does not know, ordered by
+ * sessions. Logged rather than stored: the point is to notice a new assistant
+ * showing up in real traffic and extend ga-sources.js deliberately, not to
+ * accumulate every referrer a site ever sees.
+ */
+export function unclassifiedSources(report, { minSessions = 1, limit = 10 } = {}) {
+ return readReportRows(report)
+ .filter((row) => !classifyGaSource(row.sessionSource) && toInt(row.sessions) >= minSessions)
+ .map((row) => ({ source: row.sessionSource ?? '', sessions: toInt(row.sessions) }))
+ .sort((a, b) => b.sessions - a.sessions)
+ .slice(0, limit);
+}
+
+async function upsertAll(table, rows, onConflict) {
+ for (let i = 0; i < rows.length; i += UPSERT_CHUNK) {
+ const { error } = await supabaseAdmin
+ .from(table)
+ .upsert(rows.slice(i, i + UPSERT_CHUNK), { onConflict });
+ if (error) throw new Error(`Upsert into ${table} failed: ${error.message}`);
+ }
+}
+
+/** The days a run covers, newest first, as YYYY-MM-DD. */
+export function dayRange(days) {
+ return Array.from({ length: days + 1 }, (_, i) => utcDateString(i));
+}
+
+/**
+ * Run `task` over `items` with a small concurrency window. Backfilling 90 days
+ * one request at a time would take minutes per brand for no reason; GA4 allows
+ * ten concurrent requests per property and this stays well under it.
+ */
+async function mapWithConcurrency(items, limit, task) {
+ const results = [];
+ for (let i = 0; i < items.length; i += limit) {
+ results.push(...(await Promise.all(items.slice(i, i + limit).map(task))));
+ }
+ return results;
+}
+
+/**
+ * Fetch one day of a report and upsert it. Returns the row count, and whether
+ * the day filled its ceiling — a day that did was truncated, and the caller
+ * says so rather than letting it pass as complete data.
+ */
+async function syncDay({
+ brand,
+ entityId,
+ date,
+ dimensions,
+ metrics,
+ orderBys,
+ limit,
+ map,
+ table,
+ onConflict,
+}) {
+ const report = await runGaReport(entityId, brand.ga_property_id, {
+ dateRanges: [{ startDate: date, endDate: date }],
+ dimensions,
+ metrics,
+ orderBys,
+ limit,
+ });
+
+ const rows = map(brand.id, report);
+ if (rows.length) await upsertAll(table, rows, onConflict);
+ return { stored: rows.length, truncated: (report?.rowCount ?? 0) > limit };
+}
+
+/** True when this brand has never been synced, so the first run backfills. */
+async function isFirstSync(brandId) {
+ const { data, error } = await supabaseAdmin
+ .from('ga_page_stats')
+ .select('id')
+ .eq('brand_id', brandId)
+ .limit(1);
+ // On a failed read, refresh the short window rather than re-pulling 90 days.
+ if (error) return false;
+ return (data ?? []).length === 0;
+}
+
+/**
+ * Run a per-day report across `days`, reporting how many rows were stored and
+ * on how many days the ceiling was reached.
+ *
+ * Per day rather than one call for the whole window, because the ceiling has
+ * to mean "the top pages of that day". Applied to a 90-day range it would mean
+ * "the top pages of the whole quarter", which on a large property is less than
+ * a single day's worth and silently biases everything computed from it.
+ */
+async function syncDays({ brand, entityId, days, label, ...report }) {
+ const outcomes = await mapWithConcurrency(days, DAY_CONCURRENCY, (date) =>
+ syncDay({ brand, entityId, date, ...report }),
+ );
+
+ const stored = outcomes.reduce((sum, o) => sum + o.stored, 0);
+ const truncatedDays = outcomes.filter((o) => o.truncated).length;
+ if (truncatedDays > 0) {
+ logger.warn(
+ { brandId: brand.id, label, truncatedDays, limit: report.limit, stored },
+ '[ga-sync] daily ceiling reached — long tail not stored for these days',
+ );
+ }
+ return stored;
+}
+
+async function syncBrand(brand) {
+ const entityId = `org_${brand.organization_id}`;
+ const first = await isFirstSync(brand.id);
+ const days = dayRange(first ? BACKFILL_DAYS : REFRESH_DAYS);
+ const dateRanges = [{ startDate: days[days.length - 1], endDate: days[0] }];
+ const metrics = TRAFFIC_METRICS.map((name) => ({ name }));
+
+ // The AI slice is small enough to take in one call — a live property
+ // produced 96 rows over 90 days — so it keeps the full entry URL and needs
+ // no ceiling.
+ const aiReport = await runGaReport(entityId, brand.ga_property_id, {
+ dateRanges,
+ dimensions: [
+ { name: 'date' },
+ { name: 'sessionSource' },
+ { name: 'landingPage' },
+ { name: 'landingPagePlusQueryString' },
+ ],
+ metrics,
+ // An explicit value list, not a pattern — see ga-sources.js for why.
+ dimensionFilter: {
+ filter: {
+ fieldName: 'sessionSource',
+ inListFilter: { values: GA_AI_SOURCE_VALUES, caseSensitive: false },
+ },
+ },
+ orderBys: PAGE_ORDER,
+ limit: 100_000,
+ });
+ const aiMapped = mapAiTrafficRows(brand.id, aiReport);
+ if (aiMapped.length) {
+ await upsertAll('ga_ai_traffic_stats', aiMapped, 'brand_id,date,source,landing_page_query');
+ }
+ const aiRows = aiMapped.length;
+
+ const pageRows = await syncDays({
+ brand,
+ entityId,
+ days,
+ label: 'pages',
+ table: 'ga_page_stats',
+ onConflict: 'brand_id,date,landing_page',
+ map: mapPageRows,
+ dimensions: [{ name: 'date' }, { name: 'landingPage' }],
+ metrics,
+ orderBys: PAGE_ORDER,
+ limit: PAGE_DAILY_LIMIT,
+ });
+
+ // Ecommerce is optional. A property without it returns no rows, and a
+ // property that rejects the item dimensions must not fail the whole brand —
+ // the traffic tables above are already written by this point.
+ let itemRows = 0;
+ try {
+ itemRows = await syncDays({
+ brand,
+ entityId,
+ days,
+ label: 'items',
+ table: 'ga_item_stats',
+ onConflict: 'brand_id,date,item_id,item_name',
+ map: mapItemRows,
+ dimensions: [
+ { name: 'date' },
+ { name: 'itemName' },
+ { name: 'itemId' },
+ { name: 'itemCategory' },
+ ],
+ metrics: ITEM_METRICS.map((name) => ({ name })),
+ orderBys: ITEM_ORDER,
+ limit: ITEM_DAILY_LIMIT,
+ });
+ } catch (err) {
+ logger.info(
+ { brandId: brand.id, err: err.message },
+ '[ga-sync] item report unavailable — property has no ecommerce data',
+ );
+ }
+
+ // Source discovery: one cheap call (no page dimension) over the same window
+ // so a newly popular assistant shows up in the logs instead of silently
+ // failing the inList filter above forever.
+ try {
+ const report = await runGaReport(entityId, brand.ga_property_id, {
+ dateRanges,
+ dimensions: [{ name: 'sessionSource' }],
+ metrics: [{ name: 'sessions' }],
+ orderBys: [{ desc: true, metric: { metricName: 'sessions' } }],
+ limit: 500,
+ });
+ const unknown = unclassifiedSources(report);
+ if (unknown.length) {
+ logger.debug({ brandId: brand.id, unknown }, '[ga-sync] unclassified sources observed');
+ }
+ } catch (err) {
+ logger.debug({ brandId: brand.id, err: err.message }, '[ga-sync] source discovery failed');
+ }
+
+ return { first, aiRows, pageRows, itemRows };
+}
+
+async function prune(table) {
+ const { error } = await supabaseAdmin
+ .from(table)
+ .delete()
+ .lt('date', utcDateString(RETENTION_DAYS));
+ if (error) logger.warn({ err: error, table }, '[ga-sync] retention prune failed');
+}
+
+/**
+ * Sync every eligible brand; optionally scoped to one organization (the
+ * manual trigger). Returns per-brand counts.
+ */
+export async function runGaSync({ organizationId } = {}) {
+ if (!isComposioConfigured('google-analytics')) return { synced: 0, skipped: 0, results: [] };
+
+ // Orgs with a live connection…
+ let connQuery = supabaseAdmin
+ .from('integration_connections')
+ .select('organization_id')
+ .eq('provider', 'google-analytics')
+ .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, ga_property_id')
+ .eq('is_active', true)
+ .not('ga_property_id', '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 counts = await syncBrand(brand);
+ results.push({ brandId: brand.id, ...counts });
+ synced++;
+ } catch (err) {
+ logger.error({ err, brandId: brand.id }, '[ga-sync] brand sync failed');
+ results.push({ brandId: brand.id, error: err.message });
+ skipped++;
+ }
+ }
+
+ for (const table of ['ga_ai_traffic_stats', 'ga_page_stats', 'ga_item_stats']) {
+ await prune(table);
+ }
+
+ logger.info({ synced, skipped, total: (brands || []).length }, '[ga-sync] completed');
+ return { synced, skipped, results };
+}
diff --git a/server/src/lib/ga-sync.test.js b/server/src/lib/ga-sync.test.js
new file mode 100644
index 000000000..d8d0f2e34
--- /dev/null
+++ b/server/src/lib/ga-sync.test.js
@@ -0,0 +1,303 @@
+import { describe, expect, it, vi } from 'vitest';
+
+// The module imports the supabase admin client, whose config hard-exits when
+// SUPABASE_* env is absent (as in CI) — stub it before the import chain.
+vi.mock('../config/supabase.js', () => ({ default: {} }));
+
+import { classifyGaSource } from './ga-sources.js';
+import {
+ dayRange,
+ gaDateToIso,
+ mapAiTrafficRows,
+ mapItemRows,
+ mapPageRows,
+ readReportRows,
+ unclassifiedSources,
+} from './ga-sync.js';
+
+/**
+ * GA4 traffic sync mapping (#704).
+ *
+ * Everything here is the part of the sync that turns a GA4 report into rows —
+ * the half that can be wrong without anything failing, since a mis-parsed
+ * report still upserts cleanly and only shows up as numbers nobody can
+ * reconcile later.
+ */
+
+const report = ({ dims, metrics, rows }) => ({
+ dimensionHeaders: dims.map((name) => ({ name })),
+ metricHeaders: metrics.map((name) => ({ name })),
+ rows: rows.map((row) => ({
+ dimensionValues: row.slice(0, dims.length).map((value) => ({ value })),
+ metricValues: row.slice(dims.length).map((value) => ({ value })),
+ })),
+});
+
+const TRAFFIC_METRICS = [
+ 'sessions',
+ 'engagedSessions',
+ 'keyEvents',
+ 'totalUsers',
+ 'transactions',
+ 'purchaseRevenue',
+ 'userEngagementDuration',
+];
+
+describe('classifyGaSource', () => {
+ it('collapses an engine’s several source strings onto one platform', () => {
+ // All three arrive from the same product in real data.
+ expect(classifyGaSource('chatgpt.com')).toBe('chatgpt.com');
+ expect(classifyGaSource('chatgpt')).toBe('chatgpt.com');
+ expect(classifyGaSource('openai')).toBe('chatgpt.com');
+ });
+
+ it('matches case-insensitively and ignores surrounding whitespace', () => {
+ expect(classifyGaSource(' Perplexity.AI ')).toBe('perplexity.ai');
+ });
+
+ it('does not match a host that merely contains an engine name', () => {
+ // The case that motivated an explicit list: a workers.dev subdomain with
+ // "claude" in it is an ordinary referrer, not AI traffic.
+ expect(classifyGaSource('claude-proxy.example.workers.dev')).toBeNull();
+ expect(classifyGaSource('notchatgpt.com')).toBeNull();
+ });
+
+ it('returns null for GA placeholders and non-strings', () => {
+ expect(classifyGaSource('(direct)')).toBeNull();
+ expect(classifyGaSource('(not set)')).toBeNull();
+ expect(classifyGaSource(undefined)).toBeNull();
+ });
+});
+
+describe('gaDateToIso', () => {
+ it('converts GA4’s compact date to a storable one', () => {
+ expect(gaDateToIso('20260721')).toBe('2026-07-21');
+ });
+
+ it('rejects anything that is not eight digits', () => {
+ expect(gaDateToIso('2026-07-21')).toBeNull();
+ expect(gaDateToIso('(other)')).toBeNull();
+ expect(gaDateToIso(undefined)).toBeNull();
+ });
+});
+
+describe('readReportRows', () => {
+ it('reads values by header name rather than by position', () => {
+ // GA4 echoes the requested order, but reading positionally would write
+ // sessions into the revenue column if it ever stopped doing so, and
+ // nothing downstream could tell.
+ const swapped = report({
+ dims: ['date'],
+ metrics: ['purchaseRevenue', 'sessions'],
+ rows: [['20260721', '99.5', '4']],
+ });
+
+ expect(readReportRows(swapped)[0]).toEqual({
+ date: '20260721',
+ purchaseRevenue: '99.5',
+ sessions: '4',
+ });
+ });
+
+ it('returns an empty list for a report with no rows', () => {
+ expect(readReportRows({ dimensionHeaders: [], metricHeaders: [] })).toEqual([]);
+ expect(readReportRows(undefined)).toEqual([]);
+ });
+});
+
+describe('mapAiTrafficRows', () => {
+ const AI_DIMS = ['date', 'sessionSource', 'landingPage', 'landingPagePlusQueryString'];
+ const raw = report({
+ dims: AI_DIMS,
+ metrics: TRAFFIC_METRICS,
+ rows: [
+ [
+ '20260721',
+ 'chatgpt.com',
+ '/pricing',
+ '/pricing?ref=x',
+ '10',
+ '3',
+ '1',
+ '9',
+ '2',
+ '149.9',
+ '106',
+ ],
+ ],
+ });
+
+ it('maps a row onto its storage columns', () => {
+ expect(mapAiTrafficRows('brand-1', raw)).toEqual([
+ {
+ brand_id: 'brand-1',
+ date: '2026-07-21',
+ source: 'chatgpt.com',
+ platform: 'chatgpt.com',
+ landing_page: '/pricing',
+ landing_page_query: '/pricing?ref=x',
+ sessions: 10,
+ engaged_sessions: 3,
+ key_events: 1,
+ total_users: 9,
+ transactions: 2,
+ purchase_revenue: 149.9,
+ engagement_duration_seconds: 106,
+ },
+ ]);
+ });
+
+ it('keeps the path separately from the full entry URL', () => {
+ // The path is what joins ga_page_stats, which drops query strings to stay
+ // a manageable size; the full URL is what attribution needs.
+ const [row] = mapAiTrafficRows('brand-1', raw);
+ expect(row.landing_page).toBe('/pricing');
+ expect(row.landing_page_query).toBe('/pricing?ref=x');
+ });
+
+ it('keeps the raw source when it cannot be classified', () => {
+ const unknown = report({
+ dims: AI_DIMS,
+ metrics: TRAFFIC_METRICS,
+ rows: [['20260721', 'some-new-assistant.ai', '/', '/', '3', '1', '0', '3', '0', '0', '12']],
+ });
+
+ const [row] = mapAiTrafficRows('brand-1', unknown);
+ expect(row.source).toBe('some-new-assistant.ai');
+ expect(row.platform).toBeNull();
+ });
+
+ it('keeps an empty landing page instead of dropping the row', () => {
+ // GA4 reports a blank landing page for sessions it cannot attribute to
+ // one; those sessions still happened.
+ const blank = report({
+ dims: AI_DIMS,
+ metrics: TRAFFIC_METRICS,
+ rows: [['20260721', 'chatgpt.com', '', '', '5', '2', '0', '5', '0', '0', '30']],
+ });
+
+ expect(mapAiTrafficRows('brand-1', blank)[0].landing_page).toBe('');
+ });
+
+ it('drops rows whose date is unusable rather than storing a null date', () => {
+ const broken = report({
+ dims: AI_DIMS,
+ metrics: TRAFFIC_METRICS,
+ rows: [['(other)', 'chatgpt.com', '/', '/', '5', '2', '0', '5', '0', '0', '30']],
+ });
+
+ expect(mapAiTrafficRows('brand-1', broken)).toEqual([]);
+ });
+
+ it('treats missing or non-numeric metrics as zero', () => {
+ const messy = report({
+ dims: AI_DIMS,
+ metrics: TRAFFIC_METRICS,
+ rows: [['20260721', 'chatgpt.com', '/', '/', '4', '', 'n/a', '4', '', '', '']],
+ });
+
+ const [row] = mapAiTrafficRows('brand-1', messy);
+ expect(row.sessions).toBe(4);
+ expect(row.key_events).toBe(0);
+ expect(row.purchase_revenue).toBe(0);
+ });
+});
+
+describe('mapPageRows', () => {
+ it('maps landing-page totals without a source column', () => {
+ const raw = report({
+ dims: ['date', 'landingPage'],
+ metrics: TRAFFIC_METRICS,
+ rows: [['20260810', '/', '29', '21', '2', '23', '1', '80', '3407']],
+ });
+
+ expect(mapPageRows('brand-1', raw)).toEqual([
+ {
+ brand_id: 'brand-1',
+ date: '2026-08-10',
+ landing_page: '/',
+ sessions: 29,
+ engaged_sessions: 21,
+ key_events: 2,
+ total_users: 23,
+ transactions: 1,
+ purchase_revenue: 80,
+ engagement_duration_seconds: 3407,
+ },
+ ]);
+ });
+});
+
+describe('mapItemRows', () => {
+ it('maps product rows', () => {
+ const raw = report({
+ dims: ['date', 'itemName', 'itemId', 'itemCategory'],
+ metrics: ['itemsViewed', 'itemsAddedToCart', 'itemsPurchased', 'itemRevenue'],
+ rows: [['20260721', 'Blue Shirt', 'SKU-1', 'Apparel', '40', '7', '3', '89.7']],
+ });
+
+ expect(mapItemRows('brand-1', raw)).toEqual([
+ {
+ brand_id: 'brand-1',
+ date: '2026-07-21',
+ item_id: 'SKU-1',
+ item_name: 'Blue Shirt',
+ item_category: 'Apparel',
+ items_viewed: 40,
+ items_added_to_cart: 7,
+ items_purchased: 3,
+ item_revenue: 89.7,
+ },
+ ]);
+ });
+
+ it('returns nothing for a property without ecommerce, which is not an error', () => {
+ expect(mapItemRows('brand-1', { dimensionHeaders: [], metricHeaders: [], rows: [] })).toEqual(
+ [],
+ );
+ });
+});
+
+describe('dayRange', () => {
+ it('covers today plus the requested number of days back, newest first', () => {
+ const days = dayRange(3);
+ expect(days).toHaveLength(4);
+ expect(new Date(days[0]).getTime()).toBeGreaterThan(new Date(days[3]).getTime());
+ });
+
+ it('still returns today when asked for zero days back', () => {
+ expect(dayRange(0)).toHaveLength(1);
+ });
+
+ it('returns each day exactly once, so no day is fetched twice', () => {
+ const days = dayRange(90);
+ expect(new Set(days).size).toBe(91);
+ });
+});
+
+describe('unclassifiedSources', () => {
+ const raw = report({
+ dims: ['sessionSource'],
+ metrics: ['sessions'],
+ rows: [
+ ['(direct)', '1477'],
+ ['google', '367'],
+ ['chatgpt.com', '47'],
+ ['some-new-assistant.ai', '9'],
+ ],
+ });
+
+ it('reports unknown sources ordered by sessions, excluding known ones', () => {
+ expect(unclassifiedSources(raw, { limit: 3 })).toEqual([
+ { source: '(direct)', sessions: 1477 },
+ { source: 'google', sessions: 367 },
+ { source: 'some-new-assistant.ai', sessions: 9 },
+ ]);
+ });
+
+ it('honours the session floor', () => {
+ expect(unclassifiedSources(raw, { minSessions: 400 })).toEqual([
+ { source: '(direct)', sessions: 1477 },
+ ]);
+ });
+});
diff --git a/server/src/routes/integrations.js b/server/src/routes/integrations.js
index cb660a02b..63adaf214 100644
--- a/server/src/routes/integrations.js
+++ b/server/src/routes/integrations.js
@@ -11,6 +11,7 @@ import {
listGaProperties,
} from '../lib/composio.js';
import { runGscSync } from '../lib/gsc-sync.js';
+import { runGaSync } from '../lib/ga-sync.js';
const router = Router();
@@ -295,4 +296,26 @@ router.get('/google-analytics/properties', async (req, res) => {
}
});
+/**
+ * POST /api/integrations/google-analytics/sync
+ * Runs the traffic sync for the caller's org immediately (#704) — testing and
+ * first-time backfill; the daily cycle runs the same sync.
+ */
+router.post('/google-analytics/sync', async (req, res) => {
+ try {
+ if (!isComposioConfigured(GA)) return notConfigured(res, GA);
+
+ 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 runGaSync({ organizationId: profile.organization_id });
+ return res.json(result);
+ } catch (err) {
+ req.log.error({ err }, 'integrations GA sync error');
+ return res.status(err.status || 500).json({ error: err.message });
+ }
+});
+
export default router;
diff --git a/server/src/server.js b/server/src/server.js
index 9540971e1..cd632a082 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -31,6 +31,7 @@ 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';
+import { runGaSync } from './lib/ga-sync.js';
import { runPulseCatchUp } from './lib/pulse/engine.js';
const app = express();
@@ -186,6 +187,13 @@ async function runDailyTracking() {
logger.error({ err }, '[gsc-sync] daily run failed');
});
+ // Google Analytics sync (#704) — same contract as the Search Console sync
+ // above: independent, never blocks or fails the tracking run, no-ops when
+ // Composio or the Analytics auth config isn't set.
+ runGaSync().catch((err) => {
+ logger.error({ err }, '[ga-sync] daily run failed');
+ });
+
return { triggered, total: brands.length };
}
diff --git a/supabase/migrations/00053_ga_traffic_stats.sql b/supabase/migrations/00053_ga_traffic_stats.sql
new file mode 100644
index 000000000..3385d5083
--- /dev/null
+++ b/supabase/migrations/00053_ga_traffic_stats.sql
@@ -0,0 +1,156 @@
+-- Google Analytics traffic sync (#704) — daily GA4 rows pulled through the
+-- Composio connection for every brand mapped to a property (#694).
+--
+-- Three tables rather than one, because they answer different questions and
+-- must never be added together:
+--
+-- ga_ai_traffic_stats what AI sources brought, per landing page
+-- ga_page_stats what a landing page is worth in total, all sources
+-- ga_item_stats what actually sold, product-scoped
+--
+-- The first two overlap by design: the AI table is a slice of the same
+-- traffic the page table totals. Summing them double-counts, which is the
+-- same trap this integration already avoids with ai_traffic_logs (our own
+-- snippet counts these visits a second time). Nothing in the pipeline joins
+-- or sums across origins; how the numbers are presented together is a
+-- decision for the surface phase.
+--
+-- Writes are service-role upserts keyed on the natural grain, so re-running a
+-- day rewrites it instead of duplicating. Org members read.
+
+-- ── AI-sourced traffic, by landing page ─────────────────────────────────────
+--
+-- `source` keeps GA4's raw sessionSource string and `platform` the normalised
+-- name. The raw value is not redundant: one engine arrives under several
+-- source strings, and keeping what was actually observed is what lets the
+-- classification list be extended from real data instead of guesswork.
+--
+-- Two page columns on purpose. `landing_page_query` is the full entry URL,
+-- which is what attribution needs — this table is small enough to afford the
+-- cardinality (a live property produced 96 rows over 90 days). `landing_page`
+-- drops the query string so it joins the page totals below, which cannot
+-- afford it: on the same property the query string multiplied distinct pages
+-- by 8.8, and a shop with faceted filters is far worse.
+CREATE TABLE public.ga_ai_traffic_stats (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ brand_id uuid NOT NULL REFERENCES public.brands(id) ON DELETE CASCADE,
+ date date NOT NULL,
+ source text NOT NULL,
+ platform text,
+ landing_page text NOT NULL DEFAULT '',
+ landing_page_query text NOT NULL DEFAULT '',
+ sessions integer NOT NULL DEFAULT 0,
+ engaged_sessions integer NOT NULL DEFAULT 0,
+ key_events integer NOT NULL DEFAULT 0,
+ total_users integer NOT NULL DEFAULT 0,
+ transactions integer NOT NULL DEFAULT 0,
+ purchase_revenue double precision NOT NULL DEFAULT 0,
+ engagement_duration_seconds integer NOT NULL DEFAULT 0,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (brand_id, date, source, landing_page_query)
+);
+
+CREATE INDEX ga_ai_traffic_stats_brand_page_idx
+ ON public.ga_ai_traffic_stats (brand_id, landing_page);
+
+CREATE INDEX ga_ai_traffic_stats_brand_date_idx
+ ON public.ga_ai_traffic_stats (brand_id, date DESC);
+
+-- ── Landing-page totals, every source ───────────────────────────────────────
+--
+-- "How much is this page worth to the business" cannot be answered from the
+-- AI slice: a page that converts well overall is the interesting one when its
+-- AI visibility is weak, and that comparison needs the page's full figures.
+--
+-- This is the table that grows: one row per page per day, and a large shop
+-- can have tens of thousands of pages taking traffic on any given day. Two
+-- things bound it — the path without its query string, and a per-day ceiling
+-- on how many pages are kept (PAGE_DAILY_LIMIT in ga-sync.js). Pages are
+-- ordered so anything converting survives the cut whatever its session count;
+-- what gets dropped is the one-session tail, which no ranking of commercial
+-- value would have surfaced anyway.
+CREATE TABLE public.ga_page_stats (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ brand_id uuid NOT NULL REFERENCES public.brands(id) ON DELETE CASCADE,
+ date date NOT NULL,
+ landing_page text NOT NULL DEFAULT '',
+ sessions integer NOT NULL DEFAULT 0,
+ engaged_sessions integer NOT NULL DEFAULT 0,
+ key_events integer NOT NULL DEFAULT 0,
+ total_users integer NOT NULL DEFAULT 0,
+ transactions integer NOT NULL DEFAULT 0,
+ purchase_revenue double precision NOT NULL DEFAULT 0,
+ engagement_duration_seconds integer NOT NULL DEFAULT 0,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (brand_id, date, landing_page)
+);
+
+CREATE INDEX ga_page_stats_brand_date_idx
+ ON public.ga_page_stats (brand_id, date DESC);
+
+-- ── Product rows ────────────────────────────────────────────────────────────
+--
+-- Item-scoped and deliberately not joined to a page: a GA4 purchase fires on
+-- the checkout page, so pairing item metrics with a page dimension would
+-- attribute every sale to /checkout. Which entry page produced sales lives in
+-- the two tables above; what sold lives here.
+--
+-- Absent ecommerce tracking is normal, not an error — properties without it
+-- simply return no rows.
+CREATE TABLE public.ga_item_stats (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ brand_id uuid NOT NULL REFERENCES public.brands(id) ON DELETE CASCADE,
+ date date NOT NULL,
+ item_id text NOT NULL DEFAULT '',
+ item_name text NOT NULL DEFAULT '',
+ item_category text NOT NULL DEFAULT '',
+ items_viewed integer NOT NULL DEFAULT 0,
+ items_added_to_cart integer NOT NULL DEFAULT 0,
+ items_purchased integer NOT NULL DEFAULT 0,
+ item_revenue double precision NOT NULL DEFAULT 0,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (brand_id, date, item_id, item_name)
+);
+
+CREATE INDEX ga_item_stats_brand_date_idx
+ ON public.ga_item_stats (brand_id, date DESC);
+
+-- ── RLS ─────────────────────────────────────────────────────────────────────
+
+ALTER TABLE public.ga_ai_traffic_stats ENABLE ROW LEVEL SECURITY;
+ALTER TABLE public.ga_page_stats ENABLE ROW LEVEL SECURITY;
+ALTER TABLE public.ga_item_stats ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "ga_ai_traffic_stats: member select" ON public.ga_ai_traffic_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()
+ )
+ );
+
+CREATE POLICY "ga_page_stats: member select" ON public.ga_page_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()
+ )
+ );
+
+CREATE POLICY "ga_item_stats: member select" ON public.ga_item_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.ga_ai_traffic_stats TO authenticated;
+GRANT SELECT ON public.ga_page_stats TO authenticated;
+GRANT SELECT ON public.ga_item_stats TO authenticated;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 7148945b7..dd72f6b8a 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -5279,3 +5279,163 @@ CREATE UNIQUE INDEX IF NOT EXISTS sent_pulses_brand_window_key
ON public.sent_pulses (brand_id, ((payload -> 'window' ->> 'to')))
WHERE (payload -> 'window' ->> 'to') IS NOT NULL;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00053_ga_traffic_stats.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Google Analytics traffic sync (#704) — daily GA4 rows pulled through the
+-- Composio connection for every brand mapped to a property (#694).
+--
+-- Three tables rather than one, because they answer different questions and
+-- must never be added together:
+--
+-- ga_ai_traffic_stats what AI sources brought, per landing page
+-- ga_page_stats what a landing page is worth in total, all sources
+-- ga_item_stats what actually sold, product-scoped
+--
+-- The first two overlap by design: the AI table is a slice of the same
+-- traffic the page table totals. Summing them double-counts, which is the
+-- same trap this integration already avoids with ai_traffic_logs (our own
+-- snippet counts these visits a second time). Nothing in the pipeline joins
+-- or sums across origins; how the numbers are presented together is a
+-- decision for the surface phase.
+--
+-- Writes are service-role upserts keyed on the natural grain, so re-running a
+-- day rewrites it instead of duplicating. Org members read.
+
+-- ── AI-sourced traffic, by landing page ─────────────────────────────────────
+--
+-- `source` keeps GA4's raw sessionSource string and `platform` the normalised
+-- name. The raw value is not redundant: one engine arrives under several
+-- source strings, and keeping what was actually observed is what lets the
+-- classification list be extended from real data instead of guesswork.
+--
+-- Two page columns on purpose. `landing_page_query` is the full entry URL,
+-- which is what attribution needs — this table is small enough to afford the
+-- cardinality (a live property produced 96 rows over 90 days). `landing_page`
+-- drops the query string so it joins the page totals below, which cannot
+-- afford it: on the same property the query string multiplied distinct pages
+-- by 8.8, and a shop with faceted filters is far worse.
+CREATE TABLE public.ga_ai_traffic_stats (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ brand_id uuid NOT NULL REFERENCES public.brands(id) ON DELETE CASCADE,
+ date date NOT NULL,
+ source text NOT NULL,
+ platform text,
+ landing_page text NOT NULL DEFAULT '',
+ landing_page_query text NOT NULL DEFAULT '',
+ sessions integer NOT NULL DEFAULT 0,
+ engaged_sessions integer NOT NULL DEFAULT 0,
+ key_events integer NOT NULL DEFAULT 0,
+ total_users integer NOT NULL DEFAULT 0,
+ transactions integer NOT NULL DEFAULT 0,
+ purchase_revenue double precision NOT NULL DEFAULT 0,
+ engagement_duration_seconds integer NOT NULL DEFAULT 0,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (brand_id, date, source, landing_page_query)
+);
+
+CREATE INDEX ga_ai_traffic_stats_brand_page_idx
+ ON public.ga_ai_traffic_stats (brand_id, landing_page);
+
+CREATE INDEX ga_ai_traffic_stats_brand_date_idx
+ ON public.ga_ai_traffic_stats (brand_id, date DESC);
+
+-- ── Landing-page totals, every source ───────────────────────────────────────
+--
+-- "How much is this page worth to the business" cannot be answered from the
+-- AI slice: a page that converts well overall is the interesting one when its
+-- AI visibility is weak, and that comparison needs the page's full figures.
+--
+-- This is the table that grows: one row per page per day, and a large shop
+-- can have tens of thousands of pages taking traffic on any given day. Two
+-- things bound it — the path without its query string, and a per-day ceiling
+-- on how many pages are kept (PAGE_DAILY_LIMIT in ga-sync.js). Pages are
+-- ordered so anything converting survives the cut whatever its session count;
+-- what gets dropped is the one-session tail, which no ranking of commercial
+-- value would have surfaced anyway.
+CREATE TABLE public.ga_page_stats (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ brand_id uuid NOT NULL REFERENCES public.brands(id) ON DELETE CASCADE,
+ date date NOT NULL,
+ landing_page text NOT NULL DEFAULT '',
+ sessions integer NOT NULL DEFAULT 0,
+ engaged_sessions integer NOT NULL DEFAULT 0,
+ key_events integer NOT NULL DEFAULT 0,
+ total_users integer NOT NULL DEFAULT 0,
+ transactions integer NOT NULL DEFAULT 0,
+ purchase_revenue double precision NOT NULL DEFAULT 0,
+ engagement_duration_seconds integer NOT NULL DEFAULT 0,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (brand_id, date, landing_page)
+);
+
+CREATE INDEX ga_page_stats_brand_date_idx
+ ON public.ga_page_stats (brand_id, date DESC);
+
+-- ── Product rows ────────────────────────────────────────────────────────────
+--
+-- Item-scoped and deliberately not joined to a page: a GA4 purchase fires on
+-- the checkout page, so pairing item metrics with a page dimension would
+-- attribute every sale to /checkout. Which entry page produced sales lives in
+-- the two tables above; what sold lives here.
+--
+-- Absent ecommerce tracking is normal, not an error — properties without it
+-- simply return no rows.
+CREATE TABLE public.ga_item_stats (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ brand_id uuid NOT NULL REFERENCES public.brands(id) ON DELETE CASCADE,
+ date date NOT NULL,
+ item_id text NOT NULL DEFAULT '',
+ item_name text NOT NULL DEFAULT '',
+ item_category text NOT NULL DEFAULT '',
+ items_viewed integer NOT NULL DEFAULT 0,
+ items_added_to_cart integer NOT NULL DEFAULT 0,
+ items_purchased integer NOT NULL DEFAULT 0,
+ item_revenue double precision NOT NULL DEFAULT 0,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (brand_id, date, item_id, item_name)
+);
+
+CREATE INDEX ga_item_stats_brand_date_idx
+ ON public.ga_item_stats (brand_id, date DESC);
+
+-- ── RLS ─────────────────────────────────────────────────────────────────────
+
+ALTER TABLE public.ga_ai_traffic_stats ENABLE ROW LEVEL SECURITY;
+ALTER TABLE public.ga_page_stats ENABLE ROW LEVEL SECURITY;
+ALTER TABLE public.ga_item_stats ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "ga_ai_traffic_stats: member select" ON public.ga_ai_traffic_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()
+ )
+ );
+
+CREATE POLICY "ga_page_stats: member select" ON public.ga_page_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()
+ )
+ );
+
+CREATE POLICY "ga_item_stats: member select" ON public.ga_item_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.ga_ai_traffic_stats TO authenticated;
+GRANT SELECT ON public.ga_page_stats TO authenticated;
+GRANT SELECT ON public.ga_item_stats TO authenticated;
+