feat: Pipeline V2 — 3-phase analysis with verified channel discovery

Restructured the entire analysis pipeline from AI-guessing social
handles to deterministic 3-phase discovery + collection + generation.

Phase 1 (discover-channels): 3-source channel discovery
  - Firecrawl scrape: extract social links from HTML
  - Perplexity search: find handles via web search
  - URL regex parsing: deterministic link extraction
  - Handle verification: HEAD requests + YouTube API
  - DB: creates row with verified_channels + scrape_data

Phase 2 (collect-channel-data): 9 parallel data collectors
  - Instagram (Apify), YouTube (Data API v3), Facebook (Apify)
  - 강남언니 (Firecrawl), Naver Blog + Place (Naver API)
  - Google Maps (Apify), Market analysis (Perplexity 4x parallel)
  - DB: stores ALL raw data in channel_data column

Phase 3 (generate-report): AI report from real data
  - Reads channel_data + analysis_data from DB
  - Builds channel summary with real metrics
  - AI generates report using only verified data
  - V1 backwards compatibility preserved (url-based flow)

Supporting changes:
  - DB migration: status, verified_channels, channel_data columns
  - _shared/extractSocialLinks.ts: regex-based social link parser
  - _shared/verifyHandles.ts: multi-platform handle verifier
  - AnalysisLoadingPage: real 3-phase progress + channel panel
  - useReport: channel_data column support + V2 enrichment merge
  - 강남언니 rating: auto-correct 5→10 scale + search fallback
  - KPIDashboard: navigate() instead of <a href>
  - Loading text: 20-30초 → 1-2분

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-03 21:49:13 +09:00
1 parent da267fd744
commit 7557ef774c
14 files changed
+1506 -253

No files matched your search

