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.

fix(integrations): sync a brand's data as soon as its property is mapped (#850)

Gökhan Geyik5a5156d35c92
diff --git a/server/src/lib/ga-sync.js b/server/src/lib/ga-sync.js
index 157e1ec2f..b3aa01d3b 100644
--- a/server/src/lib/ga-sync.js
+++ b/server/src/lib/ga-sync.js
@@ -410,9 +410,10 @@ async function prune(table) {
/**
* Sync every eligible brand; optionally scoped to one organization (the
- * manual trigger). Returns per-brand counts.
+ * manual trigger) or to one brand (right after its property is mapped).
+ * Returns per-brand counts.
*/
-export async function runGaSync({ organizationId } = {}) {
+export async function runGaSync({ organizationId, brandId } = {}) {
if (!isComposioConfigured('google-analytics')) return { synced: 0, skipped: 0, results: [] };
// Orgs with a live connection…
@@ -428,12 +429,14 @@ export async function runGaSync({ organizationId } = {}) {
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
+ let brandQuery = 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 (brandId) brandQuery = brandQuery.eq('id', brandId);
+ const { data: brands, error: brandError } = await brandQuery;
if (brandError) throw new Error(brandError.message);
const results = [];
@@ -451,8 +454,11 @@ export async function runGaSync({ organizationId } = {}) {
}
}
- for (const table of ['ga_ai_traffic_stats', 'ga_page_stats', 'ga_item_stats']) {
- await prune(table);
+ // Retention is table-wide, so a single-brand sync leaves it to the daily run.
+ if (!brandId) {
+ 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');
diff --git a/server/src/lib/gsc-sync.js b/server/src/lib/gsc-sync.js
index 1b742659f..b6e999ffb 100644
--- a/server/src/lib/gsc-sync.js
+++ b/server/src/lib/gsc-sync.js
@@ -86,9 +86,10 @@ async function syncBrand(brand) {
/**
* Sync every eligible brand; optionally scoped to one organization (the
- * manual trigger). Returns per-brand counts.
+ * manual trigger) or to one brand (right after its property is mapped).
+ * Returns per-brand counts.
*/
-export async function runGscSync({ organizationId } = {}) {
+export async function runGscSync({ organizationId, brandId } = {}) {
if (!isComposioConfigured('google-search-console')) return { synced: 0, skipped: 0, results: [] };
// Orgs with a live connection…
@@ -104,12 +105,14 @@ export async function runGscSync({ organizationId } = {}) {
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
+ let brandQuery = supabaseAdmin
.from('brands')
.select('id, organization_id, gsc_property')
.eq('is_active', true)
.not('gsc_property', 'is', null)
.in('organization_id', connectedOrgIds);
+ if (brandId) brandQuery = brandQuery.eq('id', brandId);
+ const { data: brands, error: brandError } = await brandQuery;
if (brandError) throw new Error(brandError.message);
const results = [];
@@ -128,13 +131,16 @@ export async function runGscSync({ organizationId } = {}) {
}
// Retention (#648): the suggestion pipeline reads a 28-day window; 90 days
- // keeps room for trend features without unbounded growth.
- const { error: pruneError } = await supabaseAdmin
- .from('gsc_query_stats')
- .delete()
- .lt('date', utcDateString(90));
- if (pruneError) {
- logger.warn({ err: pruneError }, '[gsc-sync] retention prune failed');
+ // keeps room for trend features without unbounded growth. Table-wide, so a
+ // single-brand sync leaves it to the daily run.
+ if (!brandId) {
+ const { error: pruneError } = await supabaseAdmin
+ .from('gsc_query_stats')
+ .delete()
+ .lt('date', utcDateString(90));
+ if (pruneError) {
+ logger.warn({ err: pruneError }, '[gsc-sync] retention prune failed');
+ }
}
logger.info({ synced, skipped, total: (brands || []).length }, '[gsc-sync] completed');
diff --git a/server/src/routes/integrations.js b/server/src/routes/integrations.js
index 4f77d35d0..365502819 100644
--- a/server/src/routes/integrations.js
+++ b/server/src/routes/integrations.js
@@ -12,6 +12,7 @@ import {
} from '../lib/composio.js';
import { runGscSync } from '../lib/gsc-sync.js';
import { runGaSync } from '../lib/ga-sync.js';
+import { assertBrandAccess } from '../lib/access.js';
const router = Router();
@@ -271,10 +272,32 @@ router.get('/google-search-console/properties', async (req, res) => {
}
});
+// Brand syncs started from the web app right after a property is mapped.
+// Picking a property twice in quick succession must not run the same brand's
+// sync twice at once.
+const inFlightBrandSyncs = new Set();
+
+/**
+ * Start one brand's sync without holding the request open: answer 202 at once
+ * and leave the outcome to the log. A freshly mapped property otherwise has no
+ * data until the nightly run, and suggestions built before then cannot use it.
+ */
+function startBrandSync(req, res, provider, brandId, run) {
+ const key = `${provider}:${brandId}`;
+ if (inFlightBrandSyncs.has(key)) return res.status(202).json({ started: false });
+ inFlightBrandSyncs.add(key);
+ run({ brandId })
+ .then((result) => req.log.info({ provider, brandId, result }, 'integrations brand sync done'))
+ .catch((err) => req.log.error({ err, provider, brandId }, 'integrations brand sync failed'))
+ .finally(() => inFlightBrandSyncs.delete(key));
+ return res.status(202).json({ started: true });
+}
+
/**
* 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.
+ * With `{ brandId }` in the body it syncs that brand only, in the background.
*/
router.post('/google-search-console/sync', async (req, res) => {
try {
@@ -285,6 +308,12 @@ router.post('/google-search-console/sync', async (req, res) => {
return res.status(403).json({ error: 'Only admins and managers can trigger a sync.' });
}
+ const brandId = req.body?.brandId;
+ if (brandId) {
+ await assertBrandAccess(brandId, req.user.id);
+ return startBrandSync(req, res, GSC, brandId, runGscSync);
+ }
+
const result = await runGscSync({ organizationId: profile.organization_id });
return res.json(result);
} catch (err) {
@@ -321,7 +350,8 @@ 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.
+ * first-time backfill; the daily cycle runs the same sync. With `{ brandId }`
+ * in the body it syncs that brand only, in the background.
*/
router.post('/google-analytics/sync', async (req, res) => {
try {
@@ -332,6 +362,12 @@ router.post('/google-analytics/sync', async (req, res) => {
return res.status(403).json({ error: 'Only admins and managers can trigger a sync.' });
}
+ const brandId = req.body?.brandId;
+ if (brandId) {
+ await assertBrandAccess(brandId, req.user.id);
+ return startBrandSync(req, res, GA, brandId, runGaSync);
+ }
+
const result = await runGaSync({ organizationId: profile.organization_id });
return res.json(result);
} catch (err) {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_data-sources-panel.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_data-sources-panel.tsx
index 1d582060e..f3fdc4eef 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_data-sources-panel.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_data-sources-panel.tsx
@@ -1,10 +1,23 @@
'use client';
-import { useCallback, useEffect, useState } from 'react';
+import { useCallback, useMemo, useState } from 'react';
import { Link } from '@/i18n/navigation';
import { buttonVariants } from '@/components/ui/button-variants';
-import { BarChart3, Check, ExternalLink, Lock, Radar, Search, Sparkles, X } from 'lucide-react';
-import { getSuggestionSourceStates } from '@/lib/actions/integrations';
+import {
+ BarChart3,
+ Check,
+ Clock,
+ ExternalLink,
+ Lock,
+ Radar,
+ Search,
+ Sparkles,
+ X,
+} from 'lucide-react';
+import type {
+ SourceState as SourceStatus,
+ SuggestionSourceStates,
+} from '@/lib/actions/integrations';
/**
* What feeds this brand's suggestions, and what could (#659).
@@ -16,10 +29,16 @@ import { getSuggestionSourceStates } from '@/lib/actions/integrations';
*
* A source only counts as connected when the org is linked AND this brand is
* mapped to a property. Connected-but-unmapped silently produces nothing, so
- * it gets its own wording rather than a tick.
+ * it gets its own wording rather than a tick — and so does mapped-but-not-yet-
+ * synced, which produces nothing until its first sync lands.
*/
-type SourceState = 'not_configured' | 'not_connected' | 'connected_unmapped' | 'feeding';
+type SourceState =
+ | 'not_configured'
+ | 'not_connected'
+ | 'connected_unmapped'
+ | 'awaiting_data'
+ | 'feeding';
interface Source {
key: string;
@@ -67,8 +86,12 @@ function SourceMark({ source }: { source: Source }) {
);
}
-export function DataSourcesPanel({ brandId }: { brandId: string }) {
- const [sources, setSources] = useState<Source[] | null>(null);
+export function DataSourcesPanel({
+ states,
+}: {
+ /** undefined while loading, null when the read failed. */
+ states: SuggestionSourceStates | null | undefined;
+}) {
// Read during the initial render rather than from an effect: setting it in
// an effect dismisses on a second pass, so a previously hidden panel flashes
// into view before disappearing again.
@@ -81,66 +104,54 @@ export function DataSourcesPanel({ brandId }: { brandId: string }) {
}
});
- useEffect(() => {
- let cancelled = false;
-
- getSuggestionSourceStates(brandId)
- .then((states) => {
- if (cancelled) return;
- const stateOf = (s: { configured: boolean; connected: boolean; mapped: boolean }) =>
- !s.configured
- ? ('not_configured' as const)
- : !s.connected
- ? ('not_connected' as const)
- : s.mapped
- ? ('feeding' as const)
- : ('connected_unmapped' as const);
- const gsc = stateOf(states.gsc);
- const ga = stateOf(states.ga);
- const dataForSeo = states.dataForSeo.configured;
- setSources([
- {
- key: 'gsc',
- name: 'Google Search Console',
- blurb: 'See query and impression data to find high-opportunity prompts.',
- logo: '/google-search-console.svg',
- icon: Search,
- iconClass: 'text-blue-500',
- state: gsc,
- connectable: true,
- },
- {
- key: 'ga',
- name: 'Google Analytics (GA4)',
- blurb: 'Understand user intent and behaviour to uncover relevant prompts.',
- logo: '/google-analytics.svg',
- icon: BarChart3,
- iconClass: 'text-amber-500',
- state: ga,
- connectable: true,
- },
- {
- key: 'dataforseo',
- name: 'DataForSEO',
- blurb: 'Uncover keyword and SERP data to find content gaps.',
- logo: '/dataforseo.svg',
- icon: Radar,
- iconClass: 'text-violet-500',
- state: dataForSeo ? 'feeding' : 'not_configured',
- connectable: false,
- },
- ]);
- })
- .catch(() => {
- // Best effort: a status failure must never delay or break the
- // suggestions themselves, so the panel simply stays hidden.
- if (!cancelled) setSources([]);
- });
-
- return () => {
- cancelled = true;
- };
- }, [brandId]);
+ const sources = useMemo<Source[] | null>(() => {
+ if (states === undefined) return null;
+ // Best effort: a status failure must never delay or break the
+ // suggestions themselves, so the panel simply stays hidden.
+ if (states === null) return [];
+ const stateOf = (s: SourceStatus): SourceState =>
+ !s.configured
+ ? 'not_configured'
+ : !s.connected
+ ? 'not_connected'
+ : !s.mapped
+ ? 'connected_unmapped'
+ : s.firstDataAt
+ ? 'feeding'
+ : 'awaiting_data';
+ return [
+ {
+ key: 'gsc',
+ name: 'Google Search Console',
+ blurb: 'See query and impression data to find high-opportunity prompts.',
+ logo: '/google-search-console.svg',
+ icon: Search,
+ iconClass: 'text-blue-500',
+ state: stateOf(states.gsc),
+ connectable: true,
+ },
+ {
+ key: 'ga',
+ name: 'Google Analytics (GA4)',
+ blurb: 'Understand user intent and behaviour to uncover relevant prompts.',
+ logo: '/google-analytics.svg',
+ icon: BarChart3,
+ iconClass: 'text-amber-500',
+ state: stateOf(states.ga),
+ connectable: true,
+ },
+ {
+ key: 'dataforseo',
+ name: 'DataForSEO',
+ blurb: 'Uncover keyword and SERP data to find content gaps.',
+ logo: '/dataforseo.svg',
+ icon: Radar,
+ iconClass: 'text-violet-500',
+ state: states.dataForSeo.configured ? 'feeding' : 'not_configured',
+ connectable: false,
+ },
+ ];
+ }, [states]);
const dismiss = useCallback(() => {
setDismissed(true);
@@ -208,6 +219,11 @@ export function DataSourcesPanel({ brandId }: { brandId: string }) {
<Check className="h-3.5 w-3.5" />
{source.connectable ? 'Connected' : 'Enabled'}
</span>
+ ) : source.state === 'awaiting_data' ? (
+ <span className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
+ <Clock className="h-3.5 w-3.5" />
+ Connected · first sync in progress
+ </span>
) : !source.connectable ? null : (
<Link
href={SETTINGS_HREF}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx
index 99448ba9d..603dbe36f 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx
@@ -20,6 +20,7 @@ import {
Search as SearchIcon,
Trash2,
BarChart3,
+ Clock,
} from 'lucide-react';
import { Filter } from 'lucide-react';
import { Input } from '@/components/ui/input';
@@ -31,6 +32,7 @@ import {
SelectValue,
} from '@/components/ui/select';
import { toast } from 'sonner';
+import { cn } from '@/lib/utils';
import {
getPromptSuggestions,
refreshPromptSuggestions,
@@ -44,6 +46,7 @@ import {
type GaSuggestionSourceData,
type GscSuggestionBadge,
} from '@/lib/prompt-suggestion-source';
+import type { SuggestionSourceStates } from '@/lib/actions/integrations';
/**
* Analytics evidence, in the customer's own numbers (#705). A blind spot is
@@ -202,9 +205,52 @@ const SOURCE_FILTER_LABELS: Record<SourceFilter, string> = {
interface Props {
brandId: string;
onAccepted?: () => void;
+ /** Connected sources and whether their data has landed; null when unknown. */
+ sourceStates: SuggestionSourceStates | null;
}
-export function SuggestionsCard({ brandId, onAccepted }: Props) {
+const SOURCE_NAMES = { gsc: 'Search Console', ga: 'Analytics' } as const;
+
+function joinNames(names: string[]): string {
+ return names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names.at(-1)}` : names[0];
+}
+
+/**
+ * What to tell the reader about their own data sources, if anything:
+ * - `waiting`: a mapped source whose first sync has not landed yet, so
+ * nothing it knows can be in the list.
+ * - `ready`: the data has landed since these suggestions were generated, and
+ * none of them came from it — generating again would use it.
+ * A source whose data predates the list but contributed nothing is left
+ * alone: the list already had its chance at it (thin data, or all covered).
+ */
+function sourceNotice(
+ states: SuggestionSourceStates | null,
+ suggestions: PromptSuggestion[],
+): { kind: 'waiting' | 'ready'; names: string[] } | null {
+ if (!states) return null;
+ const latestGenerated = Math.max(0, ...suggestions.map((s) => Date.parse(s.generatedAt)));
+ const waiting: string[] = [];
+ const ready: string[] = [];
+ for (const key of ['gsc', 'ga'] as const) {
+ const state = states[key];
+ if (!state.configured || !state.connected || !state.mapped) continue;
+ if (!state.firstDataAt) {
+ waiting.push(SOURCE_NAMES[key]);
+ } else if (
+ suggestions.length > 0 &&
+ latestGenerated < Date.parse(state.firstDataAt) &&
+ !suggestions.some((s) => s.source === key)
+ ) {
+ ready.push(SOURCE_NAMES[key]);
+ }
+ }
+ if (ready.length > 0) return { kind: 'ready', names: ready };
+ if (waiting.length > 0) return { kind: 'waiting', names: waiting };
+ return null;
+}
+
+export function SuggestionsCard({ brandId, onAccepted, sourceStates }: Props) {
const [suggestions, setSuggestions] = useState<PromptSuggestion[]>([]);
const [loading, setLoading] = useState(false);
const [loaded, setLoaded] = useState(false);
@@ -278,6 +324,11 @@ export function SuggestionsCard({ brandId, onAccepted }: Props) {
});
}, [suggestions, sourceFilter, search]);
+ const notice = useMemo(
+ () => sourceNotice(sourceStates, suggestions),
+ [sourceStates, suggestions],
+ );
+
/**
* Dismiss everything on screen. Kept to what is actually listed rather than
* "every suggestion for this brand": dismissing a Search Console or
@@ -423,6 +474,42 @@ export function SuggestionsCard({ brandId, onAccepted }: Props) {
</div>
</CardHeader>
<CardContent>
+ {loaded && !loading && !error && notice && (
+ <div
+ className={cn(
+ 'mb-4 flex flex-col gap-3 rounded-lg border px-4 py-3 text-sm sm:flex-row sm:items-center sm:justify-between',
+ notice.kind === 'ready' ? 'border-primary/30 bg-primary/5' : 'bg-muted/30',
+ )}
+ >
+ <div className="flex items-start gap-2.5">
+ {notice.kind === 'ready' ? (
+ <Sparkles className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
+ ) : (
+ <Clock className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ )}
+ <p className={notice.kind === 'ready' ? '' : 'text-muted-foreground'}>
+ {notice.kind === 'ready'
+ ? `Your ${joinNames(notice.names)} data is ready. These suggestions were generated before it arrived — generate new ones to include it.`
+ : `${joinNames(notice.names)} is connected and its first sync is in progress. Suggestions from it will be available once it finishes, usually within a few minutes.`}
+ </p>
+ </div>
+ {notice.kind === 'ready' && (
+ <Button
+ onClick={handleRefresh}
+ disabled={refreshing}
+ size="sm"
+ className="shrink-0 gap-2"
+ >
+ {refreshing ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <RefreshCw className="h-3.5 w-3.5" />
+ )}
+ {refreshing ? 'Generating…' : 'Generate new suggestions'}
+ </Button>
+ )}
+ </div>
+ )}
{loading ? (
<div className="flex items-center justify-center py-10">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-tab.tsx
new file mode 100644
index 000000000..829cd0d89
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-tab.tsx
@@ -0,0 +1,69 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import {
+ getSuggestionSourceStates,
+ type SourceState,
+ type SuggestionSourceStates,
+} from '@/lib/actions/integrations';
+import { DataSourcesPanel } from './_data-sources-panel';
+import { SuggestionsCard } from './_suggestions-card';
+
+/** A mapped source whose first sync has not landed yet. */
+export function isAwaitingData(s: SourceState): boolean {
+ return s.configured && s.connected && s.mapped && !s.firstDataAt;
+}
+
+const POLL_MS = 30_000;
+// A first sync takes minutes. Past this, stop polling — a sync that failed
+// would otherwise keep the page asking forever; the nightly run retries it.
+const MAX_POLLS = 20;
+
+/**
+ * The Suggestions tab: the data-sources panel and the suggestion list, fed by
+ * one read of which sources are connected and whether their data has landed.
+ * While a freshly mapped source is still on its first sync the read repeats,
+ * so the list can offer a refresh the moment the data arrives.
+ */
+export function SuggestionsTab({
+ brandId,
+ onAccepted,
+}: {
+ brandId: string;
+ onAccepted?: () => void;
+}) {
+ // undefined while loading; null when the read failed — both render nothing
+ // source-related, so a status failure never gets in the way of suggestions.
+ const [states, setStates] = useState<SuggestionSourceStates | null | undefined>(undefined);
+ const [polls, setPolls] = useState(0);
+
+ useEffect(() => {
+ let cancelled = false;
+ getSuggestionSourceStates(brandId)
+ .then((s) => !cancelled && setStates(s))
+ .catch(() => !cancelled && setStates(null));
+ return () => {
+ cancelled = true;
+ };
+ }, [brandId, polls]);
+
+ const awaiting = states ? isAwaitingData(states.gsc) || isAwaitingData(states.ga) : false;
+
+ useEffect(() => {
+ if (!awaiting || polls >= MAX_POLLS) return;
+ const timer = setTimeout(() => setPolls((n) => n + 1), POLL_MS);
+ return () => clearTimeout(timer);
+ }, [awaiting, polls]);
+
+ useEffect(() => {
+ // eslint-disable-next-line react-hooks/set-state-in-effect
+ setPolls(0);
+ }, [brandId]);
+
+ return (
+ <>
+ <DataSourcesPanel states={states} />
+ <SuggestionsCard brandId={brandId} onAccepted={onAccepted} sourceStates={states ?? null} />
+ </>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
index c3f27b504..41b8fa362 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
@@ -12,7 +12,6 @@ const PlatformVolumeChart = dynamic(() => import('./_charts').then((m) => m.Plat
ssr: false,
loading: () => <Skeleton className="h-64 w-full" />,
});
-import { SuggestionsCard } from './_suggestions-card';
import { QueryFanoutTab } from './_fanout-tab';
import { INTENT_LABELS, INTENT_COLORS } from '@/config/intent-labels';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
@@ -100,7 +99,7 @@ import {
import { DateRangeFilter } from '@/components/filters/date-range-filter';
import { getBrandFilterOptions } from '@/lib/actions/tracking';
import { formatRegionDisplay } from '@/lib/region';
-import { DataSourcesPanel } from './_data-sources-panel';
+import { SuggestionsTab } from './_suggestions-tab';
import { PLANS } from '@/config/plans';
import { getTopics } from '@/lib/actions/topic';
import { analyzeNewPrompt, type PromptVisibilitySummary } from '@/lib/actions/tracking';
@@ -1573,8 +1572,7 @@ export default function PromptsPage() {
{view === 'suggestions' ? (
activeBrandId && (
<>
- <DataSourcesPanel brandId={activeBrandId} />
- <SuggestionsCard brandId={activeBrandId} onAccepted={loadData} />
+ <SuggestionsTab brandId={activeBrandId} onAccepted={loadData} />
</>
)
) : (
diff --git a/web/src/lib/actions/integrations.ts b/web/src/lib/actions/integrations.ts
index 40161afe1..94a577748 100644
--- a/web/src/lib/actions/integrations.ts
+++ b/web/src/lib/actions/integrations.ts
@@ -53,9 +53,20 @@ export async function getIntegrationStatus(
* for a few minutes is a better failure than a second of blank space on every
* visit.
*/
+export interface SourceState {
+ configured: boolean;
+ connected: boolean;
+ mapped: boolean;
+ /**
+ * When this brand's first synced row landed, or null when nothing has been
+ * synced yet. Suggestions generated before it could not draw on the source.
+ */
+ firstDataAt: string | null;
+}
+
export interface SuggestionSourceStates {
- gsc: { configured: boolean; connected: boolean; mapped: boolean };
- ga: { configured: boolean; connected: boolean; mapped: boolean };
+ gsc: SourceState;
+ ga: SourceState;
dataForSeo: { configured: boolean };
}
@@ -68,7 +79,16 @@ export async function getSuggestionSourceStates(brandId: string): Promise<Sugges
dataForSeo?: boolean;
}
- const [configRes, brandRes, connRes] = await Promise.all([
+ const firstRow = (table: 'gsc_query_stats' | 'ga_page_stats') =>
+ supabase
+ .from(table)
+ .select('created_at')
+ .eq('brand_id', brandId)
+ .order('created_at', { ascending: true })
+ .limit(1)
+ .maybeSingle();
+
+ const [configRes, brandRes, connRes, gscFirst, gaFirst] = await Promise.all([
fetch(`${API_BASE_URL}/api/integrations/config`, {
headers: await authHeaders(),
cache: 'no-store',
@@ -77,6 +97,8 @@ export async function getSuggestionSourceStates(brandId: string): Promise<Sugges
.catch(() => ({}) as ConfigBody),
supabase.from('brands').select('gsc_property, ga_property_id').eq('id', brandId).maybeSingle(),
supabase.from('integration_connections').select('provider, status'),
+ firstRow('gsc_query_stats'),
+ firstRow('ga_page_stats'),
]);
const connected = new Set(
@@ -88,11 +110,13 @@ export async function getSuggestionSourceStates(brandId: string): Promise<Sugges
configured: Boolean(configRes.googleSearchConsole),
connected: connected.has('google-search-console'),
mapped: Boolean(brandRes.data?.gsc_property),
+ firstDataAt: gscFirst.data?.created_at ?? null,
},
ga: {
configured: Boolean(configRes.googleAnalytics),
connected: connected.has('google-analytics'),
mapped: Boolean(brandRes.data?.ga_property_id),
+ firstDataAt: gaFirst.data?.created_at ?? null,
},
dataForSeo: { configured: Boolean(configRes.dataForSeo) },
};
@@ -123,6 +147,24 @@ export async function disconnectIntegration(provider: IntegrationProvider): Prom
// ─── Property mapping (#642) ─────────────────────────────────────────────────
+/**
+ * Start a freshly mapped brand's first sync. Without it the data only lands
+ * with the nightly run, and suggestions generated in the meantime cannot draw
+ * on it. The server answers at once and syncs in the background. Best effort:
+ * the property pick is already saved, and the nightly run is the fallback.
+ */
+async function startBrandSync(provider: IntegrationProvider, brandId: string): Promise<void> {
+ try {
+ await fetch(`${API_BASE_URL}/api/integrations/${provider}/sync`, {
+ method: 'POST',
+ headers: await authHeaders(),
+ body: JSON.stringify({ brandId }),
+ });
+ } catch {
+ // The nightly sync picks the brand up.
+ }
+}
+
export interface GscProperty {
siteUrl: string;
permissionLevel: string | null;
@@ -169,6 +211,7 @@ export async function setBrandGscProperty(brandId: string, property: string | nu
.update({ gsc_property: property })
.eq('id', brandId);
if (error) throw new Error(error.message);
+ if (property) await startBrandSync('google-search-console', brandId);
}
// ─── Google Analytics property mapping (#694) ────────────────────────────────
@@ -226,4 +269,5 @@ export async function setBrandGaProperty(
.update({ ga_property_id: propertyId })
.eq('id', brandId);
if (error) throw new Error(error.message);
+ if (propertyId) await startBrandSync('google-analytics', brandId);
}