fix: Instagram data collection pipeline — handle normalization + DB persistence

- Add normalizeInstagramHandle() utility (Edge + browser) to strip URLs, @ prefixes
- generate-report: normalize handles before saving, persist socialHandles in report JSONB
- enrich-channels: normalize Instagram handle before Apify call (defense in depth)
- useReport: recover socialHandles + channelEnrichment from DB on direct URL access
- ReportPage: skip redundant enrichment when data already exists in DB

Fixes: Instagram enrichment failing due to URL-format handles passed to Apify

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Haewon KamandClaude Opus 4.6 committed 2026-04-02 13:34:54 +09:00
1 parent 2d6e95c414
commit bd7bc45192
6 files changed
+156 -23

No files matched your search

+42 -4
View File
@@ -2,12 +2,17 @@ import { useState, useEffect } from 'react';
import { useLocation } from 'react-router';
import type { MarketingReport } from '../types/report';
import { fetchReportById } from '../lib/supabase';
import { transformApiReport } from '../lib/transformReport';
import { transformApiReport, mergeEnrichment, type EnrichmentData } from '../lib/transformReport';
import { normalizeInstagramHandle } from '../lib/normalizeHandles';
interface UseReportResult {
data: MarketingReport | null;
isLoading: boolean;
error: string | null;
/** True if channelEnrichment was already in the DB — no need to re-enrich */
isEnriched: boolean;
/** Normalized social handles recovered from DB or API metadata */
socialHandles: Record<string, string | null> | null;
}
interface LocationState {
@@ -27,6 +32,8 @@ export function useReport(id: string | undefined): UseReportResult {
const [data, setData] = useState<MarketingReport | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [isEnriched, setIsEnriched] = useState(false);
const [socialHandles, setSocialHandles] = useState<Record<string, string | null> | null>(null);
const location = useLocation();
useEffect(() => {
@@ -42,6 +49,8 @@ export function useReport(id: string | undefined): UseReportResult {
state.metadata,
);
setData(transformed);
setSocialHandles(state.metadata.socialHandles || null);
setIsEnriched(false);
setIsLoading(false);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to parse report data');
@@ -54,16 +63,45 @@ export function useReport(id: string | undefined): UseReportResult {
if (id) {
fetchReportById(id)
.then((row) => {
const reportJson = row.report as Record<string, unknown>;
const scrapeData = row.scrape_data as Record<string, unknown> | undefined;
const transformed = transformApiReport(
row.id,
row.report,
reportJson,
{
url: row.url,
clinicName: row.clinic_name || '',
generatedAt: row.created_at,
},
);
setData(transformed);
// Recover social handles: report.socialHandles > scrape_data.clinic.socialMedia
let handles = (reportJson.socialHandles as Record<string, string | null>) || null;
if (!handles && scrapeData) {
const clinic = scrapeData.clinic as Record<string, unknown> | undefined;
const socialMedia = clinic?.socialMedia as Record<string, string> | undefined;
if (socialMedia) {
handles = {
instagram: normalizeInstagramHandle(socialMedia.instagram),
youtube: socialMedia.youtube || null,
facebook: socialMedia.facebook || null,
blog: socialMedia.blog || null,
};
}
}
setSocialHandles(handles);
// If channelEnrichment already exists in DB, merge it immediately
const enrichment = reportJson.channelEnrichment as EnrichmentData | undefined;
if (enrichment) {
const merged = mergeEnrichment(transformed, enrichment);
setData(merged);
setIsEnriched(true);
} else {
setData(transformed);
setIsEnriched(false);
}
})
.catch((err) => {
setError(err instanceof Error ? err.message : 'Failed to fetch report');
@@ -77,5 +115,5 @@ export function useReport(id: string | undefined): UseReportResult {
setIsLoading(false);
}, [id, location.state]);
return { data, isLoading, error };
return { data, isLoading, error, isEnriched, socialHandles };
}
+32
View File
@@ -0,0 +1,32 @@
/**
* Normalize an Instagram handle from various input formats to a pure username.
* Browser-side copy of supabase/functions/_shared/normalizeHandles.ts
*/
export function normalizeInstagramHandle(
raw: string | null | undefined,
): string | null {
if (!raw || typeof raw !== 'string') return null;
let handle = raw.trim();
if (!handle) return null;
if (handle.includes('instagram.com')) {
try {
const urlStr = handle.startsWith('http') ? handle : `https://${handle}`;
const url = new URL(urlStr);
const segments = url.pathname.split('/').filter(Boolean);
handle = segments[0] || '';
} catch {
const match = handle.match(/instagram\.com\/([^/?#]+)/);
handle = match?.[1] || '';
}
}
if (handle.startsWith('@')) {
handle = handle.slice(1);
}
handle = handle.replace(/\/+$/, '');
return handle || null;
}
+16 -8
View File
@@ -34,24 +34,32 @@ const REPORT_SECTIONS = [
export default function ReportPage() {
const { id } = useParams<{ id: string }>();
const location = useLocation();
const { data: baseData, isLoading, error } = useReport(id);
const {
data: baseData,
isLoading,
error,
isEnriched,
socialHandles: dbSocialHandles,
} = useReport(id);
// Extract enrichment params from location state (socialHandles from API) or base data
// Build enrichment params — skip if already enriched (data from DB)
const enrichmentParams = useMemo(() => {
if (!baseData) return null;
if (!baseData || isEnriched) return null;
// Priority: location.state socialHandles > DB socialHandles > transformed data
const state = location.state as Record<string, unknown> | undefined;
const metadata = state?.metadata as Record<string, unknown> | undefined;
const socialHandles = metadata?.socialHandles as Record<string, string | null> | undefined;
const stateSocialHandles = metadata?.socialHandles as Record<string, string | null> | undefined;
const handles = stateSocialHandles || dbSocialHandles;
// Priority: API socialHandles > transformed data > undefined
const igHandle =
socialHandles?.instagram ||
handles?.instagram ||
baseData.instagramAudit?.accounts?.[0]?.handle ||
undefined;
const ytHandle =
socialHandles?.youtube ||
handles?.youtube ||
baseData.youtubeAudit?.handle ||
undefined;
@@ -62,7 +70,7 @@ export default function ReportPage() {
youtubeChannelId: ytHandle || undefined,
address: baseData.clinicSnapshot.location || undefined,
};
}, [baseData, location.state]);
}, [baseData, isEnriched, dbSocialHandles, location.state]);
const { status: enrichStatus, enrichedReport } = useEnrichment(baseData, enrichmentParams);