+1 -1
View File
@@ -14,7 +14,7 @@ function formatNumber(n: number): string {
const infoFields = (data: ClinicSnapshotType) => [
data.established ? { label: '개원', value: `${data.established} (${data.yearsInBusiness}년)`, icon: Calendar } : null,
data.staffCount > 0 ? { label: '의료진', value: `${data.staffCount}명`, icon: Users } : null,
data.overallRating > 0 ? { label: '강남언니 평점', value: `${data.overallRating} / 5.0`, icon: Star } : null,
data.overallRating > 0 ? { label: '강남언니 평점', value: data.overallRating > 5 ? `${data.overallRating} / 10` : `${data.overallRating} / 5.0`, icon: Star } : null,
data.totalReviews > 0 ? { label: '리뷰 수', value: formatNumber(data.totalReviews), icon: Star } : null,
data.priceRange.min !== '-' ? { label: '시술 가격대', value: `${data.priceRange.min} ~ ${data.priceRange.max}`, icon: Globe } : null,
data.location ? { label: '위치', value: data.nearestStation ? `${data.location} (${data.nearestStation})` : data.location, icon: MapPin } : null,
+5 -4
View File
@@ -1,5 +1,5 @@
import { motion } from 'motion/react';
import { useParams } from 'react-router';
import { useParams, useNavigate } from 'react-router';
import { TrendingUp, ArrowUpRight, Download, Loader2 } from 'lucide-react';
import { SectionWrapper } from './ui/SectionWrapper';
import { useExportPDF } from '../../hooks/useExportPDF';
@@ -30,6 +30,7 @@ function formatKpiValue(value: string): string {
export default function KPIDashboard({ metrics, clinicName }: KPIDashboardProps) {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const { exportPDF, isExporting } = useExportPDF();
return (
@@ -94,13 +95,13 @@ export default function KPIDashboard({ metrics, clinicName }: KPIDashboardProps)
INFINITH와 함께 데이터 기반 마케팅 전환을 시작하세요. 90일 안에 측정 가능한 성과를 만들어 드립니다.
</p>
<div className="flex flex-col sm:flex-row items-center justify-center gap-4">
<a
href={`/plan/${id || 'live'}`}
<button
onClick={() => navigate(`/plan/${id || 'live'}`)}
className="inline-flex items-center gap-2 bg-gradient-to-r from-[#4F1DA1] to-[#021341] text-white font-semibold px-8 py-4 rounded-full hover:shadow-xl transition-all"
>
마케팅 기획
<ArrowUpRight size={18} />
</a>
</button>
<button
onClick={() => exportPDF(`INFINITH_Marketing_Report_${clinicName || 'Report'}`)}
disabled={isExporting}
+17 -4
View File
@@ -48,9 +48,17 @@ export function useReport(id: string | undefined): UseReportResult {
state.report,
state.metadata,
);
setData(transformed);
// V2 pipeline: report already includes channelEnrichment from Phase 2
const enrichment = state.report.channelEnrichment as EnrichmentData | undefined;
if (enrichment) {
const merged = mergeEnrichment(transformed, enrichment);
setData(merged);
setIsEnriched(true);
} else {
setData(transformed);
setIsEnriched(false);
}
setSocialHandles(state.metadata.socialHandles || null);
setIsEnriched(false);
setIsLoading(false);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to parse report data');
@@ -101,8 +109,13 @@ export function useReport(id: string | undefined): UseReportResult {
}
setSocialHandles(handles as Record<string, string | null> | null);
// If channelEnrichment already exists in DB, merge it immediately
const enrichment = reportJson.channelEnrichment as EnrichmentData | undefined;
// V2: channel_data column (separate from report JSONB)
// V1 compat: channelEnrichment inside report JSONB
const enrichment =
(row.channel_data && Object.keys(row.channel_data).length > 0 ? row.channel_data : null) as EnrichmentData | null
|| (reportJson.channelEnrichment as EnrichmentData | undefined)
|| null;
if (enrichment) {
const merged = mergeEnrichment(transformed, enrichment);
setData(merged);
+64
View File
@@ -80,3 +80,67 @@ export async function scrapeWebsite(url: string, clinicName?: string) {
return response.json();
}
// ─── Pipeline V2 API Functions ───
/**
* Phase 1: Discover & verify social channels from website URL.
* Returns verified handles + reportId for subsequent phases.
*/
export async function discoverChannels(url: string, clinicName?: string) {
const response = await fetch(
`${supabaseUrl}/functions/v1/discover-channels`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url, clinicName }),
}
);
if (!response.ok) {
throw new Error(`Channel discovery failed: ${response.statusText}`);
}
return response.json();
}
/**
* Phase 2: Collect all channel data using verified handles.
* Reads verified_channels from DB, runs parallel API calls.
*/
export async function collectChannelData(reportId: string) {
const response = await fetch(
`${supabaseUrl}/functions/v1/collect-channel-data`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ reportId }),
}
);
if (!response.ok) {
throw new Error(`Data collection failed: ${response.statusText}`);
}
return response.json();
}
/**
* Phase 3: Generate AI report using real collected data from DB.
*/
export async function generateReportV2(reportId: string) {
const response = await fetch(
`${supabaseUrl}/functions/v1/generate-report`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ reportId }),
}
);
if (!response.ok) {
throw new Error(`Report generation failed: ${response.statusText}`);
}
return response.json();
}
+11 -3
View File
@@ -453,7 +453,11 @@ export function transformApiReport(
rating: 0,
reviewCount: 0,
},
overallRating: r.channelAnalysis?.gangnamUnni?.rating ?? 0,
// 강남언니 is 10-point scale. AI sometimes gives 5-point — auto-correct.
overallRating: (() => {
const raw = r.channelAnalysis?.gangnamUnni?.rating ?? 0;
return typeof raw === 'number' && raw > 0 && raw <= 5 ? raw * 2 : raw;
})(),
totalReviews: r.channelAnalysis?.gangnamUnni?.reviews ?? 0,
priceRange: { min: '-', max: '-', currency: '₩' },
certifications: [],
@@ -529,8 +533,12 @@ export function transformApiReport(
}] : []),
...(r.channelAnalysis?.gangnamUnni ? [{
name: '강남언니',
status: (r.channelAnalysis.gangnamUnni.status === 'active' ? 'active' : 'inactive') as 'active' | 'inactive',
details: `평점: ${r.channelAnalysis.gangnamUnni.rating ?? '-'} / 리뷰: ${r.channelAnalysis.gangnamUnni.reviews ?? '-'}`,
status: (r.channelAnalysis.gangnamUnni.status === 'active' || r.channelAnalysis.gangnamUnni.rating ? 'active' : 'inactive') as 'active' | 'inactive',
details: (() => {
const raw = r.channelAnalysis?.gangnamUnni?.rating;
const rating = typeof raw === 'number' && raw > 0 && raw <= 5 ? raw * 2 : raw;
return `평점: ${rating ?? '-'}/10 / 리뷰: ${r.channelAnalysis?.gangnamUnni?.reviews ?? '-'}`;
})(),
}] : []),
],
+131 -60
View File
@@ -1,25 +1,60 @@
import { useState, useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router';
import { motion } from 'motion/react';
import { Check, AlertCircle } from 'lucide-react';
import { generateMarketingReport } from '../lib/supabase';
import { motion, AnimatePresence } from 'motion/react';
import { Check, AlertCircle, CheckCircle2, XCircle } from 'lucide-react';
import { discoverChannels, collectChannelData, generateReportV2 } from '../lib/supabase';
const steps = [
{ label: 'Scanning website...', key: 'scrape' },
{ label: 'Analyzing social media presence...', key: 'social' },
{ label: 'Researching competitors & keywords...', key: 'analyze' },
{ label: 'Generating AI marketing report...', key: 'generate' },
{ label: 'Finalizing report...', key: 'finalize' },
/**
* Pipeline V2: 3-phase analysis with real progress.
* Phase 1: discover-channels → verify social handles
* Phase 2: collect-channel-data → gather all channel data + market analysis
* Phase 3: generate-report → AI report from real data
*/
interface VerifiedChannel {
handle: string;
verified: boolean;
url?: string;
}
interface VerifiedChannels {
instagram?: VerifiedChannel[];
youtube?: VerifiedChannel | null;
facebook?: VerifiedChannel | null;
naverBlog?: VerifiedChannel | null;
gangnamUnni?: VerifiedChannel | null;
tiktok?: VerifiedChannel | null;
}
type Phase = 'discovering' | 'collecting' | 'generating' | 'complete';
const PHASE_STEPS = [
{ key: 'discovering' as Phase, label: '웹사이트 스캔 & 채널 발견 중...', labelDone: '채널 발견 완료' },
{ key: 'collecting' as Phase, label: '채널 데이터 수집 & 시장 분석 중...', labelDone: '데이터 수집 완료' },
{ key: 'generating' as Phase, label: 'AI 마케팅 리포트 생성 중...', labelDone: '리포트 생성 완료' },
{ key: 'complete' as Phase, label: '분석 완료!', labelDone: '분석 완료!' },
];
const CHANNEL_LABELS: Record<string, string> = {
instagram: 'Instagram',
youtube: 'YouTube',
facebook: 'Facebook',
naverBlog: '네이버 블로그',
gangnamUnni: '강남언니',
tiktok: 'TikTok',
};
export default function AnalysisLoadingPage() {
const [currentStep, setCurrentStep] = useState(0);
const [phase, setPhase] = useState<Phase>('discovering');
const [error, setError] = useState<string | null>(null);
const [verifiedChannels, setVerifiedChannels] = useState<VerifiedChannels | null>(null);
const navigate = useNavigate();
const location = useLocation();
const url = (location.state as { url?: string })?.url;
const hasStarted = useRef(false);
const phaseIndex = PHASE_STEPS.findIndex(s => s.key === phase);
useEffect(() => {
if (hasStarted.current) return;
hasStarted.current = true;
@@ -29,46 +64,48 @@ export default function AnalysisLoadingPage() {
return;
}
const runAnalysis = async () => {
const runPipeline = async () => {
try {
// Step 1: Scraping
setCurrentStep(1);
// ─── Phase 1: Discover Channels ───
setPhase('discovering');
// Simulate step progression while waiting for API
const stepTimer = setInterval(() => {
setCurrentStep((prev) => (prev < steps.length - 1 ? prev + 1 : prev));
}, 5000);
const discovery = await discoverChannels(url);
if (!discovery.success) throw new Error(discovery.error || 'Channel discovery failed');
const result = await generateMarketingReport(url);
setVerifiedChannels(discovery.verifiedChannels);
const reportId = discovery.reportId;
clearInterval(stepTimer);
setCurrentStep(steps.length);
// ─── Phase 2: Collect Channel Data ───
setPhase('collecting');
if (result.success && result.report) {
const reportPath = result.reportId
? `/report/${result.reportId}`
: '/report/live';
const collection = await collectChannelData(reportId);
if (!collection.success) throw new Error(collection.error || 'Data collection failed');
// Brief delay to show completion
setTimeout(() => {
navigate(reportPath, {
replace: true,
state: {
report: result.report,
metadata: result.metadata,
reportId: result.reportId,
},
});
}, 800);
} else {
throw new Error(result.error || 'Report generation failed');
}
// ─── Phase 3: Generate Report ───
setPhase('generating');
const result = await generateReportV2(reportId);
if (!result.success) throw new Error(result.error || 'Report generation failed');
// ─── Complete ───
setPhase('complete');
setTimeout(() => {
navigate(`/report/${reportId}`, {
replace: true,
state: {
report: result.report,
metadata: result.metadata,
reportId,
},
});
}, 1000);
} catch (err) {
setError(err instanceof Error ? err.message : 'An error occurred');
}
};
runAnalysis();
runPipeline();
}, [url, navigate]);
return (
@@ -96,7 +133,7 @@ export default function AnalysisLoadingPage() {
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.6, delay: 0.1 }}
className="text-purple-300/80 text-sm font-mono mb-12 truncate max-w-full"
className="text-purple-300/80 text-sm font-mono mb-10 truncate max-w-full"
>
{url}
</motion.p>
@@ -114,26 +151,28 @@ export default function AnalysisLoadingPage() {
onClick={() => navigate('/', { replace: true })}
className="px-6 py-2 text-sm font-medium text-white bg-white/10 rounded-lg hover:bg-white/20 transition-colors"
>
Try Again
다시 시도
</button>
</motion.div>
) : (
<>
<div className="w-full space-y-5 mb-14">
{steps.map((step, index) => {
const isCompleted = currentStep > index;
const isActive = currentStep === index + 1 && currentStep <= steps.length;
{/* Pipeline steps */}
<div className="w-full space-y-5 mb-8">
{PHASE_STEPS.map((step, index) => {
const isCompleted = phaseIndex > index;
const isActive = phaseIndex === index && phase !== 'complete';
const isDone = step.key === 'complete' && phase === 'complete';
return (
<motion.div
key={step.key}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: isActive || isCompleted ? 1 : 0.3, x: 0 }}
transition={{ duration: 0.4, delay: index * 0.15 }}
animate={{ opacity: isActive || isCompleted || isDone ? 1 : 0.3, x: 0 }}
transition={{ duration: 0.4, delay: index * 0.1 }}
className="flex items-center gap-4"
>
<div className="w-7 h-7 flex-shrink-0 flex items-center justify-center">
{isCompleted ? (
{isCompleted || isDone ? (
<motion.div
initial={{ scale: 0 }}
animate={{ scale: 1 }}
@@ -148,33 +187,65 @@ export default function AnalysisLoadingPage() {
<div className="w-7 h-7 rounded-full border-2 border-white/10" />
)}
</div>
<span
className={`text-base font-sans transition-colors duration-300 ${
isCompleted
? 'text-white'
: isActive
? 'text-purple-200'
: 'text-white/30'
}`}
>
{step.label}
<span className={`text-base font-sans transition-colors duration-300 ${isCompleted || isDone ? 'text-white' : isActive ? 'text-purple-200' : 'text-white/30'}`}>
{isCompleted ? step.labelDone : step.label}
</span>
</motion.div>
);
})}
</div>
{/* Verified channels panel — shows after Phase 1 */}
<AnimatePresence>
{verifiedChannels && (
<motion.div
initial={{ opacity: 0, y: 10, height: 0 }}
animate={{ opacity: 1, y: 0, height: 'auto' }}
exit={{ opacity: 0 }}
transition={{ duration: 0.4 }}
className="w-full mb-8 rounded-xl bg-white/[0.06] border border-white/10 p-4"
>
<p className="text-xs text-purple-300/60 uppercase tracking-wider mb-3 font-semibold">
발견된 채널
</p>
<div className="space-y-2">
{Object.entries(verifiedChannels).map(([key, value]) => {
if (!value) return null;
const channels = Array.isArray(value) ? value : [value];
return channels.map((ch, i) => (
<div key={`${key}-${i}`} className="flex items-center gap-2">
{ch.verified ? (
<CheckCircle2 size={14} className="text-green-400 shrink-0" />
) : (
<XCircle size={14} className="text-red-400/60 shrink-0" />
)}
<span className={`text-sm ${ch.verified ? 'text-purple-100' : 'text-white/30'}`}>
{CHANNEL_LABELS[key] || key}
{ch.handle && key !== 'gangnamUnni' ? ` @${ch.handle}` : ''}
</span>
<span className={`text-[10px] ml-auto ${ch.verified ? 'text-green-400/60' : 'text-red-400/40'}`}>
{ch.verified ? 'verified' : 'not found'}
</span>
</div>
));
})}
</div>
</motion.div>
)}
</AnimatePresence>
{/* Progress bar */}
<div className="w-full h-2 bg-white/10 rounded-full overflow-hidden">
<motion.div
initial={{ width: '0%' }}
animate={{ width: `${(currentStep / steps.length) * 100}%` }}
animate={{ width: `${((phaseIndex + (phase === 'complete' ? 1 : 0.5)) / PHASE_STEPS.length) * 100}%` }}
transition={{ duration: 0.8, ease: 'easeInOut' }}
className="h-full bg-gradient-to-r from-[#4F1DA1] to-[#6C5CE7] rounded-full"
/>
</div>
<p className="text-white/40 text-xs mt-4">
AI가 마케팅 데이터를 분석하고 있습니다. 약 20~30초 소요됩니다.
AI가 마케팅 데이터를 분석하고 있습니다. 약 1~2분 소요됩니다.
</p>
</>
)}
+6 -1
View File
@@ -153,7 +153,12 @@ export default function ClinicProfilePage() {
const chAnalysis = report.channelAnalysis as Record<string, Record<string, unknown>> | undefined;
if (chAnalysis) {
RATINGS.length = 0;
if (chAnalysis.gangnamUnni?.rating) RATINGS.push({ platform: '강남언니', rating: `${chAnalysis.gangnamUnni.rating}`, scale: '/5', reviews: `${chAnalysis.gangnamUnni.reviews ?? '-'}건`, color: '#FF6B8A', pct: ((chAnalysis.gangnamUnni.rating as number) / 5) * 100 });
if (chAnalysis.gangnamUnni?.rating) {
const guRating = chAnalysis.gangnamUnni.rating as number;
const guScale = guRating > 5 ? '/10' : '/5';
const guPct = guRating > 5 ? (guRating / 10) * 100 : (guRating / 5) * 100;
RATINGS.push({ platform: '강남언니', rating: `${guRating}`, scale: guScale, reviews: `${chAnalysis.gangnamUnni.reviews ?? '-'}건`, color: '#FF6B8A', pct: guPct });
}
if (chAnalysis.naverPlace?.rating) RATINGS.push({ platform: '네이버 플레이스', rating: `${chAnalysis.naverPlace.rating}`, scale: '/5', reviews: `${chAnalysis.naverPlace.reviews ?? '-'}건`, color: '#03C75A', pct: ((chAnalysis.naverPlace.rating as number) / 5) * 100 });
}
})