feat: real API integration + YouTube Data API v3 + progressive loading
- Replace mock useReport() with real Supabase API data pipeline - Add transformReport.ts to map API responses to MarketingReport type - Add useEnrichment() hook for background channel data enrichment - Replace Apify YouTube scraper with YouTube Data API v3 - Add mergeEnrichment() for progressive data loading - Add EmptyState component for graceful empty data handling - Add socialHandles to generate-report metadata - Graceful empty data in ClinicSnapshot, YouTube, Instagram, Facebook - Add Supabase Edge Functions and DB migrations - Add developer handoff documentation Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
c6e18b6a67
commit
60cd055042
30 files changed
+2905
-142
No files matched your search
@@ -14,15 +14,15 @@ function formatNumber(n: number): string {
|
||||
}
|
||||
|
||||
const infoFields = (data: ClinicSnapshotType) => [
|
||||
{ label: '개원', value: `${data.established} (${data.yearsInBusiness}년)`, icon: Calendar },
|
||||
{ label: '의료진', value: `${data.staffCount}명`, icon: Users },
|
||||
{ label: '강남언니 평점', value: `${data.overallRating} / 5.0`, icon: Star },
|
||||
{ label: '리뷰 수', value: formatNumber(data.totalReviews), icon: Star },
|
||||
{ label: '시술 가격대', value: `${data.priceRange.min} ~ ${data.priceRange.max}`, icon: Globe },
|
||||
{ label: '위치', value: `${data.location} (${data.nearestStation})`, icon: MapPin },
|
||||
{ label: '전화', value: data.phone, icon: Phone },
|
||||
{ label: '도메인', value: data.domain, icon: Globe },
|
||||
];
|
||||
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.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,
|
||||
data.phone ? { label: '전화', value: data.phone, icon: Phone } : null,
|
||||
data.domain ? { label: '도메인', value: data.domain, icon: Globe } : null,
|
||||
].filter((f): f is NonNullable<typeof f> => f !== null);
|
||||
|
||||
export default function ClinicSnapshot({ data }: ClinicSnapshotProps) {
|
||||
const fields = infoFields(data);
|
||||
@@ -55,38 +55,46 @@ export default function ClinicSnapshot({ data }: ClinicSnapshotProps) {
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Lead Doctor Highlight */}
|
||||
<motion.div
|
||||
className="rounded-2xl bg-gradient-to-r from-[#4F1DA1]/5 to-[#021341]/5 border border-purple-100 p-6 mb-8"
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
whileInView={{ opacity: 1, y: 0 }}
|
||||
viewport={{ once: true }}
|
||||
transition={{ duration: 0.5, delay: 0.3 }}
|
||||
>
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<Award size={20} className="text-[#6C5CE7]" />
|
||||
<h3 className="font-serif font-bold text-2xl text-[#0A1128]">대표 원장</h3>
|
||||
</div>
|
||||
<p className="text-xl font-bold text-[#0A1128] mb-1">{data.leadDoctor.name}</p>
|
||||
<p className="text-sm text-slate-600 mb-3">{data.leadDoctor.credentials}</p>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex items-center gap-1">
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
<Star
|
||||
key={i}
|
||||
size={16}
|
||||
className={i < Math.round(data.leadDoctor.rating) ? 'text-[#6B2D8B] fill-[#6B2D8B]' : 'text-slate-200'}
|
||||
/>
|
||||
))}
|
||||
<span className="text-sm font-semibold text-[#0A1128] ml-1">
|
||||
{data.leadDoctor.rating}
|
||||
</span>
|
||||
{/* Lead Doctor Highlight — only show if doctor name exists */}
|
||||
{data.leadDoctor.name && (
|
||||
<motion.div
|
||||
className="rounded-2xl bg-gradient-to-r from-[#4F1DA1]/5 to-[#021341]/5 border border-purple-100 p-6 mb-8"
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
whileInView={{ opacity: 1, y: 0 }}
|
||||
viewport={{ once: true }}
|
||||
transition={{ duration: 0.5, delay: 0.3 }}
|
||||
>
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<Award size={20} className="text-[#6C5CE7]" />
|
||||
<h3 className="font-serif font-bold text-2xl text-[#0A1128]">대표 원장</h3>
|
||||
</div>
|
||||
<span className="text-sm text-slate-500">
|
||||
리뷰 {formatNumber(data.leadDoctor.reviewCount)}건
|
||||
</span>
|
||||
</div>
|
||||
</motion.div>
|
||||
<p className="text-xl font-bold text-[#0A1128] mb-1">{data.leadDoctor.name}</p>
|
||||
{data.leadDoctor.credentials && (
|
||||
<p className="text-sm text-slate-600 mb-3">{data.leadDoctor.credentials}</p>
|
||||
)}
|
||||
{data.leadDoctor.rating > 0 && (
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex items-center gap-1">
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
<Star
|
||||
key={i}
|
||||
size={16}
|
||||
className={i < Math.round(data.leadDoctor.rating) ? 'text-[#6B2D8B] fill-[#6B2D8B]' : 'text-slate-200'}
|
||||
/>
|
||||
))}
|
||||
<span className="text-sm font-semibold text-[#0A1128] ml-1">
|
||||
{data.leadDoctor.rating}
|
||||
</span>
|
||||
</div>
|
||||
{data.leadDoctor.reviewCount > 0 && (
|
||||
<span className="text-sm text-slate-500">
|
||||
리뷰 {formatNumber(data.leadDoctor.reviewCount)}건
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* Certifications */}
|
||||
{data.certifications.length > 0 && (
|
||||
|
||||
@@ -325,6 +325,10 @@ function ConsolidationCard({ text }: { text: string }) {
|
||||
|
||||
/* ─── Main Component ─── */
|
||||
export default function FacebookAudit({ data }: { data: FacebookAuditType }) {
|
||||
const hasData = data.pages.length > 0 || data.diagnosis.length > 0;
|
||||
|
||||
if (!hasData) return null;
|
||||
|
||||
return (
|
||||
<SectionWrapper id="facebook-audit" title="Facebook Analysis" subtitle="페이스북 페이지 분석">
|
||||
{/* Page cards side by side */}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { motion } from 'motion/react';
|
||||
import { Instagram, AlertCircle, FileText, Users, Eye } from 'lucide-react';
|
||||
import { SectionWrapper } from './ui/SectionWrapper';
|
||||
import { EmptyState } from './ui/EmptyState';
|
||||
import { MetricCard } from './ui/MetricCard';
|
||||
import { DiagnosisRow } from './ui/DiagnosisRow';
|
||||
import type { InstagramAudit as InstagramAuditType, InstagramAccount } from '../../types/report';
|
||||
@@ -107,14 +108,25 @@ function AccountCard({ account, index }: { key?: string | number; account: Insta
|
||||
}
|
||||
|
||||
export default function InstagramAudit({ data }: InstagramAuditProps) {
|
||||
const hasAccounts = data.accounts.length > 0 && data.accounts.some(a => a.handle || a.followers > 0);
|
||||
|
||||
return (
|
||||
<SectionWrapper id="instagram-audit" title="Instagram Analysis" subtitle="인스타그램 채널 분석">
|
||||
{!hasAccounts && data.diagnosis.length === 0 && (
|
||||
<EmptyState
|
||||
message="Instagram 계정 데이터 수집 중"
|
||||
subtext="채널 데이터 보강이 완료되면 계정 정보와 분석 결과가 표시됩니다."
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Account cards */}
|
||||
{hasAccounts && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
|
||||
{data.accounts.map((account, i) => (
|
||||
<AccountCard key={account.handle} account={account} index={i} />
|
||||
<AccountCard key={account.handle || i} account={account} index={i} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Diagnosis */}
|
||||
{data.diagnosis.length > 0 && (
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { motion } from 'motion/react';
|
||||
import { Youtube, Users, Video, Eye, TrendingUp, ExternalLink } from 'lucide-react';
|
||||
import { SectionWrapper } from './ui/SectionWrapper';
|
||||
import { EmptyState } from './ui/EmptyState';
|
||||
import { MetricCard } from './ui/MetricCard';
|
||||
import { DiagnosisRow } from './ui/DiagnosisRow';
|
||||
import type { YouTubeAudit as YouTubeAuditType } from '../../types/report';
|
||||
@@ -16,8 +17,18 @@ function formatNumber(n: number): string {
|
||||
}
|
||||
|
||||
export default function YouTubeAudit({ data }: YouTubeAuditProps) {
|
||||
const hasData = data.subscribers > 0 || data.totalVideos > 0 || data.topVideos.length > 0 || data.diagnosis.length > 0;
|
||||
|
||||
return (
|
||||
<SectionWrapper id="youtube-audit" title="YouTube Analysis" subtitle="유튜브 채널 분석">
|
||||
{!hasData && (
|
||||
<EmptyState
|
||||
message="YouTube 채널 데이터 수집 중"
|
||||
subtext="채널 데이터 보강이 완료되면 구독자, 영상, 조회수 정보가 표시됩니다."
|
||||
/>
|
||||
)}
|
||||
|
||||
{hasData && <>
|
||||
{/* Metrics row */}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
|
||||
<MetricCard
|
||||
@@ -172,6 +183,7 @@ export default function YouTubeAudit({ data }: YouTubeAuditProps) {
|
||||
))}
|
||||
</motion.div>
|
||||
)}
|
||||
</>}
|
||||
</SectionWrapper>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { motion } from 'motion/react';
|
||||
import { Search } from 'lucide-react';
|
||||
|
||||
interface EmptyStateProps {
|
||||
message?: string;
|
||||
subtext?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shown inside report sections when data is not yet available
|
||||
* (e.g., before enrichment completes or when a channel is not found).
|
||||
*/
|
||||
export function EmptyState({
|
||||
message = '데이터 수집 중',
|
||||
subtext = '채널 데이터 보강이 완료되면 자동으로 업데이트됩니다.',
|
||||
}: EmptyStateProps) {
|
||||
return (
|
||||
<motion.div
|
||||
className="flex flex-col items-center justify-center py-12 text-center"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
transition={{ duration: 0.4 }}
|
||||
>
|
||||
<div className="w-12 h-12 rounded-2xl bg-slate-100 flex items-center justify-center mb-4">
|
||||
<Search size={20} className="text-slate-400" />
|
||||
</div>
|
||||
<p className="text-sm font-medium text-slate-500">{message}</p>
|
||||
<p className="text-xs text-slate-400 mt-1 max-w-xs">{subtext}</p>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { enrichChannels, fetchReportById } from '../lib/supabase';
|
||||
import { mergeEnrichment, type EnrichmentData } from '../lib/transformReport';
|
||||
import type { MarketingReport } from '../types/report';
|
||||
|
||||
type EnrichmentStatus = 'idle' | 'loading' | 'success' | 'error';
|
||||
|
||||
interface UseEnrichmentResult {
|
||||
status: EnrichmentStatus;
|
||||
enrichedReport: MarketingReport | null;
|
||||
}
|
||||
|
||||
interface EnrichmentParams {
|
||||
reportId: string | null;
|
||||
clinicName: string;
|
||||
instagramHandle?: string;
|
||||
youtubeChannelId?: string;
|
||||
address?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Triggers background channel enrichment after Phase 1 report renders.
|
||||
* Fires once, waits for the Edge Function to complete (~27s),
|
||||
* then returns the merged report.
|
||||
*/
|
||||
export function useEnrichment(
|
||||
baseReport: MarketingReport | null,
|
||||
params: EnrichmentParams | null,
|
||||
): UseEnrichmentResult {
|
||||
const [status, setStatus] = useState<EnrichmentStatus>('idle');
|
||||
const [enrichedReport, setEnrichedReport] = useState<MarketingReport | null>(null);
|
||||
const hasTriggered = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!baseReport || !params?.reportId || hasTriggered.current) return;
|
||||
// Don't enrich if no social handles are available
|
||||
if (!params.instagramHandle && !params.youtubeChannelId) return;
|
||||
|
||||
hasTriggered.current = true;
|
||||
setStatus('loading');
|
||||
|
||||
enrichChannels({
|
||||
reportId: params.reportId,
|
||||
clinicName: params.clinicName,
|
||||
instagramHandle: params.instagramHandle,
|
||||
youtubeChannelId: params.youtubeChannelId,
|
||||
address: params.address,
|
||||
})
|
||||
.then((result) => {
|
||||
if (result.success && result.data) {
|
||||
const merged = mergeEnrichment(baseReport, result.data as EnrichmentData);
|
||||
setEnrichedReport(merged);
|
||||
setStatus('success');
|
||||
} else {
|
||||
setStatus('error');
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
setStatus('error');
|
||||
});
|
||||
}, [baseReport, params]);
|
||||
|
||||
return {
|
||||
status,
|
||||
enrichedReport,
|
||||
};
|
||||
}
|
||||
+59
-12
@@ -1,6 +1,8 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useLocation } from 'react-router';
|
||||
import type { MarketingReport } from '../types/report';
|
||||
import { mockReport } from '../data/mockReport';
|
||||
import { fetchReportById } from '../lib/supabase';
|
||||
import { transformApiReport } from '../lib/transformReport';
|
||||
|
||||
interface UseReportResult {
|
||||
data: MarketingReport | null;
|
||||
@@ -8,27 +10,72 @@ interface UseReportResult {
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
interface LocationState {
|
||||
report?: Record<string, unknown>;
|
||||
metadata?: {
|
||||
url: string;
|
||||
clinicName: string;
|
||||
generatedAt: string;
|
||||
socialHandles?: Record<string, string | null>;
|
||||
address?: string;
|
||||
services?: string[];
|
||||
};
|
||||
reportId?: string;
|
||||
}
|
||||
|
||||
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 location = useLocation();
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) {
|
||||
setError('No report ID provided');
|
||||
setIsLoading(false);
|
||||
const state = location.state as LocationState | undefined;
|
||||
|
||||
// Source 1: Report data passed via navigation state (from AnalysisLoadingPage)
|
||||
if (state?.report && state?.metadata) {
|
||||
try {
|
||||
const reportId = state.reportId || id || 'live';
|
||||
const transformed = transformApiReport(
|
||||
reportId,
|
||||
state.report,
|
||||
state.metadata,
|
||||
);
|
||||
setData(transformed);
|
||||
setIsLoading(false);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to parse report data');
|
||||
setIsLoading(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Phase 1: Return mock data immediately
|
||||
// Phase 2+: Replace with real API call — fetch(`/api/reports/${id}`)
|
||||
const timer = setTimeout(() => {
|
||||
setData(mockReport);
|
||||
setIsLoading(false);
|
||||
}, 100);
|
||||
// Source 2: Fetch from Supabase by report ID (bookmarked/shared link)
|
||||
if (id && id !== 'view-clinic') {
|
||||
fetchReportById(id)
|
||||
.then((row) => {
|
||||
const transformed = transformApiReport(
|
||||
row.id,
|
||||
row.report,
|
||||
{
|
||||
url: row.url,
|
||||
clinicName: row.clinic_name || '',
|
||||
generatedAt: row.created_at,
|
||||
},
|
||||
);
|
||||
setData(transformed);
|
||||
})
|
||||
.catch((err) => {
|
||||
setError(err instanceof Error ? err.message : 'Failed to fetch report');
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
return;
|
||||
}
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [id]);
|
||||
// No data source available
|
||||
setError('리포트 데이터를 찾을 수 없습니다. 새 분석을 시작해주세요.');
|
||||
setIsLoading(false);
|
||||
}, [id, location.state]);
|
||||
|
||||
return { data, isLoading, error };
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { createClient } from "@supabase/supabase-js";
|
||||
|
||||
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
|
||||
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY;
|
||||
|
||||
export const supabase = createClient(supabaseUrl, supabaseAnonKey);
|
||||
|
||||
export async function generateMarketingReport(url: string, clinicName?: string) {
|
||||
const response = await fetch(
|
||||
`${supabaseUrl}/functions/v1/generate-report`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ url, clinicName }),
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Report generation failed: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function fetchReportById(reportId: string) {
|
||||
const { data, error } = await supabase
|
||||
.from("marketing_reports")
|
||||
.select("*")
|
||||
.eq("id", reportId)
|
||||
.single();
|
||||
|
||||
if (error) throw new Error(`Failed to fetch report: ${error.message}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
export interface EnrichChannelsRequest {
|
||||
reportId: string;
|
||||
clinicName: string;
|
||||
instagramHandle?: string;
|
||||
youtubeChannelId?: string;
|
||||
address?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fire-and-forget: triggers background channel enrichment.
|
||||
* Returns enrichment result when the Edge Function completes (~27s).
|
||||
*/
|
||||
export async function enrichChannels(params: EnrichChannelsRequest) {
|
||||
const response = await fetch(
|
||||
`${supabaseUrl}/functions/v1/enrich-channels`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(params),
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Channel enrichment failed: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function scrapeWebsite(url: string, clinicName?: string) {
|
||||
const response = await fetch(
|
||||
`${supabaseUrl}/functions/v1/scrape-website`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ url, clinicName }),
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Scraping failed: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
@@ -0,0 +1,501 @@
|
||||
import type { MarketingReport, Severity, ChannelScore, DiagnosisItem, TopVideo } from '../types/report';
|
||||
|
||||
/**
|
||||
* API response from generate-report Edge Function.
|
||||
* The `report` field is AI-generated JSON with varying structure.
|
||||
*/
|
||||
interface ApiReport {
|
||||
clinicInfo?: {
|
||||
name?: string;
|
||||
address?: string;
|
||||
phone?: string;
|
||||
services?: string[];
|
||||
doctors?: { name: string; specialty: string }[];
|
||||
};
|
||||
executiveSummary?: string;
|
||||
overallScore?: number;
|
||||
channelAnalysis?: Record<string, {
|
||||
score?: number;
|
||||
status?: string;
|
||||
posts?: number;
|
||||
followers?: number;
|
||||
subscribers?: number;
|
||||
rating?: number;
|
||||
reviews?: number;
|
||||
issues?: string[];
|
||||
recommendation?: string;
|
||||
}>;
|
||||
competitors?: {
|
||||
name: string;
|
||||
strengths?: string[];
|
||||
weaknesses?: string[];
|
||||
marketingChannels?: string[];
|
||||
}[];
|
||||
keywords?: {
|
||||
primary?: { keyword: string; monthlySearches?: number; competition?: string }[];
|
||||
longTail?: { keyword: string; monthlySearches?: number }[];
|
||||
};
|
||||
targetAudience?: {
|
||||
primary?: { ageRange?: string; gender?: string; interests?: string[]; channels?: string[] };
|
||||
secondary?: { ageRange?: string; gender?: string; interests?: string[]; channels?: string[] };
|
||||
};
|
||||
recommendations?: {
|
||||
priority?: string;
|
||||
category?: string;
|
||||
title?: string;
|
||||
description?: string;
|
||||
expectedImpact?: string;
|
||||
}[];
|
||||
marketTrends?: string[];
|
||||
}
|
||||
|
||||
interface ApiMetadata {
|
||||
url: string;
|
||||
clinicName: string;
|
||||
generatedAt: string;
|
||||
dataSources?: Record<string, boolean>;
|
||||
}
|
||||
|
||||
function scoreToSeverity(score: number | undefined): Severity {
|
||||
if (score === undefined) return 'unknown';
|
||||
if (score >= 80) return 'excellent';
|
||||
if (score >= 60) return 'good';
|
||||
if (score >= 40) return 'warning';
|
||||
return 'critical';
|
||||
}
|
||||
|
||||
function statusToSeverity(status: string | undefined): Severity {
|
||||
switch (status) {
|
||||
case 'active': return 'good';
|
||||
case 'inactive': return 'critical';
|
||||
case 'weak': return 'warning';
|
||||
default: return 'unknown';
|
||||
}
|
||||
}
|
||||
|
||||
const CHANNEL_ICONS: Record<string, string> = {
|
||||
naverBlog: 'blog',
|
||||
instagram: 'instagram',
|
||||
youtube: 'youtube',
|
||||
naverPlace: 'map',
|
||||
gangnamUnni: 'star',
|
||||
website: 'globe',
|
||||
facebook: 'facebook',
|
||||
tiktok: 'video',
|
||||
};
|
||||
|
||||
function buildChannelScores(channels: ApiReport['channelAnalysis']): ChannelScore[] {
|
||||
if (!channels) return [];
|
||||
return Object.entries(channels).map(([key, ch]) => ({
|
||||
channel: key,
|
||||
icon: CHANNEL_ICONS[key] || 'circle',
|
||||
score: ch.score ?? 0,
|
||||
maxScore: 100,
|
||||
status: ch.score !== undefined ? scoreToSeverity(ch.score) : statusToSeverity(ch.status),
|
||||
headline: ch.recommendation || '',
|
||||
}));
|
||||
}
|
||||
|
||||
function buildDiagnosis(report: ApiReport): DiagnosisItem[] {
|
||||
const items: DiagnosisItem[] = [];
|
||||
|
||||
// Extract issues from channel analysis
|
||||
if (report.channelAnalysis) {
|
||||
for (const [channel, ch] of Object.entries(report.channelAnalysis)) {
|
||||
if (ch.status === 'inactive' || ch.status === 'weak') {
|
||||
items.push({
|
||||
category: channel,
|
||||
detail: ch.recommendation || `${channel} 채널이 ${ch.status === 'inactive' ? '비활성' : '약함'} 상태입니다`,
|
||||
severity: statusToSeverity(ch.status),
|
||||
});
|
||||
}
|
||||
if (ch.issues) {
|
||||
for (const issue of ch.issues) {
|
||||
items.push({ category: channel, detail: issue, severity: 'warning' });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extract from recommendations
|
||||
if (report.recommendations) {
|
||||
for (const rec of report.recommendations) {
|
||||
if (rec.priority === 'high') {
|
||||
items.push({
|
||||
category: rec.category || '일반',
|
||||
detail: `${rec.title}: ${rec.description}`,
|
||||
severity: 'critical',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform raw API response into the MarketingReport shape
|
||||
* that frontend components expect.
|
||||
*/
|
||||
export function transformApiReport(
|
||||
reportId: string,
|
||||
apiReport: ApiReport,
|
||||
metadata: ApiMetadata,
|
||||
): MarketingReport {
|
||||
const r = apiReport;
|
||||
const clinic = r.clinicInfo || {};
|
||||
const doctor = clinic.doctors?.[0];
|
||||
|
||||
return {
|
||||
id: reportId,
|
||||
createdAt: metadata.generatedAt || new Date().toISOString(),
|
||||
targetUrl: metadata.url,
|
||||
overallScore: r.overallScore ?? 50,
|
||||
|
||||
clinicSnapshot: {
|
||||
name: clinic.name || metadata.clinicName || '',
|
||||
nameEn: '',
|
||||
established: '',
|
||||
yearsInBusiness: 0,
|
||||
staffCount: 0,
|
||||
leadDoctor: {
|
||||
name: doctor?.name || '',
|
||||
credentials: doctor?.specialty || '',
|
||||
rating: 0,
|
||||
reviewCount: 0,
|
||||
},
|
||||
overallRating: r.channelAnalysis?.gangnamUnni?.rating ?? 0,
|
||||
totalReviews: r.channelAnalysis?.gangnamUnni?.reviews ?? 0,
|
||||
priceRange: { min: '-', max: '-', currency: '₩' },
|
||||
certifications: [],
|
||||
mediaAppearances: [],
|
||||
medicalTourism: [],
|
||||
location: clinic.address || '',
|
||||
nearestStation: '',
|
||||
phone: clinic.phone || '',
|
||||
domain: new URL(metadata.url).hostname,
|
||||
},
|
||||
|
||||
channelScores: buildChannelScores(r.channelAnalysis),
|
||||
|
||||
youtubeAudit: {
|
||||
channelName: clinic.name || '',
|
||||
handle: '',
|
||||
subscribers: r.channelAnalysis?.youtube?.subscribers ?? 0,
|
||||
totalVideos: 0,
|
||||
totalViews: 0,
|
||||
weeklyViewGrowth: { absolute: 0, percentage: 0 },
|
||||
estimatedMonthlyRevenue: { min: 0, max: 0 },
|
||||
avgVideoLength: '-',
|
||||
uploadFrequency: '-',
|
||||
channelCreatedDate: '',
|
||||
subscriberRank: '-',
|
||||
channelDescription: '',
|
||||
linkedUrls: [],
|
||||
playlists: [],
|
||||
topVideos: [],
|
||||
diagnosis: (r.channelAnalysis?.youtube?.recommendation)
|
||||
? [{ category: 'YouTube', detail: r.channelAnalysis.youtube.recommendation, severity: scoreToSeverity(r.channelAnalysis.youtube.score) }]
|
||||
: [],
|
||||
},
|
||||
|
||||
instagramAudit: {
|
||||
accounts: r.channelAnalysis?.instagram ? [{
|
||||
handle: '',
|
||||
language: 'KR',
|
||||
label: '메인',
|
||||
posts: r.channelAnalysis.instagram.posts ?? 0,
|
||||
followers: r.channelAnalysis.instagram.followers ?? 0,
|
||||
following: 0,
|
||||
category: '의료/건강',
|
||||
profileLink: '',
|
||||
highlights: [],
|
||||
reelsCount: 0,
|
||||
contentFormat: '',
|
||||
profilePhoto: '',
|
||||
bio: '',
|
||||
}] : [],
|
||||
diagnosis: (r.channelAnalysis?.instagram?.recommendation)
|
||||
? [{ category: 'Instagram', detail: r.channelAnalysis.instagram.recommendation, severity: scoreToSeverity(r.channelAnalysis.instagram.score) }]
|
||||
: [],
|
||||
},
|
||||
|
||||
facebookAudit: {
|
||||
pages: [],
|
||||
diagnosis: [],
|
||||
brandInconsistencies: [],
|
||||
consolidationRecommendation: '',
|
||||
},
|
||||
|
||||
otherChannels: [
|
||||
...(r.channelAnalysis?.naverBlog ? [{
|
||||
name: '네이버 블로그',
|
||||
status: (r.channelAnalysis.naverBlog.status === 'active' ? 'active' : 'inactive') as 'active' | 'inactive',
|
||||
details: r.channelAnalysis.naverBlog.recommendation || '',
|
||||
}] : []),
|
||||
...(r.channelAnalysis?.naverPlace ? [{
|
||||
name: '네이버 플레이스',
|
||||
status: (r.channelAnalysis.naverPlace.status === 'active' ? 'active' : 'inactive') as 'active' | 'inactive',
|
||||
details: `평점: ${r.channelAnalysis.naverPlace.rating ?? '-'} / 리뷰: ${r.channelAnalysis.naverPlace.reviews ?? '-'}`,
|
||||
}] : []),
|
||||
...(r.channelAnalysis?.gangnamUnni ? [{
|
||||
name: '강남언니',
|
||||
status: (r.channelAnalysis.gangnamUnni.status === 'active' ? 'active' : 'inactive') as 'active' | 'inactive',
|
||||
details: `평점: ${r.channelAnalysis.gangnamUnni.rating ?? '-'} / 리뷰: ${r.channelAnalysis.gangnamUnni.reviews ?? '-'}`,
|
||||
}] : []),
|
||||
],
|
||||
|
||||
websiteAudit: {
|
||||
primaryDomain: new URL(metadata.url).hostname,
|
||||
additionalDomains: [],
|
||||
snsLinksOnSite: false,
|
||||
trackingPixels: [],
|
||||
mainCTA: '',
|
||||
},
|
||||
|
||||
problemDiagnosis: buildDiagnosis(r),
|
||||
|
||||
transformation: {
|
||||
brandIdentity: [],
|
||||
contentStrategy: (r.recommendations || [])
|
||||
.filter(rec => rec.category?.includes('콘텐츠') || rec.category?.includes('content'))
|
||||
.map(rec => ({
|
||||
area: rec.title || '',
|
||||
asIs: rec.description || '',
|
||||
toBe: rec.expectedImpact || '',
|
||||
})),
|
||||
platformStrategies: buildChannelScores(r.channelAnalysis).map(ch => ({
|
||||
platform: ch.channel,
|
||||
icon: ch.icon,
|
||||
currentMetric: `점수: ${ch.score}`,
|
||||
targetMetric: `목표: ${Math.min(ch.score + 20, 100)}`,
|
||||
strategies: [],
|
||||
})),
|
||||
websiteImprovements: (r.channelAnalysis?.website?.issues || []).map(issue => ({
|
||||
area: '웹사이트',
|
||||
asIs: issue,
|
||||
toBe: '개선 필요',
|
||||
})),
|
||||
newChannelProposals: [],
|
||||
},
|
||||
|
||||
roadmap: [1, 2, 3].map(month => ({
|
||||
month,
|
||||
title: `${month}개월차`,
|
||||
subtitle: month === 1 ? '기반 구축' : month === 2 ? '콘텐츠 강화' : '성과 최적화',
|
||||
tasks: (r.recommendations || [])
|
||||
.filter(rec => {
|
||||
if (month === 1) return rec.priority === 'high';
|
||||
if (month === 2) return rec.priority === 'medium';
|
||||
return rec.priority === 'low';
|
||||
})
|
||||
.slice(0, 4)
|
||||
.map(rec => ({ task: rec.title || rec.description || '', completed: false })),
|
||||
})),
|
||||
|
||||
kpiDashboard: [
|
||||
{ metric: '종합 점수', current: `${r.overallScore ?? '-'}`, target3Month: `${Math.min((r.overallScore ?? 50) + 15, 100)}`, target12Month: `${Math.min((r.overallScore ?? 50) + 30, 100)}` },
|
||||
...(r.channelAnalysis?.instagram ? [
|
||||
{ metric: 'Instagram 팔로워', current: `${r.channelAnalysis.instagram.followers ?? 0}`, target3Month: `${Math.round((r.channelAnalysis.instagram.followers ?? 0) * 1.3)}`, target12Month: `${Math.round((r.channelAnalysis.instagram.followers ?? 0) * 2)}` },
|
||||
] : []),
|
||||
...(r.channelAnalysis?.youtube ? [
|
||||
{ metric: 'YouTube 구독자', current: `${r.channelAnalysis.youtube.subscribers ?? 0}`, target3Month: `${Math.round((r.channelAnalysis.youtube.subscribers ?? 0) * 1.5)}`, target12Month: `${Math.round((r.channelAnalysis.youtube.subscribers ?? 0) * 3)}` },
|
||||
] : []),
|
||||
],
|
||||
|
||||
screenshots: [],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Enrichment data shape from enrich-channels Edge Function.
|
||||
*/
|
||||
export interface EnrichmentData {
|
||||
instagram?: {
|
||||
username?: string;
|
||||
followers?: number;
|
||||
following?: number;
|
||||
posts?: number;
|
||||
bio?: string;
|
||||
isBusinessAccount?: boolean;
|
||||
externalUrl?: string;
|
||||
latestPosts?: {
|
||||
type?: string;
|
||||
likes?: number;
|
||||
comments?: number;
|
||||
caption?: string;
|
||||
timestamp?: string;
|
||||
}[];
|
||||
};
|
||||
googleMaps?: {
|
||||
name?: string;
|
||||
rating?: number;
|
||||
reviewCount?: number;
|
||||
address?: string;
|
||||
phone?: string;
|
||||
website?: string;
|
||||
category?: string;
|
||||
openingHours?: unknown;
|
||||
topReviews?: {
|
||||
stars?: number;
|
||||
text?: string;
|
||||
publishedAtDate?: string;
|
||||
}[];
|
||||
};
|
||||
youtube?: {
|
||||
channelId?: string;
|
||||
channelName?: string;
|
||||
handle?: string;
|
||||
description?: string;
|
||||
publishedAt?: string;
|
||||
thumbnailUrl?: string;
|
||||
subscribers?: number;
|
||||
totalViews?: number;
|
||||
totalVideos?: number;
|
||||
videos?: {
|
||||
title?: string;
|
||||
views?: number;
|
||||
likes?: number;
|
||||
comments?: number;
|
||||
date?: string;
|
||||
duration?: string;
|
||||
url?: string;
|
||||
thumbnail?: string;
|
||||
}[];
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge enrichment data into an existing MarketingReport.
|
||||
* Returns a new object — does not mutate the original.
|
||||
*/
|
||||
export function mergeEnrichment(
|
||||
report: MarketingReport,
|
||||
enrichment: EnrichmentData,
|
||||
): MarketingReport {
|
||||
const merged = { ...report };
|
||||
|
||||
// Instagram enrichment
|
||||
if (enrichment.instagram) {
|
||||
const ig = enrichment.instagram;
|
||||
const existingAccount = merged.instagramAudit.accounts[0];
|
||||
|
||||
merged.instagramAudit = {
|
||||
...merged.instagramAudit,
|
||||
accounts: [{
|
||||
handle: ig.username || existingAccount?.handle || '',
|
||||
language: 'KR',
|
||||
label: '메인',
|
||||
posts: ig.posts ?? existingAccount?.posts ?? 0,
|
||||
followers: ig.followers ?? existingAccount?.followers ?? 0,
|
||||
following: ig.following ?? existingAccount?.following ?? 0,
|
||||
category: '의료/건강',
|
||||
profileLink: ig.username ? `https://instagram.com/${ig.username}` : '',
|
||||
highlights: [],
|
||||
reelsCount: 0,
|
||||
contentFormat: ig.isBusinessAccount ? '비즈니스 계정' : '일반 계정',
|
||||
profilePhoto: '',
|
||||
bio: ig.bio || '',
|
||||
}],
|
||||
};
|
||||
|
||||
// Update KPI with real follower data
|
||||
merged.kpiDashboard = merged.kpiDashboard.map(kpi =>
|
||||
kpi.metric === 'Instagram 팔로워' && ig.followers
|
||||
? {
|
||||
...kpi,
|
||||
current: `${ig.followers.toLocaleString()}`,
|
||||
target3Month: `${Math.round(ig.followers * 1.3).toLocaleString()}`,
|
||||
target12Month: `${Math.round(ig.followers * 2).toLocaleString()}`,
|
||||
}
|
||||
: kpi
|
||||
);
|
||||
}
|
||||
|
||||
// YouTube enrichment (YouTube Data API v3)
|
||||
if (enrichment.youtube) {
|
||||
const yt = enrichment.youtube;
|
||||
const videos = yt.videos || [];
|
||||
|
||||
// Parse ISO 8601 duration (PT1H2M3S) to readable format
|
||||
const parseDuration = (iso?: string): string => {
|
||||
if (!iso) return '-';
|
||||
const match = iso.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);
|
||||
if (!match) return iso;
|
||||
const h = match[1] ? `${match[1]}:` : '';
|
||||
const m = match[2] || '0';
|
||||
const s = (match[3] || '0').padStart(2, '0');
|
||||
return h ? `${h}${m.padStart(2, '0')}:${s}` : `${m}:${s}`;
|
||||
};
|
||||
|
||||
// Check if video is a Short (< 60 seconds)
|
||||
const isShort = (iso?: string): boolean => {
|
||||
if (!iso) return false;
|
||||
const match = iso.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);
|
||||
if (!match) return false;
|
||||
const totalSec = (parseInt(match[1] || '0') * 3600) + (parseInt(match[2] || '0') * 60) + parseInt(match[3] || '0');
|
||||
return totalSec <= 60;
|
||||
};
|
||||
|
||||
merged.youtubeAudit = {
|
||||
...merged.youtubeAudit,
|
||||
channelName: yt.channelName || merged.youtubeAudit.channelName,
|
||||
handle: yt.handle || merged.youtubeAudit.handle,
|
||||
subscribers: yt.subscribers ?? merged.youtubeAudit.subscribers,
|
||||
totalVideos: yt.totalVideos ?? merged.youtubeAudit.totalVideos,
|
||||
totalViews: yt.totalViews ?? merged.youtubeAudit.totalViews,
|
||||
channelDescription: yt.description || merged.youtubeAudit.channelDescription,
|
||||
channelCreatedDate: yt.publishedAt ? new Date(yt.publishedAt).toLocaleDateString('ko-KR') : merged.youtubeAudit.channelCreatedDate,
|
||||
topVideos: videos.slice(0, 5).map((v): TopVideo => ({
|
||||
title: v.title || '',
|
||||
views: v.views || 0,
|
||||
uploadedAgo: v.date ? new Date(v.date).toLocaleDateString('ko-KR') : '',
|
||||
type: isShort(v.duration) ? 'Short' : 'Long',
|
||||
duration: parseDuration(v.duration),
|
||||
})),
|
||||
};
|
||||
|
||||
// Update KPI with real subscriber data
|
||||
if (yt.subscribers) {
|
||||
merged.kpiDashboard = merged.kpiDashboard.map(kpi =>
|
||||
kpi.metric === 'YouTube 구독자'
|
||||
? {
|
||||
...kpi,
|
||||
current: `${yt.subscribers!.toLocaleString()}`,
|
||||
target3Month: `${Math.round(yt.subscribers! * 1.5).toLocaleString()}`,
|
||||
target12Month: `${Math.round(yt.subscribers! * 3).toLocaleString()}`,
|
||||
}
|
||||
: kpi
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Google Maps enrichment
|
||||
if (enrichment.googleMaps) {
|
||||
const gm = enrichment.googleMaps;
|
||||
|
||||
merged.clinicSnapshot = {
|
||||
...merged.clinicSnapshot,
|
||||
overallRating: gm.rating ?? merged.clinicSnapshot.overallRating,
|
||||
totalReviews: gm.reviewCount ?? merged.clinicSnapshot.totalReviews,
|
||||
phone: gm.phone || merged.clinicSnapshot.phone,
|
||||
location: gm.address || merged.clinicSnapshot.location,
|
||||
};
|
||||
|
||||
// Update or add Google Maps to otherChannels
|
||||
const gmChannelIdx = merged.otherChannels.findIndex(c => c.name === '구글 지도');
|
||||
const gmChannel = {
|
||||
name: '구글 지도',
|
||||
status: 'active' as const,
|
||||
details: `평점: ${gm.rating ?? '-'} / 리뷰: ${gm.reviewCount ?? '-'}`,
|
||||
url: '',
|
||||
};
|
||||
if (gmChannelIdx >= 0) {
|
||||
merged.otherChannels[gmChannelIdx] = gmChannel;
|
||||
} else {
|
||||
merged.otherChannels = [...merged.otherChannels, gmChannel];
|
||||
}
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
@@ -1,52 +1,82 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { useNavigate, useLocation } from 'react-router';
|
||||
import { motion } from 'motion/react';
|
||||
import { Check } from 'lucide-react';
|
||||
import { Check, AlertCircle } from 'lucide-react';
|
||||
import { generateMarketingReport } from '../lib/supabase';
|
||||
|
||||
const steps = [
|
||||
'Scanning website...',
|
||||
'Capturing channel screenshots...',
|
||||
'Analyzing social media presence...',
|
||||
'Evaluating brand consistency...',
|
||||
'Generating intelligence report...',
|
||||
{ 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' },
|
||||
];
|
||||
|
||||
export default function AnalysisLoadingPage() {
|
||||
const [currentStep, setCurrentStep] = useState(0);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const url = (location.state as { url?: string })?.url;
|
||||
const hasStarted = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
const timers: ReturnType<typeof setTimeout>[] = [];
|
||||
if (hasStarted.current) return;
|
||||
hasStarted.current = true;
|
||||
|
||||
steps.forEach((_, index) => {
|
||||
timers.push(
|
||||
setTimeout(() => {
|
||||
setCurrentStep(index + 1);
|
||||
}, (index + 1) * 1250)
|
||||
);
|
||||
});
|
||||
if (!url) {
|
||||
navigate('/', { replace: true });
|
||||
return;
|
||||
}
|
||||
|
||||
timers.push(
|
||||
setTimeout(() => {
|
||||
navigate('/report/view-clinic', { replace: true });
|
||||
}, 5500)
|
||||
);
|
||||
const runAnalysis = async () => {
|
||||
try {
|
||||
// Step 1: Scraping
|
||||
setCurrentStep(1);
|
||||
|
||||
return () => timers.forEach(clearTimeout);
|
||||
}, [navigate]);
|
||||
// Simulate step progression while waiting for API
|
||||
const stepTimer = setInterval(() => {
|
||||
setCurrentStep((prev) => (prev < steps.length - 1 ? prev + 1 : prev));
|
||||
}, 5000);
|
||||
|
||||
const result = await generateMarketingReport(url);
|
||||
|
||||
clearInterval(stepTimer);
|
||||
setCurrentStep(steps.length);
|
||||
|
||||
if (result.success && result.report) {
|
||||
const reportPath = result.reportId
|
||||
? `/report/${result.reportId}`
|
||||
: '/report/live';
|
||||
|
||||
// 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');
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'An error occurred');
|
||||
}
|
||||
};
|
||||
|
||||
runAnalysis();
|
||||
}, [url, navigate]);
|
||||
|
||||
return (
|
||||
<div className="relative min-h-screen bg-primary-900 flex flex-col items-center justify-center px-6 overflow-hidden">
|
||||
{/* Radial gradient overlay */}
|
||||
<div className="absolute inset-0 bg-[radial-gradient(ellipse_at_center,_rgba(79,29,161,0.25)_0%,_transparent_70%)]" />
|
||||
|
||||
{/* Purple glow blob */}
|
||||
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[500px] h-[500px] bg-purple-600/20 rounded-full blur-[120px] pointer-events-none" />
|
||||
|
||||
<div className="relative z-10 flex flex-col items-center w-full max-w-lg">
|
||||
{/* INFINITH logo text */}
|
||||
<motion.h1
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
@@ -56,7 +86,6 @@ export default function AnalysisLoadingPage() {
|
||||
INFINITH
|
||||
</motion.h1>
|
||||
|
||||
{/* Entered URL */}
|
||||
{url && (
|
||||
<motion.p
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
@@ -68,64 +97,82 @@ export default function AnalysisLoadingPage() {
|
||||
</motion.p>
|
||||
)}
|
||||
|
||||
{/* Analysis steps */}
|
||||
<div className="w-full space-y-5 mb-14">
|
||||
{steps.map((step, index) => {
|
||||
const isCompleted = currentStep > index;
|
||||
const isActive = currentStep === index;
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
key={step}
|
||||
initial={{ opacity: 0, x: -20 }}
|
||||
animate={{ opacity: isActive || isCompleted ? 1 : 0.3, x: 0 }}
|
||||
transition={{ duration: 0.4, delay: index * 0.15 }}
|
||||
className="flex items-center gap-4"
|
||||
>
|
||||
{/* Status icon */}
|
||||
<div className="w-7 h-7 flex-shrink-0 flex items-center justify-center">
|
||||
{isCompleted ? (
|
||||
<motion.div
|
||||
initial={{ scale: 0 }}
|
||||
animate={{ scale: 1 }}
|
||||
transition={{ type: 'spring', stiffness: 300, damping: 20 }}
|
||||
className="w-7 h-7 rounded-full bg-gradient-to-r from-[#4F1DA1] to-[#6C5CE7] flex items-center justify-center"
|
||||
>
|
||||
<Check className="w-4 h-4 text-white" strokeWidth={3} />
|
||||
</motion.div>
|
||||
) : isActive ? (
|
||||
<div className="w-7 h-7 rounded-full border-2 border-purple-400 border-t-transparent animate-spin" />
|
||||
) : (
|
||||
<div className="w-7 h-7 rounded-full border-2 border-white/10" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Step text */}
|
||||
<span
|
||||
className={`text-base font-sans transition-colors duration-300 ${
|
||||
isCompleted
|
||||
? 'text-white'
|
||||
: isActive
|
||||
? 'text-purple-200'
|
||||
: 'text-white/30'
|
||||
}`}
|
||||
>
|
||||
{step}
|
||||
</span>
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Progress bar */}
|
||||
<div className="w-full h-2 bg-white/10 rounded-full overflow-hidden">
|
||||
{error ? (
|
||||
<motion.div
|
||||
initial={{ width: '0%' }}
|
||||
animate={{ width: '100%' }}
|
||||
transition={{ duration: 5, ease: 'linear' }}
|
||||
className="h-full bg-gradient-to-r from-[#4F1DA1] to-[#6C5CE7] rounded-full"
|
||||
/>
|
||||
</div>
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
className="w-full p-6 rounded-2xl bg-red-500/10 border border-red-500/20 text-center"
|
||||
>
|
||||
<AlertCircle className="w-10 h-10 text-red-400 mx-auto mb-3" />
|
||||
<p className="text-red-300 text-sm mb-4">{error}</p>
|
||||
<button
|
||||
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;
|
||||
|
||||
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 }}
|
||||
className="flex items-center gap-4"
|
||||
>
|
||||
<div className="w-7 h-7 flex-shrink-0 flex items-center justify-center">
|
||||
{isCompleted ? (
|
||||
<motion.div
|
||||
initial={{ scale: 0 }}
|
||||
animate={{ scale: 1 }}
|
||||
transition={{ type: 'spring', stiffness: 300, damping: 20 }}
|
||||
className="w-7 h-7 rounded-full bg-gradient-to-r from-[#4F1DA1] to-[#6C5CE7] flex items-center justify-center"
|
||||
>
|
||||
<Check className="w-4 h-4 text-white" strokeWidth={3} />
|
||||
</motion.div>
|
||||
) : isActive ? (
|
||||
<div className="w-7 h-7 rounded-full border-2 border-purple-400 border-t-transparent animate-spin" />
|
||||
) : (
|
||||
<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>
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="w-full h-2 bg-white/10 rounded-full overflow-hidden">
|
||||
<motion.div
|
||||
initial={{ width: '0%' }}
|
||||
animate={{ width: `${(currentStep / 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초 소요됩니다.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useParams } from 'react-router';
|
||||
import { useMemo } from 'react';
|
||||
import { useParams, useLocation } from 'react-router';
|
||||
import { useReport } from '../hooks/useReport';
|
||||
import { useEnrichment } from '../hooks/useEnrichment';
|
||||
import { ReportNav } from '../components/report/ReportNav';
|
||||
import { ScreenshotProvider } from '../contexts/ScreenshotContext';
|
||||
|
||||
@@ -25,14 +27,47 @@ const REPORT_SECTIONS = [
|
||||
{ id: 'facebook-audit', label: 'Facebook' },
|
||||
{ id: 'other-channels', label: '기타 채널' },
|
||||
{ id: 'problem-diagnosis', label: '문제 진단' },
|
||||
{ id: 'transformation', label: '변환 전략' },
|
||||
{ id: 'roadmap', label: '로드맵' },
|
||||
{ id: 'kpi-dashboard', label: 'KPI' },
|
||||
];
|
||||
|
||||
export default function ReportPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const { data, isLoading, error } = useReport(id);
|
||||
const location = useLocation();
|
||||
const { data: baseData, isLoading, error } = useReport(id);
|
||||
|
||||
// Extract enrichment params from location state (socialHandles from API) or base data
|
||||
const enrichmentParams = useMemo(() => {
|
||||
if (!baseData) return null;
|
||||
|
||||
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;
|
||||
|
||||
// Priority: API socialHandles > transformed data > undefined
|
||||
const igHandle =
|
||||
socialHandles?.instagram ||
|
||||
baseData.instagramAudit?.accounts?.[0]?.handle ||
|
||||
undefined;
|
||||
|
||||
const ytHandle =
|
||||
socialHandles?.youtube ||
|
||||
baseData.youtubeAudit?.handle ||
|
||||
undefined;
|
||||
|
||||
return {
|
||||
reportId: baseData.id,
|
||||
clinicName: baseData.clinicSnapshot.name,
|
||||
instagramHandle: igHandle || undefined,
|
||||
youtubeChannelId: ytHandle || undefined,
|
||||
address: baseData.clinicSnapshot.location || undefined,
|
||||
};
|
||||
}, [baseData, location.state]);
|
||||
|
||||
const { status: enrichStatus, enrichedReport } = useEnrichment(baseData, enrichmentParams);
|
||||
|
||||
// Use enriched data when available, otherwise base data
|
||||
const data = enrichedReport || baseData;
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
@@ -61,6 +96,14 @@ export default function ReportPage() {
|
||||
<div className="pt-20">
|
||||
<ReportNav sections={REPORT_SECTIONS} />
|
||||
|
||||
{/* Enrichment status indicator */}
|
||||
{enrichStatus === 'loading' && (
|
||||
<div className="fixed bottom-6 right-6 z-50 flex items-center gap-3 px-4 py-3 bg-white rounded-xl shadow-[3px_4px_12px_rgba(0,0,0,0.06)] border border-slate-100">
|
||||
<div className="w-4 h-4 border-2 border-[#6C5CE7] border-t-transparent rounded-full animate-spin" />
|
||||
<span className="text-xs text-slate-500">채널 데이터 보강 중...</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div data-report-content>
|
||||
<ReportHeader
|
||||
overallScore={data.overallScore}
|
||||
|
||||
Reference in new issue
Block a user