fix: add Authorization header to all Edge Function calls + fix Vision Analysis
- All fetch calls to Supabase Edge Functions now include Authorization: Bearer <anon_key> (was missing → 401 errors) - Fix Firecrawl screenshot API: remove invalid screenshotOptions, use "screenshot@fullPage" format (v2 API compatibility) - Fix screenshot response handling: v2 returns URL not base64, now downloads and converts to base64 for Gemini Vision - Add about page to Vision Analysis capture targets - Add retry utility, channel error tracking, pipeline resume, enrichment retry, EmptyState improvements (Sprint 2-3) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
2f2aa5a5b6
commit
79950925a1
12 files changed
+961
-214
No files matched your search
+1
-1
@@ -5,7 +5,7 @@ import PageNavigator from './components/PageNavigator';
|
||||
|
||||
export default function App() {
|
||||
const location = useLocation();
|
||||
const isLoadingPage = location.pathname === '/report/loading';
|
||||
const isLoadingPage = location.pathname.startsWith('/report/loading');
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-50 selection:bg-purple-200 selection:text-primary-900">
|
||||
|
||||
@@ -1,19 +1,83 @@
|
||||
import { motion } from 'motion/react';
|
||||
import { Search } from 'lucide-react';
|
||||
import { Search, AlertCircle, Info, RefreshCw } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
type EmptyStatus = 'loading' | 'error' | 'not_found' | 'timeout';
|
||||
|
||||
interface EmptyStateProps {
|
||||
message?: string;
|
||||
subtext?: string;
|
||||
status?: EmptyStatus;
|
||||
onRetry?: () => void;
|
||||
/** Auto-timeout: switch to 'timeout' status after N seconds (default: 60) */
|
||||
autoTimeoutSec?: number;
|
||||
}
|
||||
|
||||
const STATUS_CONFIG: Record<EmptyStatus, {
|
||||
icon: typeof Search;
|
||||
iconColor: string;
|
||||
bgColor: string;
|
||||
defaultMessage: string;
|
||||
defaultSubtext: string;
|
||||
}> = {
|
||||
loading: {
|
||||
icon: Search,
|
||||
iconColor: 'text-slate-400',
|
||||
bgColor: 'bg-slate-100',
|
||||
defaultMessage: '데이터 수집 중',
|
||||
defaultSubtext: '채널 데이터 보강이 완료되면 자동으로 업데이트됩니다.',
|
||||
},
|
||||
error: {
|
||||
icon: AlertCircle,
|
||||
iconColor: 'text-red-400',
|
||||
bgColor: 'bg-red-50',
|
||||
defaultMessage: '데이터 수집 실패',
|
||||
defaultSubtext: '일시적인 오류가 발생했습니다. 다시 시도해 주세요.',
|
||||
},
|
||||
not_found: {
|
||||
icon: Info,
|
||||
iconColor: 'text-blue-400',
|
||||
bgColor: 'bg-blue-50',
|
||||
defaultMessage: '채널을 찾을 수 없음',
|
||||
defaultSubtext: '이 채널은 발견되지 않았거나 데이터가 없습니다.',
|
||||
},
|
||||
timeout: {
|
||||
icon: AlertCircle,
|
||||
iconColor: 'text-amber-400',
|
||||
bgColor: 'bg-amber-50',
|
||||
defaultMessage: '응답 시간 초과',
|
||||
defaultSubtext: '데이터 수집에 시간이 오래 걸리고 있습니다.',
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Shown inside report sections when data is not yet available
|
||||
* (e.g., before enrichment completes or when a channel is not found).
|
||||
* (e.g., before enrichment completes, when a channel is not found, or on error).
|
||||
*/
|
||||
export function EmptyState({
|
||||
message = '데이터 수집 중',
|
||||
subtext = '채널 데이터 보강이 완료되면 자동으로 업데이트됩니다.',
|
||||
message,
|
||||
subtext,
|
||||
status = 'loading',
|
||||
onRetry,
|
||||
autoTimeoutSec = 60,
|
||||
}: EmptyStateProps) {
|
||||
const [currentStatus, setCurrentStatus] = useState<EmptyStatus>(status);
|
||||
|
||||
// Auto-timeout: switch from 'loading' to 'timeout' after N seconds
|
||||
useEffect(() => {
|
||||
if (status !== 'loading') return;
|
||||
const timer = setTimeout(() => setCurrentStatus('timeout'), autoTimeoutSec * 1000);
|
||||
return () => clearTimeout(timer);
|
||||
}, [status, autoTimeoutSec]);
|
||||
|
||||
// Sync external status changes
|
||||
useEffect(() => {
|
||||
setCurrentStatus(status);
|
||||
}, [status]);
|
||||
|
||||
const config = STATUS_CONFIG[currentStatus];
|
||||
const Icon = config.icon;
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
className="flex flex-col items-center justify-center py-12 text-center"
|
||||
@@ -21,11 +85,25 @@ export function EmptyState({
|
||||
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 className={`w-12 h-12 rounded-2xl ${config.bgColor} flex items-center justify-center mb-4`}>
|
||||
{currentStatus === 'loading' ? (
|
||||
<div className="w-5 h-5 border-2 border-slate-300 border-t-slate-500 rounded-full animate-spin" />
|
||||
) : (
|
||||
<Icon size={20} className={config.iconColor} />
|
||||
)}
|
||||
</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>
|
||||
<p className="text-sm font-medium text-slate-500">{message || config.defaultMessage}</p>
|
||||
<p className="text-xs text-slate-400 mt-1 max-w-xs">{subtext || config.defaultSubtext}</p>
|
||||
|
||||
{onRetry && (currentStatus === 'error' || currentStatus === 'timeout') && (
|
||||
<button
|
||||
onClick={onRetry}
|
||||
className="mt-4 flex items-center gap-1.5 px-4 py-1.5 text-xs font-medium text-purple-600 bg-purple-50 rounded-lg hover:bg-purple-100 transition-colors"
|
||||
>
|
||||
<RefreshCw size={12} />
|
||||
다시 시도
|
||||
</button>
|
||||
)}
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
+46
-25
@@ -8,6 +8,10 @@ type EnrichmentStatus = 'idle' | 'loading' | 'success' | 'error';
|
||||
interface UseEnrichmentResult {
|
||||
status: EnrichmentStatus;
|
||||
enrichedReport: MarketingReport | null;
|
||||
/** Number of retry attempts made */
|
||||
retryCount: number;
|
||||
/** Call this to retry enrichment (max 2 retries) */
|
||||
retry: () => void;
|
||||
}
|
||||
|
||||
interface EnrichmentParams {
|
||||
@@ -20,10 +24,12 @@ interface EnrichmentParams {
|
||||
address?: string;
|
||||
}
|
||||
|
||||
const MAX_RETRIES = 2;
|
||||
|
||||
/**
|
||||
* Triggers background channel enrichment after Phase 1 report renders.
|
||||
* Fires once, waits for the Edge Function to complete (~27s),
|
||||
* then returns the merged report.
|
||||
* then returns the merged report. Supports up to 2 manual retries.
|
||||
*/
|
||||
export function useEnrichment(
|
||||
baseReport: MarketingReport | null,
|
||||
@@ -31,40 +37,55 @@ export function useEnrichment(
|
||||
): UseEnrichmentResult {
|
||||
const [status, setStatus] = useState<EnrichmentStatus>('idle');
|
||||
const [enrichedReport, setEnrichedReport] = useState<MarketingReport | null>(null);
|
||||
const [retryCount, setRetryCount] = useState(0);
|
||||
const hasTriggered = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!baseReport || !params?.reportId || hasTriggered.current) return;
|
||||
// Always enrich if clinicName exists — Naver, 강남언니, Google Maps work with name alone
|
||||
const doEnrich = useCallback(async () => {
|
||||
if (!baseReport || !params?.reportId) return;
|
||||
|
||||
hasTriggered.current = true;
|
||||
setStatus('loading');
|
||||
|
||||
enrichChannels({
|
||||
reportId: params.reportId,
|
||||
clinicName: params.clinicName,
|
||||
instagramHandle: params.instagramHandle,
|
||||
instagramHandles: params.instagramHandles,
|
||||
youtubeChannelId: params.youtubeChannelId,
|
||||
facebookHandle: params.facebookHandle,
|
||||
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');
|
||||
try {
|
||||
const result = await enrichChannels({
|
||||
reportId: params.reportId,
|
||||
clinicName: params.clinicName,
|
||||
instagramHandle: params.instagramHandle,
|
||||
instagramHandles: params.instagramHandles,
|
||||
youtubeChannelId: params.youtubeChannelId,
|
||||
facebookHandle: params.facebookHandle,
|
||||
address: params.address,
|
||||
});
|
||||
|
||||
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]);
|
||||
|
||||
// Initial trigger
|
||||
useEffect(() => {
|
||||
if (!baseReport || !params?.reportId || hasTriggered.current) return;
|
||||
hasTriggered.current = true;
|
||||
doEnrich();
|
||||
}, [baseReport, params, doEnrich]);
|
||||
|
||||
// Manual retry
|
||||
const retry = useCallback(() => {
|
||||
if (retryCount >= MAX_RETRIES) return;
|
||||
setRetryCount(prev => prev + 1);
|
||||
doEnrich();
|
||||
}, [retryCount, doEnrich]);
|
||||
|
||||
return {
|
||||
status,
|
||||
enrichedReport,
|
||||
retryCount,
|
||||
retry,
|
||||
};
|
||||
}
|
||||
+44
-6
@@ -5,12 +5,18 @@ const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY;
|
||||
|
||||
export const supabase = createClient(supabaseUrl, supabaseAnonKey);
|
||||
|
||||
/** Common headers for Edge Function calls (includes JWT auth) */
|
||||
const fnHeaders = () => ({
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": `Bearer ${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" },
|
||||
headers: fnHeaders(),
|
||||
body: JSON.stringify({ url, clinicName }),
|
||||
}
|
||||
);
|
||||
@@ -33,6 +39,38 @@ export async function fetchReportById(reportId: string) {
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch pipeline status for a report.
|
||||
* Used by AnalysisLoadingPage to resume interrupted pipelines.
|
||||
*/
|
||||
export interface PipelineStatus {
|
||||
reportId: string;
|
||||
clinicId?: string;
|
||||
runId?: string;
|
||||
status: string;
|
||||
clinicName?: string;
|
||||
hasChannelData: boolean;
|
||||
hasReport: boolean;
|
||||
}
|
||||
|
||||
export async function fetchPipelineStatus(reportId: string): Promise<PipelineStatus> {
|
||||
const { data, error } = await supabase
|
||||
.from("marketing_reports")
|
||||
.select("id, status, clinic_name, channel_data, report")
|
||||
.eq("id", reportId)
|
||||
.single();
|
||||
|
||||
if (error || !data) throw new Error(`Report not found: ${error?.message}`);
|
||||
|
||||
return {
|
||||
reportId: data.id,
|
||||
status: data.status || "unknown",
|
||||
clinicName: data.clinic_name,
|
||||
hasChannelData: !!data.channel_data && Object.keys(data.channel_data).length > 0,
|
||||
hasReport: !!data.report && Object.keys(data.report).length > 0,
|
||||
};
|
||||
}
|
||||
|
||||
export interface EnrichChannelsRequest {
|
||||
reportId: string;
|
||||
clinicName: string;
|
||||
@@ -52,7 +90,7 @@ export async function enrichChannels(params: EnrichChannelsRequest) {
|
||||
`${supabaseUrl}/functions/v1/enrich-channels`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
headers: fnHeaders(),
|
||||
body: JSON.stringify(params),
|
||||
}
|
||||
);
|
||||
@@ -69,7 +107,7 @@ export async function scrapeWebsite(url: string, clinicName?: string) {
|
||||
`${supabaseUrl}/functions/v1/scrape-website`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
headers: fnHeaders(),
|
||||
body: JSON.stringify({ url, clinicName }),
|
||||
}
|
||||
);
|
||||
@@ -92,7 +130,7 @@ export async function discoverChannels(url: string, clinicName?: string) {
|
||||
`${supabaseUrl}/functions/v1/discover-channels`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
headers: fnHeaders(),
|
||||
body: JSON.stringify({ url, clinicName }),
|
||||
}
|
||||
);
|
||||
@@ -113,7 +151,7 @@ export async function collectChannelData(reportId: string, clinicId?: string, ru
|
||||
`${supabaseUrl}/functions/v1/collect-channel-data`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
headers: fnHeaders(),
|
||||
body: JSON.stringify({ reportId, clinicId, runId }),
|
||||
}
|
||||
);
|
||||
@@ -133,7 +171,7 @@ export async function generateReportV2(reportId: string, clinicId?: string, runI
|
||||
`${supabaseUrl}/functions/v1/generate-report`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
headers: fnHeaders(),
|
||||
body: JSON.stringify({ reportId, clinicId, runId }),
|
||||
}
|
||||
);
|
||||
|
||||
@@ -21,6 +21,7 @@ createRoot(document.getElementById('root')!).render(
|
||||
<Route element={<App />}>
|
||||
<Route index element={<LandingPage />} />
|
||||
<Route path="report/loading" element={<AnalysisLoadingPage />} />
|
||||
<Route path="report/loading/:reportId" element={<AnalysisLoadingPage />} />
|
||||
<Route path="report/:id" element={<ReportPage />} />
|
||||
<Route path="plan/:id" element={<MarketingPlanPage />} />
|
||||
<Route path="studio/:id" element={<ContentStudioPage />} />
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { useNavigate, useLocation } from 'react-router';
|
||||
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { useNavigate, useLocation, useParams } from 'react-router';
|
||||
import { motion } from 'motion/react';
|
||||
import { Check, AlertCircle } from 'lucide-react';
|
||||
import { discoverChannels, collectChannelData, generateReportV2 } from '../lib/supabase';
|
||||
import { Check, AlertCircle, RefreshCw } from 'lucide-react';
|
||||
import {
|
||||
discoverChannels,
|
||||
collectChannelData,
|
||||
generateReportV2,
|
||||
fetchPipelineStatus,
|
||||
} from '../lib/supabase';
|
||||
|
||||
type Phase = 'discovering' | 'collecting' | 'generating' | 'complete';
|
||||
type Phase = 'resuming' | 'discovering' | 'collecting' | 'generating' | 'complete';
|
||||
|
||||
const PHASE_STEPS = [
|
||||
{ key: 'discovering' as Phase, label: 'Scanning website & discovering channels...', labelDone: 'Channels discovered' },
|
||||
@@ -13,47 +18,95 @@ const PHASE_STEPS = [
|
||||
{ key: 'complete' as Phase, label: 'Finalizing report...', labelDone: 'Complete' },
|
||||
];
|
||||
|
||||
// Session keys for pipeline resume
|
||||
const SESSION_KEYS = {
|
||||
reportId: 'infinith_reportId',
|
||||
clinicId: 'infinith_clinicId',
|
||||
runId: 'infinith_runId',
|
||||
url: 'infinith_url',
|
||||
};
|
||||
|
||||
function saveSession(data: { reportId: string; clinicId?: string; runId?: string; url?: string }) {
|
||||
sessionStorage.setItem(SESSION_KEYS.reportId, data.reportId);
|
||||
if (data.clinicId) sessionStorage.setItem(SESSION_KEYS.clinicId, data.clinicId);
|
||||
if (data.runId) sessionStorage.setItem(SESSION_KEYS.runId, data.runId);
|
||||
if (data.url) sessionStorage.setItem(SESSION_KEYS.url, data.url);
|
||||
}
|
||||
|
||||
function loadSession() {
|
||||
return {
|
||||
reportId: sessionStorage.getItem(SESSION_KEYS.reportId),
|
||||
clinicId: sessionStorage.getItem(SESSION_KEYS.clinicId),
|
||||
runId: sessionStorage.getItem(SESSION_KEYS.runId),
|
||||
url: sessionStorage.getItem(SESSION_KEYS.url),
|
||||
};
|
||||
}
|
||||
|
||||
function clearSession() {
|
||||
Object.values(SESSION_KEYS).forEach(k => sessionStorage.removeItem(k));
|
||||
}
|
||||
|
||||
export default function AnalysisLoadingPage() {
|
||||
const [phase, setPhase] = useState<Phase>('discovering');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [errorDetails, setErrorDetails] = useState<Record<string, string> | null>(null);
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const { reportId: urlReportId } = useParams<{ reportId?: string }>();
|
||||
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;
|
||||
const runPipeline = useCallback(async (
|
||||
startUrl?: string,
|
||||
resumeFrom?: { reportId: string; clinicId?: string; runId?: string; phase: Phase },
|
||||
) => {
|
||||
try {
|
||||
let reportId = resumeFrom?.reportId || '';
|
||||
let clinicId = resumeFrom?.clinicId;
|
||||
let runId = resumeFrom?.runId;
|
||||
let startPhase = resumeFrom?.phase || 'discovering';
|
||||
|
||||
if (!url) {
|
||||
navigate('/', { replace: true });
|
||||
return;
|
||||
}
|
||||
|
||||
const runPipeline = async () => {
|
||||
try {
|
||||
// Phase 1: Discover Channels
|
||||
// Phase 1: Discover Channels (skip if resuming from later phase)
|
||||
if (startPhase === 'discovering') {
|
||||
if (!startUrl) throw new Error('No URL provided');
|
||||
setPhase('discovering');
|
||||
const discovery = await discoverChannels(url);
|
||||
const discovery = await discoverChannels(startUrl);
|
||||
if (!discovery.success) throw new Error(discovery.error || 'Channel discovery failed');
|
||||
const reportId = discovery.reportId;
|
||||
const clinicId = discovery.clinicId; // V3
|
||||
const runId = discovery.runId; // V3
|
||||
reportId = discovery.reportId;
|
||||
clinicId = discovery.clinicId;
|
||||
runId = discovery.runId;
|
||||
|
||||
// Phase 2: Collect Channel Data
|
||||
// Save to session + update URL for resume
|
||||
saveSession({ reportId, clinicId, runId, url: startUrl });
|
||||
window.history.replaceState(null, '', `/report/loading/${reportId}`);
|
||||
startPhase = 'collecting';
|
||||
}
|
||||
|
||||
// Phase 2: Collect Channel Data
|
||||
if (startPhase === 'collecting') {
|
||||
setPhase('collecting');
|
||||
const collection = await collectChannelData(reportId, clinicId, runId);
|
||||
if (!collection.success) throw new Error(collection.error || 'Data collection failed');
|
||||
// Allow partial success — only fail on total failure
|
||||
if (collection.success === false && !collection.partialFailure) {
|
||||
throw new Error(collection.error || 'Data collection failed');
|
||||
}
|
||||
if (collection.channelErrors && Object.keys(collection.channelErrors).length > 0) {
|
||||
console.warn('[pipeline] Partial failures:', collection.channelErrors);
|
||||
}
|
||||
startPhase = 'generating';
|
||||
}
|
||||
|
||||
// Phase 3: Generate Report
|
||||
// Phase 3: Generate Report
|
||||
if (startPhase === 'generating') {
|
||||
setPhase('generating');
|
||||
const result = await generateReportV2(reportId, clinicId, runId);
|
||||
if (!result.success) throw new Error(result.error || 'Report generation failed');
|
||||
|
||||
// Complete — navigate to report
|
||||
setPhase('complete');
|
||||
clearSession();
|
||||
|
||||
setTimeout(() => {
|
||||
navigate(`/report/${reportId}`, {
|
||||
@@ -63,13 +116,117 @@ export default function AnalysisLoadingPage() {
|
||||
: undefined,
|
||||
});
|
||||
}, 800);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'An error occurred');
|
||||
}
|
||||
};
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : 'An error occurred';
|
||||
setError(msg);
|
||||
}
|
||||
}, [navigate]);
|
||||
|
||||
runPipeline();
|
||||
}, [url, navigate]);
|
||||
// Retry from the current failed phase
|
||||
const handleRetry = useCallback(() => {
|
||||
setError(null);
|
||||
setErrorDetails(null);
|
||||
const session = loadSession();
|
||||
if (session.reportId) {
|
||||
// Resume from the phase that failed
|
||||
runPipeline(undefined, {
|
||||
reportId: session.reportId,
|
||||
clinicId: session.clinicId || undefined,
|
||||
runId: session.runId || undefined,
|
||||
phase,
|
||||
});
|
||||
} else if (url || session.url) {
|
||||
// Restart from scratch
|
||||
hasStarted.current = false;
|
||||
runPipeline(url || session.url || undefined);
|
||||
}
|
||||
}, [phase, url, runPipeline]);
|
||||
|
||||
useEffect(() => {
|
||||
if (hasStarted.current) return;
|
||||
hasStarted.current = true;
|
||||
|
||||
// 1. Try URL param resume (e.g., /report/loading/abc-123)
|
||||
if (urlReportId) {
|
||||
setPhase('resuming');
|
||||
fetchPipelineStatus(urlReportId)
|
||||
.then((status) => {
|
||||
// Also check sessionStorage for clinicId/runId
|
||||
const session = loadSession();
|
||||
const clinicId = session.clinicId || status.clinicId;
|
||||
const runId = session.runId || status.runId;
|
||||
|
||||
if (status.hasReport || status.status === 'complete') {
|
||||
// Already done — go to report
|
||||
navigate(`/report/${urlReportId}`, { replace: true });
|
||||
return;
|
||||
}
|
||||
|
||||
let resumePhase: Phase = 'discovering';
|
||||
if (status.status === 'discovered' || status.status === 'discovering') {
|
||||
resumePhase = 'collecting';
|
||||
} else if (['collecting', 'collected', 'partial'].includes(status.status)) {
|
||||
resumePhase = 'generating';
|
||||
} else if (status.status === 'collection_failed') {
|
||||
setError('Data collection failed. Please retry.');
|
||||
setPhase('collecting');
|
||||
return;
|
||||
}
|
||||
|
||||
saveSession({ reportId: urlReportId, clinicId, runId, url: session.url || undefined });
|
||||
runPipeline(undefined, { reportId: urlReportId, clinicId, runId, phase: resumePhase });
|
||||
})
|
||||
.catch(() => {
|
||||
setError('Could not resume analysis. Please try again.');
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. Try sessionStorage resume
|
||||
const session = loadSession();
|
||||
if (session.reportId && !url) {
|
||||
setPhase('resuming');
|
||||
fetchPipelineStatus(session.reportId)
|
||||
.then((status) => {
|
||||
if (status.hasReport || status.status === 'complete') {
|
||||
clearSession();
|
||||
navigate(`/report/${session.reportId}`, { replace: true });
|
||||
return;
|
||||
}
|
||||
|
||||
let resumePhase: Phase = 'discovering';
|
||||
if (['discovered', 'discovering'].includes(status.status)) {
|
||||
resumePhase = 'collecting';
|
||||
} else if (['collecting', 'collected', 'partial'].includes(status.status)) {
|
||||
resumePhase = 'generating';
|
||||
}
|
||||
|
||||
runPipeline(undefined, {
|
||||
reportId: session.reportId!,
|
||||
clinicId: session.clinicId || undefined,
|
||||
runId: session.runId || undefined,
|
||||
phase: resumePhase,
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
clearSession();
|
||||
navigate('/', { replace: true });
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Fresh start with URL
|
||||
if (!url) {
|
||||
navigate('/', { replace: true });
|
||||
return;
|
||||
}
|
||||
|
||||
runPipeline(url);
|
||||
}, [url, urlReportId, navigate, runPipeline]);
|
||||
|
||||
// Adjust phaseIndex for 'resuming' state
|
||||
const displayPhaseIndex = phase === 'resuming' ? -1 : phaseIndex;
|
||||
|
||||
return (
|
||||
<div className="relative min-h-screen bg-primary-900 flex flex-col items-center justify-center px-6 overflow-hidden">
|
||||
@@ -91,14 +248,14 @@ export default function AnalysisLoadingPage() {
|
||||
INFINITH
|
||||
</motion.h1>
|
||||
|
||||
{url && (
|
||||
{(url || loadSession().url) && (
|
||||
<motion.p
|
||||
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"
|
||||
>
|
||||
{url}
|
||||
{url || loadSession().url}
|
||||
</motion.p>
|
||||
)}
|
||||
|
||||
@@ -110,68 +267,102 @@ export default function AnalysisLoadingPage() {
|
||||
>
|
||||
<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>
|
||||
|
||||
{errorDetails && (
|
||||
<div className="mb-4 text-left bg-red-500/5 rounded-lg p-3">
|
||||
<p className="text-red-400/60 text-xs font-mono mb-1">Failed channels:</p>
|
||||
{Object.entries(errorDetails).map(([ch, err]) => (
|
||||
<p key={ch} className="text-red-400/80 text-xs font-mono">
|
||||
• {ch}: {err}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-3 justify-center">
|
||||
<button
|
||||
onClick={handleRetry}
|
||||
className="px-6 py-2 text-sm font-medium text-white bg-purple-600/30 rounded-lg hover:bg-purple-600/50 transition-colors flex items-center gap-2"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
Retry
|
||||
</button>
|
||||
<button
|
||||
onClick={() => { clearSession(); 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"
|
||||
>
|
||||
Start Over
|
||||
</button>
|
||||
</div>
|
||||
</motion.div>
|
||||
) : (
|
||||
<>
|
||||
<div className="w-full space-y-5 mb-14">
|
||||
{PHASE_STEPS.map((step, index) => {
|
||||
const isCompleted = phaseIndex > index || (step.key === 'complete' && phase === 'complete');
|
||||
const isActive = phaseIndex === index && 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 }}
|
||||
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'
|
||||
}`}
|
||||
>
|
||||
{isCompleted ? step.labelDone : step.label}
|
||||
</span>
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="w-full h-2 bg-white/10 rounded-full overflow-hidden">
|
||||
{phase === 'resuming' ? (
|
||||
<motion.div
|
||||
initial={{ width: '0%' }}
|
||||
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>
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
className="flex flex-col items-center gap-4 mb-14"
|
||||
>
|
||||
<div className="w-7 h-7 rounded-full border-2 border-purple-400 border-t-transparent animate-spin" />
|
||||
<p className="text-purple-200 text-sm">Resuming analysis...</p>
|
||||
</motion.div>
|
||||
) : (
|
||||
<>
|
||||
<div className="w-full space-y-5 mb-14">
|
||||
{PHASE_STEPS.map((step, index) => {
|
||||
const isCompleted = displayPhaseIndex > index || (step.key === 'complete' && phase === 'complete');
|
||||
const isActive = displayPhaseIndex === index && phase !== 'complete';
|
||||
|
||||
<p className="text-white/40 text-xs mt-4">
|
||||
AI가 마케팅 데이터를 분석하고 있습니다. 약 1~2분 소요됩니다.
|
||||
</p>
|
||||
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'
|
||||
}`}
|
||||
>
|
||||
{isCompleted ? step.labelDone : 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: `${((displayPhaseIndex + (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가 마케팅 데이터를 분석하고 있습니다. 약 1~2분 소요됩니다.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user