카카오 로그인 및 비로그인 플로우 적용 .
This commit is contained in:
1 parent
2acf4e2cb6
commit
662b6b80bc
15 files changed
+1393
-335
No files matched your search
+187
-9
@@ -8,7 +8,7 @@ import LoadingSection from './pages/Analysis/LoadingSection';
|
||||
import AnalysisResultSection from './pages/Analysis/AnalysisResultSection';
|
||||
import LoginSection from './pages/Login/LoginSection';
|
||||
import GenerationFlow from './pages/Dashboard/GenerationFlow';
|
||||
import { crawlUrl } from './utils/api';
|
||||
import { crawlUrl, kakaoCallback, isLoggedIn, saveTokens } from './utils/api';
|
||||
import { CrawlingResponse } from './types/api';
|
||||
|
||||
type ViewMode = 'landing' | 'loading' | 'analysis' | 'login' | 'generation_flow';
|
||||
@@ -46,15 +46,116 @@ const App: React.FC = () => {
|
||||
const savedViewMode = localStorage.getItem(VIEW_MODE_KEY) as ViewMode | null;
|
||||
const savedAnalysisData = localStorage.getItem(ANALYSIS_DATA_KEY);
|
||||
|
||||
const [viewMode, setViewMode] = useState<ViewMode>(
|
||||
savedViewMode === 'generation_flow' ? 'generation_flow' : 'landing'
|
||||
);
|
||||
// 저장된 분석 데이터 파싱 및 유효성 검사
|
||||
const parseSavedAnalysisData = (): CrawlingResponse | null => {
|
||||
if (!savedAnalysisData) return null;
|
||||
try {
|
||||
const data = JSON.parse(savedAnalysisData) as CrawlingResponse;
|
||||
// 기본값 보장
|
||||
if (data.marketing_analysis) {
|
||||
data.marketing_analysis.tags = data.marketing_analysis.tags || [];
|
||||
data.marketing_analysis.facilities = data.marketing_analysis.facilities || [];
|
||||
data.marketing_analysis.report = data.marketing_analysis.report || '';
|
||||
}
|
||||
if (data.processed_info) {
|
||||
data.processed_info.customer_name = data.processed_info.customer_name || '알 수 없음';
|
||||
data.processed_info.region = data.processed_info.region || '';
|
||||
data.processed_info.detail_region_info = data.processed_info.detail_region_info || '';
|
||||
}
|
||||
data.image_list = data.image_list || [];
|
||||
return data;
|
||||
} catch {
|
||||
localStorage.removeItem(ANALYSIS_DATA_KEY);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// 초기 viewMode 결정: 로그인 상태면 바로 generation_flow로
|
||||
const getInitialViewMode = (): ViewMode => {
|
||||
if (savedViewMode === 'generation_flow') return 'generation_flow';
|
||||
if (isLoggedIn()) return 'generation_flow';
|
||||
return 'landing';
|
||||
};
|
||||
|
||||
const [viewMode, setViewMode] = useState<ViewMode>(getInitialViewMode());
|
||||
const [initialTab, setInitialTab] = useState('새 프로젝트 만들기');
|
||||
const [analysisData, setAnalysisData] = useState<CrawlingResponse | null>(
|
||||
savedAnalysisData ? JSON.parse(savedAnalysisData) : null
|
||||
parseSavedAnalysisData()
|
||||
);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [scrollProgress, setScrollProgress] = useState(0);
|
||||
const [isProcessingCallback, setIsProcessingCallback] = useState(false);
|
||||
|
||||
// 카카오 로그인 콜백 처리 (URL에서 토큰 또는 code 파라미터 확인)
|
||||
useEffect(() => {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const accessToken = urlParams.get('access_token');
|
||||
const refreshToken = urlParams.get('refresh_token');
|
||||
const code = urlParams.get('code');
|
||||
|
||||
// 백엔드에서 토큰을 URL 파라미터로 전달한 경우
|
||||
if (accessToken && refreshToken && !isProcessingCallback) {
|
||||
setIsProcessingCallback(true);
|
||||
handleTokenCallback(accessToken, refreshToken);
|
||||
}
|
||||
// 기존 code 방식 (Redirect URI가 프론트엔드인 경우)
|
||||
else if (code && !isProcessingCallback) {
|
||||
setIsProcessingCallback(true);
|
||||
handleKakaoCallback(code);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 백엔드에서 토큰을 URL 파라미터로 전달받은 경우 처리
|
||||
const handleTokenCallback = (accessToken: string, refreshToken: string) => {
|
||||
try {
|
||||
// 토큰 저장
|
||||
saveTokens(accessToken, refreshToken);
|
||||
|
||||
// URL에서 토큰 파라미터 제거
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.delete('access_token');
|
||||
url.searchParams.delete('refresh_token');
|
||||
window.history.replaceState({}, document.title, url.pathname);
|
||||
|
||||
// 로그인 성공 - 분석 데이터 유무에 따라 분기
|
||||
// 비로그인 상태에서 URL 입력 후 브랜드 분석을 본 경우 → 바로 generation_flow로 (URL 입력 스킵)
|
||||
// 홈에서 바로 로그인한 경우 → generation_flow로 (URL 입력 필요)
|
||||
const savedData = localStorage.getItem(ANALYSIS_DATA_KEY);
|
||||
if (savedData) {
|
||||
// 분석 데이터가 있으면 바로 에셋 관리로
|
||||
setInitialTab('새 프로젝트 만들기');
|
||||
setViewMode('generation_flow');
|
||||
} else {
|
||||
// 분석 데이터가 없으면 URL 입력부터 시작하도록 generation_flow로
|
||||
setInitialTab('새 프로젝트 만들기');
|
||||
setViewMode('generation_flow');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Token callback failed:', err);
|
||||
alert('로그인 처리에 실패했습니다. 다시 시도해주세요.');
|
||||
} finally {
|
||||
setIsProcessingCallback(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleKakaoCallback = async (code: string) => {
|
||||
try {
|
||||
const response = await kakaoCallback(code);
|
||||
|
||||
// 로그인 성공 - 서버에서 받은 redirect_url로 이동
|
||||
window.location.href = response.redirect_url;
|
||||
} catch (err) {
|
||||
console.error('Kakao callback failed:', err);
|
||||
alert('카카오 로그인에 실패했습니다. 다시 시도해주세요.');
|
||||
|
||||
// URL에서 code 파라미터 제거
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.delete('code');
|
||||
window.history.replaceState({}, document.title, url.pathname);
|
||||
} finally {
|
||||
setIsProcessingCallback(false);
|
||||
}
|
||||
};
|
||||
|
||||
// viewMode 변경 시 localStorage에 저장
|
||||
useEffect(() => {
|
||||
@@ -88,6 +189,43 @@ const App: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
// 크롤링 응답 유효성 검사
|
||||
const validateCrawlingResponse = (data: CrawlingResponse): boolean => {
|
||||
// 필수 필드 존재 여부 확인
|
||||
if (!data) return false;
|
||||
if (!data.processed_info) return false;
|
||||
if (!data.marketing_analysis) return false;
|
||||
|
||||
// marketing_analysis 내부 필드 기본값 보장
|
||||
if (!data.marketing_analysis.tags) {
|
||||
data.marketing_analysis.tags = [];
|
||||
}
|
||||
if (!data.marketing_analysis.facilities) {
|
||||
data.marketing_analysis.facilities = [];
|
||||
}
|
||||
if (!data.marketing_analysis.report) {
|
||||
data.marketing_analysis.report = '';
|
||||
}
|
||||
|
||||
// processed_info 내부 필드 기본값 보장
|
||||
if (!data.processed_info.customer_name) {
|
||||
data.processed_info.customer_name = '알 수 없음';
|
||||
}
|
||||
if (!data.processed_info.region) {
|
||||
data.processed_info.region = '';
|
||||
}
|
||||
if (!data.processed_info.detail_region_info) {
|
||||
data.processed_info.detail_region_info = '';
|
||||
}
|
||||
|
||||
// image_list 기본값 보장
|
||||
if (!data.image_list) {
|
||||
data.image_list = [];
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const handleStartAnalysis = async (url: string) => {
|
||||
if (!url.trim()) return;
|
||||
|
||||
@@ -96,18 +234,40 @@ const App: React.FC = () => {
|
||||
|
||||
try {
|
||||
const data = await crawlUrl(url);
|
||||
|
||||
// 응답 유효성 검사
|
||||
if (!validateCrawlingResponse(data)) {
|
||||
throw new Error('유효하지 않은 URL입니다. 네이버 지도 URL을 입력해주세요.');
|
||||
}
|
||||
|
||||
setAnalysisData(data);
|
||||
localStorage.setItem(ANALYSIS_DATA_KEY, JSON.stringify(data));
|
||||
setViewMode('analysis');
|
||||
} catch (err) {
|
||||
console.error('Crawling failed:', err);
|
||||
setError('분석 중 오류가 발생했습니다. 다시 시도해주세요.');
|
||||
const errorMessage = err instanceof Error ? err.message : '분석 중 오류가 발생했습니다. 다시 시도해주세요.';
|
||||
setError(errorMessage);
|
||||
setViewMode('landing');
|
||||
}
|
||||
};
|
||||
|
||||
const handleToLogin = () => {
|
||||
setViewMode('login');
|
||||
const handleToLogin = async () => {
|
||||
// 이미 로그인된 상태면 바로 generation_flow로 이동
|
||||
if (isLoggedIn()) {
|
||||
setInitialTab('새 프로젝트 만들기');
|
||||
setViewMode('generation_flow');
|
||||
return;
|
||||
}
|
||||
|
||||
// 로그인 안 된 상태면 카카오 로그인 페이지로 리다이렉션
|
||||
try {
|
||||
const { getKakaoLoginUrl } = await import('./utils/api');
|
||||
const response = await getKakaoLoginUrl();
|
||||
window.location.href = response.auth_url;
|
||||
} catch (err) {
|
||||
console.error('Failed to get Kakao login URL:', err);
|
||||
alert('로그인 URL을 가져오는데 실패했습니다. 다시 시도해주세요.');
|
||||
}
|
||||
};
|
||||
|
||||
const handleLoginSuccess = () => {
|
||||
@@ -124,6 +284,17 @@ const App: React.FC = () => {
|
||||
setViewMode('landing');
|
||||
};
|
||||
|
||||
// 카카오 콜백 처리 중 로딩 화면 표시
|
||||
if (isProcessingCallback) {
|
||||
return (
|
||||
<div className="login-container" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
|
||||
<div style={{ textAlign: 'center', color: '#fff' }}>
|
||||
<p style={{ fontSize: '18px' }}>로그인 처리 중...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (viewMode === 'loading') {
|
||||
return <LoadingSection />;
|
||||
}
|
||||
@@ -149,13 +320,20 @@ const App: React.FC = () => {
|
||||
initialActiveItem={initialTab}
|
||||
initialImageList={analysisData?.image_list || []}
|
||||
businessInfo={analysisData?.processed_info}
|
||||
initialAnalysisData={analysisData}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// 로그인된 상태에서 "시작하기" 버튼 클릭
|
||||
const handleHeaderStart = () => {
|
||||
setInitialTab('새 프로젝트 만들기');
|
||||
setViewMode('generation_flow');
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="landing-container" ref={containerRef}>
|
||||
<Header />
|
||||
<Header onStartClick={handleHeaderStart} />
|
||||
<section className="landing-section">
|
||||
<HeroSection
|
||||
onAnalyze={handleStartAnalysis}
|
||||
|
||||
@@ -1,15 +1,57 @@
|
||||
|
||||
import React from 'react';
|
||||
import React, { useState } from 'react';
|
||||
import { getKakaoLoginUrl, isLoggedIn } from '../utils/api';
|
||||
|
||||
interface HeaderProps {
|
||||
onStartClick?: () => void;
|
||||
}
|
||||
|
||||
const Header: React.FC<HeaderProps> = ({ onStartClick }) => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const loggedIn = isLoggedIn();
|
||||
|
||||
const handleLogin = async () => {
|
||||
if (isLoading) return;
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const response = await getKakaoLoginUrl();
|
||||
// 카카오 로그인 페이지로 리다이렉트
|
||||
window.location.href = response.auth_url;
|
||||
} catch (err) {
|
||||
console.error('Failed to get Kakao login URL:', err);
|
||||
alert('로그인 URL을 가져오는데 실패했습니다. 다시 시도해주세요.');
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleStart = () => {
|
||||
if (onStartClick) {
|
||||
onStartClick();
|
||||
}
|
||||
};
|
||||
|
||||
const Header: React.FC = () => {
|
||||
return (
|
||||
<header className="landing-header">
|
||||
<div className="header-logo">
|
||||
<img src="/assets/images/logo.svg" alt="CASTAD" />
|
||||
<img src="/assets/images/ado2-header-logo.svg" alt="ADO2" />
|
||||
</div>
|
||||
<button className="header-login-btn">
|
||||
로그인
|
||||
</button>
|
||||
{loggedIn ? (
|
||||
<button
|
||||
className="header-start-btn"
|
||||
onClick={handleStart}
|
||||
>
|
||||
시작하기
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
className="header-login-btn"
|
||||
onClick={handleLogin}
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? '로딩...' : '로그인'}
|
||||
</button>
|
||||
)}
|
||||
</header>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -57,7 +57,7 @@ const Sidebar: React.FC<SidebarProps> = ({ activeItem, onNavigate, onHome }) =>
|
||||
const menuItems = [
|
||||
{ id: '대시보드', label: '대시보드', disabled: true, icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><rect x="3" y="3" width="7" height="9"/><rect x="14" y="3" width="7" height="5"/><rect x="14" y="12" width="7" height="9"/><rect x="3" y="16" width="7" height="5"/></svg> },
|
||||
{ id: '새 프로젝트 만들기', label: '새 프로젝트 만들기', disabled: false, icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> },
|
||||
{ id: '내 보관함', label: '내 보관함', disabled: true, icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg> },
|
||||
{ id: 'ADO2 콘텐츠', label: 'ADO2 콘텐츠', disabled: true, icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg> },
|
||||
{ id: '에셋 관리', label: '에셋 관리', disabled: true, icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg> },
|
||||
{ id: '내 펜션', label: '내 펜션', disabled: true, icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg> },
|
||||
{ id: '계정 설정', label: '계정 설정', disabled: true, icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg> },
|
||||
|
||||
@@ -50,129 +50,114 @@ const formatReportText = (text: string): React.ReactNode[] => {
|
||||
});
|
||||
};
|
||||
|
||||
// 마크다운 report를 섹션별로 파싱
|
||||
const parseReport = (report: string) => {
|
||||
if (!report || report.trim() === '') {
|
||||
return [];
|
||||
}
|
||||
// 셀링 포인트 카드 타입
|
||||
interface SellingPointCard {
|
||||
title: string;
|
||||
items: string[];
|
||||
}
|
||||
|
||||
const sections: { title: string; content: string }[] = [];
|
||||
const lines = report.split('\n');
|
||||
let currentTitle = '';
|
||||
let currentContent: string[] = [];
|
||||
let hasMarkdownHeaders = report.includes('## ');
|
||||
// facilities 배열을 셀링 포인트 카드 형태로 변환
|
||||
const parseSellingPoints = (facilities: string[]): SellingPointCard[] => {
|
||||
// 기본 카테고리 정의
|
||||
const categories: SellingPointCard[] = [
|
||||
{ title: '브랜드 컨셉', items: [] },
|
||||
{ title: '프라이버시', items: [] },
|
||||
{ title: '로컬 결합', items: [] },
|
||||
{ title: '무드/비주얼', items: [] },
|
||||
{ title: '편의/신뢰', items: [] },
|
||||
{ title: '체류형 가치', items: [] },
|
||||
];
|
||||
|
||||
// 마크다운 헤더가 없는 경우 전체 텍스트를 하나의 섹션으로 반환
|
||||
if (!hasMarkdownHeaders) {
|
||||
return [{ title: '분석 결과', content: report.trim() }];
|
||||
}
|
||||
|
||||
lines.forEach((line) => {
|
||||
if (line.startsWith('## ')) {
|
||||
if (currentTitle || currentContent.length > 0) {
|
||||
sections.push({ title: currentTitle, content: currentContent.join('\n').trim() });
|
||||
}
|
||||
currentTitle = line.replace('## ', '').trim();
|
||||
currentContent = [];
|
||||
} else if (!line.startsWith('# ')) {
|
||||
currentContent.push(line);
|
||||
// facilities를 카테고리에 분배 (최대 2개씩)
|
||||
facilities.forEach((facility, idx) => {
|
||||
const categoryIdx = Math.floor(idx / 2) % categories.length;
|
||||
if (categories[categoryIdx].items.length < 2) {
|
||||
categories[categoryIdx].items.push(facility);
|
||||
}
|
||||
});
|
||||
|
||||
if (currentTitle || currentContent.length > 0) {
|
||||
sections.push({ title: currentTitle, content: currentContent.join('\n').trim() });
|
||||
}
|
||||
|
||||
return sections.filter(s => s.content && !s.title.includes('JSON'));
|
||||
// 아이템이 있는 카테고리만 반환
|
||||
return categories.filter(cat => cat.items.length > 0);
|
||||
};
|
||||
|
||||
const AnalysisResultSection: React.FC<AnalysisResultSectionProps> = ({ onBack, onGenerate, data }) => {
|
||||
const { processed_info, marketing_analysis } = data;
|
||||
const tags = marketing_analysis.tags || [];
|
||||
const facilities = marketing_analysis.facilities || [];
|
||||
const reportSections = parseReport(marketing_analysis.report);
|
||||
const sellingPoints = parseSellingPoints(facilities);
|
||||
|
||||
return (
|
||||
<div className="analysis-container">
|
||||
{/* Back Button */}
|
||||
<div className="back-button-container" style={{ marginLeft: 0 }}>
|
||||
<button onClick={onBack} className="btn-back">
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||
<path d="M15 18l-6-6 6-6" />
|
||||
</svg>
|
||||
뒤로가기
|
||||
</button>
|
||||
</div>
|
||||
{/* Header Area */}
|
||||
<div className="analysis-header-area">
|
||||
{/* Back Button */}
|
||||
<div className="back-button-container">
|
||||
<button onClick={onBack} className="btn-back">
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||
<path d="M15 18l-6-6 6-6" />
|
||||
</svg>
|
||||
뒤로가기
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Header */}
|
||||
<div className="analysis-header">
|
||||
<div className="analysis-icon">
|
||||
<svg className="w-8 h-8" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M12 2l2.4 7.2L22 12l-7.6 2.4L12 22l-2.4-7.2L2 12l7.6-2.4z" />
|
||||
</svg>
|
||||
{/* Header */}
|
||||
<div className="analysis-header">
|
||||
<div className="analysis-icon">
|
||||
<svg className="w-8 h-8" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M12 2l2.4 7.2L22 12l-7.6 2.4L12 22l-2.4-7.2L2 12l7.6-2.4z" />
|
||||
</svg>
|
||||
</div>
|
||||
<h1 className="page-title">브랜드 분석</h1>
|
||||
<p className="page-subtitle">
|
||||
쉽고 빠르게, 브랜드 소셜 미디어 캠페인을 만드세요.
|
||||
</p>
|
||||
</div>
|
||||
<h1 className="page-title">브랜드 분석</h1>
|
||||
<p className="page-subtitle">
|
||||
쉽고 빠르게, 브랜드 소셜 미디어 캠페인을 만드세요.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Main Content Grid */}
|
||||
<div className="analysis-grid">
|
||||
{/* Brand Identity */}
|
||||
{/* Left: Brand Identity (Scrollable) */}
|
||||
<div className="brand-identity-card">
|
||||
<div className="brand-header">
|
||||
<span className="section-title">브랜드 정체성</span>
|
||||
<span className="brand-subtitle">AI 마케팅 분석 요약</span>
|
||||
</div>
|
||||
|
||||
<div className="brand-info">
|
||||
<h2 className="brand-name">{processed_info.customer_name}</h2>
|
||||
<p className="brand-location">{processed_info.region} · {processed_info.detail_region_info}</p>
|
||||
</div>
|
||||
<div className="brand-content">
|
||||
<div className="brand-info">
|
||||
<h2 className="brand-name">{processed_info.customer_name}</h2>
|
||||
<p className="brand-location">{processed_info.detail_region_info}</p>
|
||||
</div>
|
||||
|
||||
{/* Marketing Analysis Summary */}
|
||||
<div className="report-section">
|
||||
<div className="report-content custom-scrollbar">
|
||||
{reportSections.length === 0 ? (
|
||||
<div>
|
||||
{marketing_analysis.report
|
||||
? formatReportText(marketing_analysis.report)
|
||||
: '분석 결과가 없습니다.'}
|
||||
</div>
|
||||
) : (
|
||||
<div className="report-sections">
|
||||
{reportSections.map((section, idx) => (
|
||||
<div key={idx}>
|
||||
{section.title && <h4 className="report-section-title">{section.title}</h4>}
|
||||
<div>
|
||||
{formatReportText(section.content)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="report-content">
|
||||
{marketing_analysis.report
|
||||
? formatReportText(marketing_analysis.report)
|
||||
: '분석 결과가 없습니다.'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
{/* Right Cards */}
|
||||
{/* Right: Selling Points & Keywords (Fixed) */}
|
||||
<div className="analysis-cards-column">
|
||||
{/* Main Selling Points (Facilities) */}
|
||||
<div className="feature-card">
|
||||
<span className="section-title-purple">주요 셀링 포인트</span>
|
||||
<div className="tags-wrapper">
|
||||
{facilities.map((facility, idx) => (
|
||||
<span key={idx} className="feature-tag">
|
||||
{facility}
|
||||
</span>
|
||||
{/* Main Selling Points */}
|
||||
<div className="feature-card selling-points-card">
|
||||
<span className="section-title">주요 셀링 포인트</span>
|
||||
<div className="selling-points-grid">
|
||||
{sellingPoints.map((point, idx) => (
|
||||
<div key={idx} className="selling-point-item">
|
||||
<span className="selling-point-title">{point.title}</span>
|
||||
<div className="selling-point-content">
|
||||
{point.items.map((item, itemIdx) => (
|
||||
<p key={itemIdx}>{item}</p>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Recommended Target Keywords (Tags) */}
|
||||
<div className="feature-card">
|
||||
{/* Recommended Target Keywords */}
|
||||
<div className="feature-card keywords-card">
|
||||
<span className="section-title">추천 타겟 키워드</span>
|
||||
<div className="tags-wrapper">
|
||||
{tags.map((tag, idx) => (
|
||||
|
||||
@@ -6,12 +6,17 @@ import SoundStudioContent from './SoundStudioContent';
|
||||
import CompletionContent from './CompletionContent';
|
||||
import DashboardContent from './DashboardContent';
|
||||
import BusinessSettingsContent from './BusinessSettingsContent';
|
||||
import { ImageItem } from '../../types/api';
|
||||
import UrlInputContent from './UrlInputContent';
|
||||
import LoadingSection from '../Analysis/LoadingSection';
|
||||
import AnalysisResultSection from '../Analysis/AnalysisResultSection';
|
||||
import { ImageItem, CrawlingResponse } from '../../types/api';
|
||||
import { crawlUrl } from '../../utils/api';
|
||||
|
||||
const WIZARD_STEP_KEY = 'castad_wizard_step';
|
||||
const ACTIVE_ITEM_KEY = 'castad_active_item';
|
||||
const SONG_TASK_ID_KEY = 'castad_song_task_id';
|
||||
const IMAGE_TASK_ID_KEY = 'castad_image_task_id';
|
||||
const ANALYSIS_DATA_KEY = 'castad_analysis_data';
|
||||
|
||||
// 다른 컴포넌트에서 사용하는 storage key들 (초기화용)
|
||||
const SONG_GENERATION_KEY = 'castad_song_generation';
|
||||
@@ -37,27 +42,82 @@ interface GenerationFlowProps {
|
||||
initialActiveItem?: string;
|
||||
initialImageList?: string[];
|
||||
businessInfo?: BusinessInfo;
|
||||
initialAnalysisData?: CrawlingResponse | null;
|
||||
}
|
||||
|
||||
const GenerationFlow: React.FC<GenerationFlowProps> = ({ onHome, initialActiveItem = '대시보드', initialImageList = [], businessInfo }) => {
|
||||
// 위저드 단계:
|
||||
// -2: URL 입력
|
||||
// -1: 로딩 (분석 중)
|
||||
// 0: 브랜드 분석 결과
|
||||
// 1: 에셋 관리 (Asset Management)
|
||||
// 2: 사운드 스튜디오 (Sound Studio)
|
||||
// 3: 완료 (Completion)
|
||||
|
||||
const GenerationFlow: React.FC<GenerationFlowProps> = ({
|
||||
onHome,
|
||||
initialActiveItem = '대시보드',
|
||||
initialImageList = [],
|
||||
businessInfo,
|
||||
initialAnalysisData
|
||||
}) => {
|
||||
// localStorage에서 저장된 상태 복원
|
||||
const savedActiveItem = localStorage.getItem(ACTIVE_ITEM_KEY);
|
||||
const savedWizardStep = localStorage.getItem(WIZARD_STEP_KEY);
|
||||
const savedSongTaskId = localStorage.getItem(SONG_TASK_ID_KEY);
|
||||
const savedImageTaskId = localStorage.getItem(IMAGE_TASK_ID_KEY);
|
||||
const savedAnalysisData = localStorage.getItem(ANALYSIS_DATA_KEY);
|
||||
|
||||
// 분석 데이터 파싱
|
||||
const parseAnalysisData = (): CrawlingResponse | null => {
|
||||
if (initialAnalysisData) return initialAnalysisData;
|
||||
if (!savedAnalysisData) return null;
|
||||
try {
|
||||
return JSON.parse(savedAnalysisData) as CrawlingResponse;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const [activeItem, setActiveItem] = useState(savedActiveItem || initialActiveItem);
|
||||
// 현재 위저드 단계 (0: Asset, 1: Sound Studio, 2: Completion)
|
||||
const [wizardStep, setWizardStep] = useState(savedWizardStep ? parseInt(savedWizardStep, 10) : 0);
|
||||
|
||||
// 초기 위저드 단계 결정
|
||||
const getInitialWizardStep = (): number => {
|
||||
// 저장된 단계가 있으면 사용
|
||||
if (savedWizardStep !== null) {
|
||||
return parseInt(savedWizardStep, 10);
|
||||
}
|
||||
// 분석 데이터가 있으면 에셋 관리(1)부터, 없으면 URL 입력(-2)부터
|
||||
const hasAnalysisData = initialAnalysisData || savedAnalysisData;
|
||||
return hasAnalysisData ? 1 : -2;
|
||||
};
|
||||
|
||||
const [wizardStep, setWizardStep] = useState(getInitialWizardStep());
|
||||
const [songTaskId, setSongTaskId] = useState<string | null>(savedSongTaskId);
|
||||
const [imageTaskId, setImageTaskId] = useState<string | null>(savedImageTaskId);
|
||||
const [videoGenerationStatus, setVideoGenerationStatus] = useState<'idle' | 'generating' | 'complete' | 'error'>('idle');
|
||||
const [videoGenerationProgress, setVideoGenerationProgress] = useState(0);
|
||||
const [analysisData, setAnalysisData] = useState<CrawlingResponse | null>(parseAnalysisData());
|
||||
const [analysisError, setAnalysisError] = useState<string | null>(null);
|
||||
|
||||
// 현재 비즈니스 정보 (분석 데이터에서 가져오거나 prop에서 가져옴)
|
||||
const currentBusinessInfo = analysisData?.processed_info || businessInfo;
|
||||
|
||||
// URL 이미지를 ImageItem 형태로 변환하여 초기화
|
||||
const [imageList, setImageList] = useState<ImageItem[]>(
|
||||
initialImageList.map(url => ({ type: 'url', url }))
|
||||
);
|
||||
const getInitialImageList = (): ImageItem[] => {
|
||||
if (analysisData?.image_list && analysisData.image_list.length > 0) {
|
||||
return analysisData.image_list.map(url => ({ type: 'url', url }));
|
||||
}
|
||||
return initialImageList.map(url => ({ type: 'url', url }));
|
||||
};
|
||||
|
||||
const [imageList, setImageList] = useState<ImageItem[]>(getInitialImageList());
|
||||
|
||||
// analysisData 변경 시 imageList 업데이트
|
||||
useEffect(() => {
|
||||
if (analysisData?.image_list && analysisData.image_list.length > 0) {
|
||||
setImageList(analysisData.image_list.map(url => ({ type: 'url', url })));
|
||||
}
|
||||
}, [analysisData]);
|
||||
|
||||
const handleRemoveImage = (index: number) => {
|
||||
setImageList(prev => {
|
||||
@@ -83,10 +143,12 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({ onHome, initialActiveIt
|
||||
// 홈 버튼(로고) 클릭 시 모든 상태 초기화 후 홈으로 이동
|
||||
const handleHome = () => {
|
||||
clearAllProjectStorage();
|
||||
setWizardStep(0);
|
||||
localStorage.removeItem(ANALYSIS_DATA_KEY);
|
||||
setWizardStep(-2);
|
||||
setSongTaskId(null);
|
||||
setImageTaskId(null);
|
||||
setImageList(initialImageList.map(url => ({ type: 'url', url })));
|
||||
setAnalysisData(null);
|
||||
setImageList([]);
|
||||
onHome();
|
||||
};
|
||||
|
||||
@@ -96,6 +158,50 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({ onHome, initialActiveIt
|
||||
localStorage.setItem(WIZARD_STEP_KEY, step.toString());
|
||||
};
|
||||
|
||||
// URL 분석 시작
|
||||
const handleStartAnalysis = async (url: string) => {
|
||||
if (!url.trim()) return;
|
||||
|
||||
goToWizardStep(-1); // 로딩 상태로
|
||||
setAnalysisError(null);
|
||||
|
||||
try {
|
||||
const data = await crawlUrl(url);
|
||||
|
||||
// 기본값 보장
|
||||
if (data.marketing_analysis) {
|
||||
data.marketing_analysis.tags = data.marketing_analysis.tags || [];
|
||||
data.marketing_analysis.facilities = data.marketing_analysis.facilities || [];
|
||||
data.marketing_analysis.report = data.marketing_analysis.report || '';
|
||||
}
|
||||
if (data.processed_info) {
|
||||
data.processed_info.customer_name = data.processed_info.customer_name || '알 수 없음';
|
||||
data.processed_info.region = data.processed_info.region || '';
|
||||
data.processed_info.detail_region_info = data.processed_info.detail_region_info || '';
|
||||
}
|
||||
data.image_list = data.image_list || [];
|
||||
|
||||
setAnalysisData(data);
|
||||
localStorage.setItem(ANALYSIS_DATA_KEY, JSON.stringify(data));
|
||||
goToWizardStep(0); // 브랜드 분석 결과로
|
||||
} catch (err) {
|
||||
console.error('Crawling failed:', err);
|
||||
const errorMessage = err instanceof Error ? err.message : '분석 중 오류가 발생했습니다. 다시 시도해주세요.';
|
||||
setAnalysisError(errorMessage);
|
||||
goToWizardStep(-2); // URL 입력으로 돌아가기
|
||||
}
|
||||
};
|
||||
|
||||
// 브랜드 분석에서 콘텐츠 생성 클릭
|
||||
const handleAnalysisGenerate = () => {
|
||||
goToWizardStep(1); // 에셋 관리로
|
||||
};
|
||||
|
||||
// 브랜드 분석에서 뒤로가기
|
||||
const handleAnalysisBack = () => {
|
||||
goToWizardStep(-2); // URL 입력으로
|
||||
};
|
||||
|
||||
// activeItem 변경 시 localStorage에 저장
|
||||
useEffect(() => {
|
||||
localStorage.setItem(ACTIVE_ITEM_KEY, activeItem);
|
||||
@@ -104,7 +210,31 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({ onHome, initialActiveIt
|
||||
// 새 프로젝트 만들기 - 단계별 컨텐츠 렌더링
|
||||
const renderWizardContent = () => {
|
||||
switch (wizardStep) {
|
||||
case -2:
|
||||
// URL 입력 단계
|
||||
return (
|
||||
<UrlInputContent
|
||||
onAnalyze={handleStartAnalysis}
|
||||
error={analysisError}
|
||||
/>
|
||||
);
|
||||
case -1:
|
||||
// 로딩 단계
|
||||
return <LoadingSection />;
|
||||
case 0:
|
||||
// 브랜드 분석 결과 단계
|
||||
if (!analysisData) {
|
||||
goToWizardStep(-2);
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<AnalysisResultSection
|
||||
onBack={handleAnalysisBack}
|
||||
onGenerate={handleAnalysisGenerate}
|
||||
data={analysisData}
|
||||
/>
|
||||
);
|
||||
case 1:
|
||||
return (
|
||||
<AssetManagementContent
|
||||
onNext={(taskId: string) => {
|
||||
@@ -115,32 +245,32 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({ onHome, initialActiveIt
|
||||
|
||||
setImageTaskId(taskId);
|
||||
localStorage.setItem(IMAGE_TASK_ID_KEY, taskId);
|
||||
goToWizardStep(1);
|
||||
goToWizardStep(2);
|
||||
}}
|
||||
imageList={imageList}
|
||||
onRemoveImage={handleRemoveImage}
|
||||
onAddImages={handleAddImages}
|
||||
/>
|
||||
);
|
||||
case 1:
|
||||
case 2:
|
||||
return (
|
||||
<SoundStudioContent
|
||||
onBack={() => goToWizardStep(0)}
|
||||
onBack={() => goToWizardStep(1)}
|
||||
onNext={(taskId: string) => {
|
||||
setSongTaskId(taskId);
|
||||
localStorage.setItem(SONG_TASK_ID_KEY, taskId);
|
||||
goToWizardStep(2);
|
||||
goToWizardStep(3);
|
||||
}}
|
||||
businessInfo={businessInfo}
|
||||
businessInfo={currentBusinessInfo}
|
||||
imageTaskId={imageTaskId}
|
||||
videoGenerationStatus={videoGenerationStatus}
|
||||
videoGenerationProgress={videoGenerationProgress}
|
||||
/>
|
||||
);
|
||||
case 2:
|
||||
case 3:
|
||||
return (
|
||||
<CompletionContent
|
||||
onBack={() => goToWizardStep(1)}
|
||||
onBack={() => goToWizardStep(2)}
|
||||
songTaskId={songTaskId}
|
||||
onVideoStatusChange={setVideoGenerationStatus}
|
||||
onVideoProgressChange={setVideoGenerationProgress}
|
||||
@@ -158,6 +288,10 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({ onHome, initialActiveIt
|
||||
case '비즈니스 설정':
|
||||
return <BusinessSettingsContent />;
|
||||
case '새 프로젝트 만들기':
|
||||
// 브랜드 분석(0)과 로딩(-1)은 전체 화면으로 표시
|
||||
if (wizardStep === 0 || wizardStep === -1) {
|
||||
return renderWizardContent();
|
||||
}
|
||||
return (
|
||||
<div className="wizard-page-container">
|
||||
{renderWizardContent()}
|
||||
@@ -172,10 +306,34 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({ onHome, initialActiveIt
|
||||
}
|
||||
};
|
||||
|
||||
// 로딩 화면에서만 Sidebar 숨김
|
||||
const showSidebar = wizardStep !== -1;
|
||||
|
||||
// 브랜드 분석(0)일 때는 전체 페이지 스크롤
|
||||
const isBrandAnalysis = activeItem === '새 프로젝트 만들기' && wizardStep === 0;
|
||||
// 스크롤이 필요한 페이지: 대시보드, 비즈니스 설정, 브랜드 분석(0)
|
||||
const needsScroll = activeItem === '대시보드' || activeItem === '비즈니스 설정' || isBrandAnalysis;
|
||||
|
||||
// 브랜드 분석일 때는 높이 제한 없이 자연 스크롤
|
||||
if (isBrandAnalysis) {
|
||||
return (
|
||||
<div className="flex w-full bg-[#0d1416] text-white">
|
||||
{showSidebar && (
|
||||
<Sidebar activeItem={activeItem} onNavigate={setActiveItem} onHome={handleHome} />
|
||||
)}
|
||||
<div className="flex-1 relative">
|
||||
{renderContent()}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`flex w-full bg-[#0d1416] text-white ${activeItem === '대시보드' || activeItem === '비즈니스 설정' ? 'min-h-[100dvh]' : 'h-[100dvh] overflow-hidden'}`}>
|
||||
<Sidebar activeItem={activeItem} onNavigate={setActiveItem} onHome={handleHome} />
|
||||
<div className={`flex-1 relative pl-0 md:pl-0 ${activeItem === '대시보드' || activeItem === '비즈니스 설정' ? 'overflow-y-auto' : 'h-full overflow-hidden'}`}>
|
||||
<div className={`flex w-full bg-[#0d1416] text-white ${needsScroll ? 'min-h-[100dvh]' : 'h-[100dvh] overflow-hidden'}`}>
|
||||
{showSidebar && (
|
||||
<Sidebar activeItem={activeItem} onNavigate={setActiveItem} onHome={handleHome} />
|
||||
)}
|
||||
<div className={`flex-1 relative pl-0 md:pl-0 ${needsScroll ? 'overflow-y-auto' : 'h-full overflow-hidden'}`}>
|
||||
{renderContent()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
|
||||
import React, { useState } from 'react';
|
||||
|
||||
interface UrlInputContentProps {
|
||||
onAnalyze: (url: string) => void;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
const UrlInputContent: React.FC<UrlInputContentProps> = ({ onAnalyze, error }) => {
|
||||
const [url, setUrl] = useState('');
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (url.trim()) {
|
||||
onAnalyze(url.trim());
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="url-input-container">
|
||||
<div className="url-input-content">
|
||||
{/* 아이콘 */}
|
||||
<div className="url-input-icon">
|
||||
<svg width="40" height="40" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M12 2l2.4 7.2L22 12l-7.6 2.4L12 22l-2.4-7.2L2 12l7.6-2.4z" />
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
{/* 제목 */}
|
||||
<h1 className="url-input-title">브랜드 분석</h1>
|
||||
<p className="url-input-subtitle">
|
||||
쉽고 빠르게, 브랜드 소셜 미디어 캠페인을 만드세요.
|
||||
</p>
|
||||
|
||||
{/* URL 입력 폼 */}
|
||||
<form onSubmit={handleSubmit} className="url-input-form">
|
||||
<div className="url-input-wrapper">
|
||||
<input
|
||||
type="url"
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
placeholder="네이버 지도 URL을 입력하세요"
|
||||
className="url-input-field"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!url.trim()}
|
||||
className="url-input-button"
|
||||
>
|
||||
분석 시작
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 에러 메시지 */}
|
||||
{error && (
|
||||
<p className="url-input-error">{error}</p>
|
||||
)}
|
||||
</form>
|
||||
|
||||
{/* 안내 텍스트 */}
|
||||
<p className="url-input-guide">
|
||||
네이버 지도에서 업체 URL을 복사하여 붙여넣기 해주세요.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default UrlInputContent;
|
||||
@@ -50,6 +50,7 @@ const orbConfigs: OrbConfig[] = [
|
||||
const HeroSection: React.FC<HeroSectionProps> = ({ onAnalyze, onNext, error: externalError, scrollProgress = 0 }) => {
|
||||
const [url, setUrl] = useState('');
|
||||
const [localError, setLocalError] = useState('');
|
||||
const [isFocused, setIsFocused] = useState(false);
|
||||
const orbRefs = useRef<(HTMLDivElement | null)[]>([]);
|
||||
const animationRefs = useRef<number[]>([]);
|
||||
|
||||
@@ -174,8 +175,8 @@ const HeroSection: React.FC<HeroSectionProps> = ({ onAnalyze, onNext, error: ext
|
||||
<div className="hero-content">
|
||||
{/* Logo Image */}
|
||||
<img
|
||||
src="/assets/images/castad-logo-large.svg"
|
||||
alt="CASTAD"
|
||||
src="/assets/images/ado2-logo.svg"
|
||||
alt="ADO2"
|
||||
className="hero-logo"
|
||||
/>
|
||||
|
||||
@@ -183,7 +184,7 @@ const HeroSection: React.FC<HeroSectionProps> = ({ onAnalyze, onNext, error: ext
|
||||
{/* Input Form */}
|
||||
<div className="hero-form">
|
||||
<span className="hero-input-label">URL 입력</span>
|
||||
<div className="hero-input-wrapper">
|
||||
<div className={`hero-input-wrapper ${isFocused ? 'focused' : ''} ${error ? 'error' : ''} ${url && !isFocused ? 'filled' : ''}`}>
|
||||
<input
|
||||
type="text"
|
||||
value={url}
|
||||
@@ -191,9 +192,23 @@ const HeroSection: React.FC<HeroSectionProps> = ({ onAnalyze, onNext, error: ext
|
||||
setUrl(e.target.value);
|
||||
if (localError) setLocalError('');
|
||||
}}
|
||||
onFocus={() => setIsFocused(true)}
|
||||
onBlur={() => setIsFocused(false)}
|
||||
placeholder="https://www.castad.com"
|
||||
className={`hero-input ${error ? 'error' : ''}`}
|
||||
className={`hero-input ${url ? 'has-value' : ''}`}
|
||||
/>
|
||||
{url && (
|
||||
<button
|
||||
type="button"
|
||||
className="hero-input-clear"
|
||||
onClick={() => {
|
||||
setUrl('');
|
||||
setLocalError('');
|
||||
}}
|
||||
>
|
||||
<img src="/assets/images/input-clear-icon.svg" alt="Clear" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<span className="hero-input-hint">URL에서 가져온 정보로 영상이 자동 생성됩니다.</span>
|
||||
{error && (
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
|
||||
import React from 'react';
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { getKakaoLoginUrl, kakaoCallback } from '../../utils/api';
|
||||
|
||||
interface LoginSectionProps {
|
||||
onBack: () => void;
|
||||
@@ -7,10 +8,66 @@ interface LoginSectionProps {
|
||||
}
|
||||
|
||||
const LoginSection: React.FC<LoginSectionProps> = ({ onBack, onLogin }) => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// 카카오 콜백 처리 (URL에서 code 파라미터 확인)
|
||||
useEffect(() => {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const code = urlParams.get('code');
|
||||
|
||||
if (code) {
|
||||
handleKakaoCallback(code);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleKakaoCallback = async (code: string) => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await kakaoCallback(code);
|
||||
|
||||
// URL에서 code 파라미터 제거
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.delete('code');
|
||||
window.history.replaceState({}, document.title, url.pathname);
|
||||
|
||||
// 로그인 성공
|
||||
onLogin();
|
||||
} catch (err) {
|
||||
console.error('Kakao callback failed:', err);
|
||||
setError('카카오 로그인에 실패했습니다. 다시 시도해주세요.');
|
||||
|
||||
// URL에서 code 파라미터 제거
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.delete('code');
|
||||
window.history.replaceState({}, document.title, url.pathname);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleKakaoLogin = async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await getKakaoLoginUrl();
|
||||
|
||||
// 카카오 로그인 페이지로 리다이렉트
|
||||
window.location.href = response.auth_url;
|
||||
} catch (err) {
|
||||
console.error('Failed to get Kakao login URL:', err);
|
||||
setError('로그인 URL을 가져오는데 실패했습니다. 다시 시도해주세요.');
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="login-container">
|
||||
{/* Back Button */}
|
||||
<button onClick={onBack} className="login-back-btn">
|
||||
<button onClick={onBack} className="login-back-btn" disabled={isLoading}>
|
||||
<img src="/assets/images/icon-back.svg" alt="Back" />
|
||||
<span>뒤로가기</span>
|
||||
</button>
|
||||
@@ -21,9 +78,20 @@ const LoginSection: React.FC<LoginSectionProps> = ({ onBack, onLogin }) => {
|
||||
<img src="/assets/images/login-logo.svg" alt="CASTAD" />
|
||||
</div>
|
||||
|
||||
{/* Error Message */}
|
||||
{error && (
|
||||
<div className="login-error">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Kakao Login Button */}
|
||||
<button onClick={onLogin} className="btn-kakao">
|
||||
카카오로 시작하기
|
||||
<button
|
||||
onClick={handleKakaoLogin}
|
||||
className="btn-kakao"
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? '로그인 중...' : '카카오로 시작하기'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -180,3 +180,43 @@ export const LANGUAGE_MAP: Record<string, string> = {
|
||||
'ไทย': 'Thai',
|
||||
'Tiếng Việt': 'Vietnamese',
|
||||
};
|
||||
|
||||
// 카카오 로그인 URL 응답
|
||||
export interface KakaoLoginUrlResponse {
|
||||
auth_url: string;
|
||||
}
|
||||
|
||||
// 카카오 콜백 사용자 정보
|
||||
export interface KakaoCallbackUser {
|
||||
id: number;
|
||||
nickname: string;
|
||||
email: string | null;
|
||||
profile_image_url: string | null;
|
||||
is_new_user: boolean;
|
||||
}
|
||||
|
||||
// 카카오 콜백 응답 (JWT 토큰)
|
||||
export interface KakaoCallbackResponse {
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
token_type: string;
|
||||
expires_in: number;
|
||||
user: KakaoCallbackUser;
|
||||
redirect_url: string;
|
||||
}
|
||||
|
||||
// 토큰 갱신 응답
|
||||
export interface TokenRefreshResponse {
|
||||
access_token: string;
|
||||
token_type: string;
|
||||
expires_in: number;
|
||||
}
|
||||
|
||||
// 사용자 정보 응답
|
||||
export interface UserMeResponse {
|
||||
id: number;
|
||||
kakao_id: string;
|
||||
nickname: string;
|
||||
profile_image: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
@@ -13,6 +13,10 @@ import {
|
||||
VideoDownloadResponse,
|
||||
ImageUrlItem,
|
||||
ImageUploadResponse,
|
||||
KakaoLoginUrlResponse,
|
||||
KakaoCallbackResponse,
|
||||
TokenRefreshResponse,
|
||||
UserMeResponse,
|
||||
} from '../types/api';
|
||||
|
||||
const API_URL = import.meta.env.VITE_API_URL || 'http://40.82.133.44';
|
||||
@@ -344,3 +348,160 @@ export async function waitForVideoComplete(
|
||||
|
||||
return poll();
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 카카오 인증 API
|
||||
// ============================================
|
||||
|
||||
// 토큰 저장 키
|
||||
const ACCESS_TOKEN_KEY = 'castad_access_token';
|
||||
const REFRESH_TOKEN_KEY = 'castad_refresh_token';
|
||||
|
||||
// 토큰 저장
|
||||
export function saveTokens(accessToken: string, refreshToken: string) {
|
||||
localStorage.setItem(ACCESS_TOKEN_KEY, accessToken);
|
||||
localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken);
|
||||
}
|
||||
|
||||
// 토큰 가져오기
|
||||
export function getAccessToken(): string | null {
|
||||
return localStorage.getItem(ACCESS_TOKEN_KEY);
|
||||
}
|
||||
|
||||
export function getRefreshToken(): string | null {
|
||||
return localStorage.getItem(REFRESH_TOKEN_KEY);
|
||||
}
|
||||
|
||||
// 토큰 삭제
|
||||
export function clearTokens() {
|
||||
localStorage.removeItem(ACCESS_TOKEN_KEY);
|
||||
localStorage.removeItem(REFRESH_TOKEN_KEY);
|
||||
}
|
||||
|
||||
// 인증 헤더 생성
|
||||
function getAuthHeader(): HeadersInit {
|
||||
const token = getAccessToken();
|
||||
return token ? { 'Authorization': `Bearer ${token}` } : {};
|
||||
}
|
||||
|
||||
// 카카오 로그인 URL 획득
|
||||
export async function getKakaoLoginUrl(): Promise<KakaoLoginUrlResponse> {
|
||||
const response = await fetch(`${API_URL}/user/auth/kakao/login`, {
|
||||
method: 'GET',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// 카카오 콜백 처리 (인가 코드로 JWT 토큰 발급)
|
||||
export async function kakaoCallback(code: string): Promise<KakaoCallbackResponse> {
|
||||
const response = await fetch(`${API_URL}/user/auth/kakao/callback?code=${encodeURIComponent(code)}`, {
|
||||
method: 'GET',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const data: KakaoCallbackResponse = await response.json();
|
||||
|
||||
|
||||
// 토큰 저장
|
||||
saveTokens(data.access_token, data.refresh_token);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
// Access Token 갱신
|
||||
export async function refreshAccessToken(): Promise<TokenRefreshResponse> {
|
||||
const refreshToken = getRefreshToken();
|
||||
|
||||
if (!refreshToken) {
|
||||
throw new Error('No refresh token available');
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_URL}/user/auth/refresh`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ refresh_token: refreshToken }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
// 리프레시 토큰도 만료된 경우 토큰 삭제
|
||||
if (response.status === 401) {
|
||||
clearTokens();
|
||||
}
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const data: TokenRefreshResponse = await response.json();
|
||||
|
||||
// 새 액세스 토큰 저장
|
||||
const currentRefreshToken = getRefreshToken();
|
||||
if (currentRefreshToken) {
|
||||
saveTokens(data.access_token, currentRefreshToken);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
// 로그아웃
|
||||
export async function logout(): Promise<void> {
|
||||
const response = await fetch(`${API_URL}/user/auth/logout`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...getAuthHeader(),
|
||||
},
|
||||
});
|
||||
|
||||
// 응답과 관계없이 로컬 토큰 삭제
|
||||
clearTokens();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 모든 기기에서 로그아웃
|
||||
export async function logoutAll(): Promise<void> {
|
||||
const response = await fetch(`${API_URL}/user/auth/logout/all`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...getAuthHeader(),
|
||||
},
|
||||
});
|
||||
|
||||
// 응답과 관계없이 로컬 토큰 삭제
|
||||
clearTokens();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 현재 사용자 정보 조회
|
||||
export async function getUserMe(): Promise<UserMeResponse> {
|
||||
const response = await fetch(`${API_URL}/user/auth/me`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
...getAuthHeader(),
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// 로그인 여부 확인
|
||||
export function isLoggedIn(): boolean {
|
||||
return !!getAccessToken();
|
||||
}
|
||||
Reference in new issue
Block a user