chore: 프론트엔드 마이그레이션 + 아키텍처 정의

- 백엔드 SDK 이전: FastAPI OpenAPI → orval 자동생성 (React Query 훅 포함)
- HTTP 어댑터: ky 기반 customFetcher, fetch httpClient 시그니처
- 아키텍처: features 모듈 / shared 레이어 컨벤션 정의
- 디자인 시스템: Tailwind v4 CSS-first 토큰 (브랜드 색 / status / shadcn)
- 커스텀 CSS: utilities / animations 를 custom.css 로 분리
- Docker: 개발(Dockerfile.dev + compose) / 프로덕션(nginx) 셋업
- README: 기술 스펙 / 프로젝트 구조 / 디자인 토큰 / 폰트 / SDK 사용법 정리

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
minaChoiandClaude Opus 4.7 committed 2026-05-13 11:38:07 +09:00
commit e66b208318
219 files changed
+36881

No files matched your search

@@ -0,0 +1,216 @@
/**
* MultiChannelInput — 랜딩 Hero / CTA 공용 멀티 URL 입력 컴포넌트.
*
* 설계 배경 (PART III 피봇 + 2026-04 입력 분할 개편):
* - 영업 현장에서는 병원이 본인들의 YouTube/Instagram/FB/네이버플레이스/블로그/강남언니 URL을
* 이미 알고 있는 경우가 많아 이를 직접 받는 편이 정확도·속도 면에서 우월합니다.
* - 단일 textarea + 자동 분류 방식은 사용자가 "어떻게 입력해야 하는지" 직관이 없어
* 공란이 되거나 잘못된 URL이 섞이는 경우가 많았습니다.
* - 따라서 채널별로 7개 필드를 명시적으로 노출 — 빈 칸을 보면 "여기에 무엇을 넣어야 하는지"가 명확합니다.
*
* 동작:
* 1) 7개 필드 각각에 URL 입력 (한 줄에 하나)
* 2) 입력 시 `classifyUrls()`로 검증 — 해당 채널 패턴과 매치되는지 실시간 확인
* 3) 매치 성공: 우측에 체크 아이콘, 실패: 경고 아이콘
* 4) 1개 이상 유효 입력 시 Analyze 버튼 활성화
* 5) Submit 시 onAnalyze(payload) 호출 (부모가 navigation 처리)
*
* DS 준수:
* - Filled Icons Only (lucide 무단 사용 금지)
* - DS Primary pill: rounded-full + gradient `from-[#4F1DA1] to-[#021341]`
* - variant='hero': 글래스 배경 (랜딩 Hero)
* - variant='cta': 다크 배경 (CTA 섹션)
*/
import { useMemo, useState, type ReactElement } from 'react';
import { ArrowRight } from 'lucide-react';
import {
GlobeFilled,
YoutubeFilled,
InstagramFilled,
FacebookFilled,
DatabaseFilled,
FileTextFilled,
MessageFilled,
CheckFilled,
WarningFilled,
} from '@/shared/icons/FilledIcons';
import {
classifyUrls,
hasAnalyzableChannels,
pickPrimaryUrl,
type ClassifiedUrls,
} from '../lib/classifyUrls';
import { Button } from '@/shared/ui/button';
/** discover-channels Edge Function에 전달되는 수동 채널 URL 묶음. */
export interface ManualChannels {
youtube?: string[];
instagram?: string[];
facebook?: string[];
naverPlace?: string[];
naverBlog?: string[];
gangnamUnni?: string[];
}
export interface AnalyzePayload {
/** discover-channels `url` 필드 (필수) — 홈페이지 우선, 없으면 첫 SNS URL. */
primaryUrl: string;
/** 사용자가 제공한 채널별 URL — Edge Function이 Firecrawl discovery를 스킵. */
manualChannels: ManualChannels;
/** 사용자 원본 입력 (디버깅·재실행용) */
rawInput: string;
}
interface MultiChannelInputProps {
variant?: 'hero' | 'cta';
onAnalyze: (payload: AnalyzePayload) => void;
}
type ChannelKey = keyof Omit<ClassifiedUrls, 'unknown'>;
/** 채널별 메타 — 라벨/아이콘/색상/플레이스홀더 (뷰성형외과 실 URL을 데모 placeholder로). */
const CHANNEL_META: Array<{
key: ChannelKey;
label: string;
Icon: (props: { size?: number; className?: string }) => ReactElement;
color: string;
placeholder: string;
}> = [
{ key: 'homepage', label: '홈페이지', Icon: GlobeFilled, color: 'text-brand-purple', placeholder: 'viewclinic.com' },
{ key: 'youtube', label: 'YouTube', Icon: YoutubeFilled, color: 'text-[#FF0000]', placeholder: 'youtube.com/@ViewclinicKR' },
{ key: 'instagram', label: 'Instagram', Icon: InstagramFilled,color: 'text-[#E1306C]', placeholder: 'instagram.com/viewplastic' },
{ key: 'facebook', label: 'Facebook', Icon: FacebookFilled, color: 'text-[#1877F2]', placeholder: 'facebook.com/viewps1' },
{ key: 'naverPlace', label: '네이버 플레이스', Icon: DatabaseFilled, color: 'text-[#03C75A]', placeholder: 'place.naver.com/hospital/11709005' },
{ key: 'naverBlog', label: '네이버 블로그', Icon: FileTextFilled, color: 'text-[#03C75A]', placeholder: 'blog.naver.com/viewclinicps' },
{ key: 'gangnamUnni', label: '강남언니', Icon: MessageFilled, color: 'text-[#FF5C89]', placeholder: 'gangnamunni.com/hospitals/189' },
];
type EmptyClassified = Record<ChannelKey, string>;
const EMPTY_URLS: EmptyClassified = {
homepage: '', youtube: '', instagram: '', facebook: '',
naverPlace: '', naverBlog: '', gangnamUnni: '',
};
/**
* 단일 입력값 검증 — 해당 채널 패턴과 매치되는지.
* 빈 값: 'empty', 매치 성공: 'valid', SNS인데 다른 채널: 'wrong', 파싱 실패: 'invalid'
*/
function validateField(value: string, expected: ChannelKey): 'empty' | 'valid' | 'wrong' | 'invalid' {
if (!value.trim()) return 'empty';
const c = classifyUrls(value);
if (c[expected].length > 0) return 'valid';
// 다른 채널로 분류됐으면 'wrong', unknown이면 'invalid'
for (const k of Object.keys(c) as Array<keyof ClassifiedUrls>) {
if (k !== 'unknown' && k !== expected && c[k].length > 0) return 'wrong';
}
return 'invalid';
}
export default function MultiChannelInput({ variant = 'hero', onAnalyze }: MultiChannelInputProps) {
const [urls, setUrls] = useState<EmptyClassified>(EMPTY_URLS);
// 통합 분류 결과 — 7개 필드 값을 join해 classifyUrls에 한 번에 통과시켜 manualChannels 구성.
const aggregated = useMemo(() => {
const joined = Object.values(urls).filter(Boolean).join('\n');
return classifyUrls(joined);
}, [urls]);
const canAnalyze = hasAnalyzableChannels(aggregated);
const primaryUrl = pickPrimaryUrl(aggregated);
const handleSubmit = () => {
if (!canAnalyze || !primaryUrl) return;
const payload: AnalyzePayload = {
primaryUrl,
manualChannels: {
youtube: aggregated.youtube.length ? aggregated.youtube : undefined,
instagram: aggregated.instagram.length ? aggregated.instagram : undefined,
facebook: aggregated.facebook.length ? aggregated.facebook : undefined,
naverPlace: aggregated.naverPlace.length ? aggregated.naverPlace : undefined,
naverBlog: aggregated.naverBlog.length ? aggregated.naverBlog : undefined,
gangnamUnni: aggregated.gangnamUnni.length ? aggregated.gangnamUnni : undefined,
},
rawInput: Object.entries(urls)
.filter(([, v]) => v.trim())
.map(([k, v]) => `${k}: ${v}`)
.join('\n'),
};
onAnalyze(payload);
};
// variant별 스타일 토큰
const isHero = variant === 'hero';
const inputClass = isHero
? 'w-full pl-11 pr-10 py-2.5 text-sm bg-white/80 backdrop-blur-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-accent/20 focus:border-accent/40 shadow-sm text-primary-900 placeholder:text-slate-400 transition-all'
: 'w-full pl-11 pr-10 py-2.5 text-sm bg-white/5 backdrop-blur-sm border border-white/15 rounded-xl focus:outline-none focus:ring-2 focus:ring-accent/30 focus:border-accent/60 text-white placeholder:text-white/40 transition-all';
const labelClass = isHero ? 'text-slate-600' : 'text-white/70';
const helperClass = isHero ? 'text-slate-500' : 'text-white/60';
return (
<div className="w-full max-w-2xl mx-auto">
{/* 7개 채널별 입력 필드 — 한 줄에 하나, 좌측 아이콘 + 우측 검증 상태 */}
<div className="flex flex-col gap-2">
{CHANNEL_META.map(({ key, label, Icon, color, placeholder }) => {
const value = urls[key];
const status = validateField(value, key);
return (
<div key={key} className="relative">
{/* 좌측 채널 아이콘 — 입력 시 컬러 적용, 빈 칸일 땐 회색 */}
<div className="absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none flex items-center gap-2">
<Icon size={16} className={value ? color : isHero ? 'text-slate-400' : 'text-white/40'} />
</div>
{/* 채널 라벨 — 좌측 상단 작은 라벨로 placeholder 위에 노출 */}
<input
type="url"
inputMode="url"
value={value}
onChange={(e) => setUrls((prev) => ({ ...prev, [key]: e.target.value }))}
placeholder={`${label} · ${placeholder}`}
aria-label={label}
className={inputClass}
spellCheck={false}
autoComplete="off"
/>
{/* 우측 검증 상태 아이콘 */}
<div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none">
{status === 'valid' && (
<CheckFilled size={16} className="text-emerald-500" />
)}
{(status === 'wrong' || status === 'invalid') && (
<WarningFilled size={16} className={isHero ? 'text-amber-500' : 'text-amber-300'} />
)}
</div>
</div>
);
})}
</div>
{/* 보조 안내 — 1개 이상 입력 시 어느 채널이 분석 대상인지 요약 */}
<p className={`text-xs font-medium mt-3 text-center leading-relaxed break-keep ${labelClass}`}>
7개 채널 중 알고 계신 URL만 입력해주세요 — 1개만 입력하셔도 분석이 시작됩니다.
</p>
{/* 분석 시작 버튼 — DS Primary pill */}
<Button
onClick={handleSubmit}
disabled={!canAnalyze}
className={`w-full max-w-md mx-auto mt-4 px-10 py-4 h-auto text-lg font-medium rounded-full shadow-xl hover:shadow-2xl flex items-center justify-center gap-2 group bg-gradient-to-r transform-gpu will-change-transform transition-[transform,filter,box-shadow] duration-500 ease-[cubic-bezier(0.16,1,0.3,1)] motion-safe:hover:scale-[1.02] motion-safe:hover:brightness-110 active:scale-[0.98] active:duration-150 ${
isHero
? 'from-brand-purple to-brand-purple-deep text-white'
: 'from-brand-grad-peach via-brand-grad-violet to-brand-grad-sky text-primary-900'
}`}
>
Analyze
<ArrowRight className="size-5 transform-gpu will-change-transform transition-transform duration-500 ease-[cubic-bezier(0.16,1,0.3,1)] motion-safe:group-hover:translate-x-1" />
</Button>
{/* 보조 안내 (하단) */}
<p className={`text-xs font-medium mt-3 text-center leading-relaxed break-keep ${helperClass}`}>
네이버 블로그 · 플레이스 · 소셜미디어 등 Online Presence 종합 분석 리포트를 제공합니다.
</p>
</div>
);
}
@@ -0,0 +1,94 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { useVerifyChannels } from '@/shared/api/generated/channels/channels';
import { mergeEnrichment, type EnrichmentData } from '@/features/report/lib/transformReport';
import type { MarketingReport } from '@/features/report/types/report';
// TODO(migration): 기존 enrichChannels Edge Function 은 백엔드의 /api/channels/verify 로 통합.
// 응답 스펙이 약간 다르므로 데이터 정합 시점에 추가 매핑 필요.
type EnrichmentStatus = 'idle' | 'loading' | 'success' | 'error';
interface UseEnrichmentResult {
status: EnrichmentStatus;
enrichedReport: MarketingReport | null;
/** 재시도 시도 횟수 */
retryCount: number;
/** enrichment를 재시도할 때 호출 (최대 2회 재시도) */
retry: () => void;
}
interface EnrichmentParams {
reportId: string | null;
clinicName: string;
instagramHandle?: string;
instagramHandles?: string[];
youtubeChannelId?: string;
facebookHandle?: string;
address?: string;
}
const MAX_RETRIES = 2;
/**
* Phase 1 리포트 렌더링 후 백그라운드 채널 enrichment를 트리거.
* 한 번만 실행되며, 백엔드 verify 엔드포인트 완료(~27초)까지 대기한 후
* 병합된 리포트를 반환. 최대 2회까지 수동 재시도 지원.
*/
export function useEnrichment(
baseReport: MarketingReport | null,
params: EnrichmentParams | null,
): UseEnrichmentResult {
const [status, setStatus] = useState<EnrichmentStatus>('idle');
const [enrichedReport, setEnrichedReport] = useState<MarketingReport | null>(null);
const [retryCount, setRetryCount] = useState(0);
const hasTriggered = useRef(false);
const { mutateAsync: verifyChannelsAsync } = useVerifyChannels();
const doEnrich = useCallback(async () => {
if (!baseReport || !params?.reportId) return;
setStatus('loading');
try {
const result = await verifyChannelsAsync({
// TODO(migration): backend ChannelVerifyRequest 스키마와 정확한 필드 매핑 확인 필요
data: {
instagram: params.instagramHandle ? { handle: params.instagramHandle } : undefined,
youtube: params.youtubeChannelId ? { channel_id: params.youtubeChannelId } : undefined,
facebook: params.facebookHandle ? { handle: params.facebookHandle } : undefined,
} as unknown as Parameters<typeof verifyChannelsAsync>[0]['data'],
});
if (result.status === 200 && result.data) {
const merged = mergeEnrichment(baseReport, result.data as unknown as EnrichmentData);
setEnrichedReport(merged);
setStatus('success');
} else {
setStatus('error');
}
} catch {
setStatus('error');
}
}, [baseReport, params, verifyChannelsAsync]);
// 초기 트리거
useEffect(() => {
if (!baseReport || !params?.reportId || hasTriggered.current) return;
hasTriggered.current = true;
doEnrich();
}, [baseReport, params, doEnrich]);
// 수동 재시도
const retry = useCallback(() => {
if (retryCount >= MAX_RETRIES) return;
setRetryCount(prev => prev + 1);
doEnrich();
}, [retryCount, doEnrich]);
return {
status,
enrichedReport,
retryCount,
retry,
};
}
+258
View File
@@ -0,0 +1,258 @@
/**
* classifyUrls — 랜딩 MultiChannelInput 전용 URL 분류 유틸.
*
* 사용자가 textarea에 붙여넣은 여러 URL을 7개 채널(holder)로 분류합니다.
* - homepage · youtube · instagram · facebook · naverPlace · naverBlog · gangnamUnni · unknown
*
* 설계 결정:
* 1) 결정론적 regex 분류 (AI 추측 없음) — 백엔드의 extractSocialLinks 패턴을 브라우저로 복제.
* ⚠️ 백엔드와 프론트 두 곳의 패턴은 **동일하게 유지**되어야 합니다. SNS 플랫폼 URL 구조 변경 시 같이 수정하세요.
*
* 2) 우선순위: naverPlace / gangnamUnni (고유 도메인) → YouTube / Instagram / Facebook / naverBlog
* → 미매치이면서 `new URL()` 성공한 URL 중 **호스트네임이 SNS 도메인이 아닌 경우만** homepage.
* 호스트네임이 SNS인데 프로필 패턴 불일치 (예: instagram.com/p/XYZ, youtube.com/watch)는 `unknown`.
* ▸ "homepage" 필드가 분석 첫 진입점이라서, 여기에 잘못된 URL이 들어가면 전체 파이프라인이
* 잘못된 축으로 돌아갑니다. 따라서 방어적으로 분류합니다.
*
* 3) 값은 **원본 URL 문자열**을 그대로 보관 — backend `discover-channels`의 `manualChannels`는
* URL을 받아서 내부에서 handle을 추출하므로, 프론트에서 미리 handle로 변환하지 않습니다.
* (백엔드 discover-channels 워커가 extractHandleFromUrl 처리)
*
* 4) 중복 제거 — 공백/줄바꿈/쉼표로 분리 후, 정규화된 URL(소문자 + trailing slash 제거) 기준으로 dedup.
*/
export interface ClassifiedUrls {
homepage: string[];
youtube: string[];
instagram: string[];
facebook: string[];
naverPlace: string[];
naverBlog: string[];
gangnamUnni: string[];
/** 파싱 실패 or SNS 도메인이지만 프로필이 아닌 URL (포스트/비디오 등) */
unknown: string[];
}
/** SNS 호스트네임 집합 — 이들 도메인인데 프로필 패턴에 매치되지 않으면 `unknown`으로 강제. */
const SNS_HOSTNAMES = new Set([
'instagram.com',
'www.instagram.com',
'm.instagram.com',
'youtube.com',
'www.youtube.com',
'm.youtube.com',
'youtu.be',
'facebook.com',
'www.facebook.com',
'm.facebook.com',
'fb.com',
'blog.naver.com',
'm.blog.naver.com',
'place.naver.com',
'm.place.naver.com',
'map.naver.com',
'gangnamunni.com',
'm.gangnamunni.com',
'www.gangnamunni.com',
]);
/** Instagram 프로필이 아닌 경로 (포스트/릴/스토리 등) */
const IG_SKIP = new Set([
'p', 'reel', 'reels', 'stories', 'explore', 'accounts',
'about', 'developer', 'legal', 'privacy', 'terms',
]);
/** Facebook 페이지가 아닌 경로 */
const FB_SKIP = new Set([
'sharer', 'share', 'login', 'help', 'pages', 'events', 'groups',
'marketplace', 'watch', 'gaming', 'privacy', 'policies', 'tr',
'dialog', 'plugins', 'photo', 'video', 'reel',
]);
/** YouTube 프로필 패턴: `@handle`, `channel/UC...`, `c/custom`, `user/...` */
const YT_PROFILE_RE = /youtube\.com\/(?:@[a-zA-Z0-9._-]+|channel\/UC[a-zA-Z0-9_-]+|c\/[a-zA-Z0-9._-]+|user\/[a-zA-Z0-9._-]+)/i;
/** Naver Place: m.place.naver.com/hospital/{id}, place.naver.com/hospital/{id}, map.naver.com/p/entry/place/{id} */
const NAVER_PLACE_RE = /(?:m\.)?place\.naver\.com\/[a-z]+\/\d+|map\.naver\.com\/p\/entry\/place\/\d+/i;
/** Naver Blog: blog.naver.com/{id} (또는 m.blog.naver.com) */
const NAVER_BLOG_RE = /(?:m\.)?blog\.naver\.com\/[a-zA-Z0-9_-]+/i;
/** 강남언니: gangnamunni.com/hospitals/{id-or-slug} */
const GANGNAMUNNI_RE = /(?:m\.|www\.)?gangnamunni\.com\/hospitals?\/[a-zA-Z0-9_-]+/i;
/** Instagram 프로필: instagram.com/{handle} — 포스트/릴 등은 아래 IG_SKIP로 걸러냄 */
const IG_RE = /(?:www\.|m\.)?instagram\.com\/([a-zA-Z0-9._]+)\/?/i;
/** Facebook 페이지: facebook.com/{page} */
const FB_RE = /(?:www\.|m\.)?facebook\.com\/([a-zA-Z0-9._-]+)\/?/i;
/**
* URL 문자열을 정규화해 중복 체크 키로 사용.
* - 소문자, trailing slash 제거, scheme 유지
* - URL 파싱 실패 시 원본 trim.
*/
function normalizeForDedup(url: string): string {
try {
const u = new URL(url);
const path = u.pathname.replace(/\/+$/, '');
return `${u.protocol}//${u.hostname.toLowerCase()}${path}${u.search}`.toLowerCase();
} catch {
return url.trim().toLowerCase();
}
}
/**
* 단일 URL 토큰을 분류해서 어느 버킷에 넣을지 결정.
* 반환값: [bucketKey, originalUrl] 또는 null (이미 중복).
*/
function classifySingle(
rawToken: string,
): { bucket: keyof ClassifiedUrls; value: string } | null {
const token = rawToken.trim();
if (!token || token.length < 4) return null;
// URL 파싱 시도 — 실패하면 unknown
let parsed: URL;
try {
// scheme 없는 경우 https:// 추가 (예: "instagram.com/foo")
const withScheme = /^https?:\/\//i.test(token) ? token : `https://${token}`;
parsed = new URL(withScheme);
} catch {
return { bucket: 'unknown', value: token };
}
const hostname = parsed.hostname.toLowerCase();
const fullUrl = parsed.toString();
// 1) Naver Place (고유 도메인)
if (NAVER_PLACE_RE.test(fullUrl)) {
return { bucket: 'naverPlace', value: fullUrl };
}
// 2) 강남언니 (고유 도메인)
if (GANGNAMUNNI_RE.test(fullUrl)) {
return { bucket: 'gangnamUnni', value: fullUrl };
}
// 3) Naver Blog
if (NAVER_BLOG_RE.test(fullUrl)) {
return { bucket: 'naverBlog', value: fullUrl };
}
// 4) YouTube — 프로필 패턴만 매치
if (hostname.endsWith('youtube.com') || hostname === 'youtu.be') {
if (YT_PROFILE_RE.test(fullUrl)) {
return { bucket: 'youtube', value: fullUrl };
}
// youtube.com 인데 프로필 아님 (watch URL 등) → unknown
return { bucket: 'unknown', value: fullUrl };
}
// 5) Instagram
if (hostname.endsWith('instagram.com')) {
const m = fullUrl.match(IG_RE);
const firstSeg = m?.[1];
if (firstSeg && !IG_SKIP.has(firstSeg.toLowerCase())) {
return { bucket: 'instagram', value: fullUrl };
}
return { bucket: 'unknown', value: fullUrl };
}
// 6) Facebook
if (hostname.endsWith('facebook.com') || hostname.endsWith('fb.com')) {
const m = fullUrl.match(FB_RE);
const firstSeg = m?.[1];
if (firstSeg && !FB_SKIP.has(firstSeg.toLowerCase())) {
return { bucket: 'facebook', value: fullUrl };
}
return { bucket: 'unknown', value: fullUrl };
}
// 7) 남은 케이스: SNS 도메인이면 unknown (프로필 패턴 미매치), 아니면 homepage
if (SNS_HOSTNAMES.has(hostname)) {
return { bucket: 'unknown', value: fullUrl };
}
return { bucket: 'homepage', value: fullUrl };
}
/**
* 사용자 textarea 입력 → 7채널 분류 결과.
* 공백/쉼표/줄바꿈으로 분리된 각 토큰을 개별 URL로 간주합니다.
*/
export function classifyUrls(input: string): ClassifiedUrls {
const result: ClassifiedUrls = {
homepage: [],
youtube: [],
instagram: [],
facebook: [],
naverPlace: [],
naverBlog: [],
gangnamUnni: [],
unknown: [],
};
if (!input || typeof input !== 'string') return result;
// 공백/쉼표/줄바꿈으로 분리
const tokens = input.split(/[\s,]+/).map((t) => t.trim()).filter(Boolean);
// 버킷별 중복 체크 — 같은 URL이 textarea에 두 번 나와도 한 번만
const seen: Record<keyof ClassifiedUrls, Set<string>> = {
homepage: new Set(),
youtube: new Set(),
instagram: new Set(),
facebook: new Set(),
naverPlace: new Set(),
naverBlog: new Set(),
gangnamUnni: new Set(),
unknown: new Set(),
};
for (const token of tokens) {
const classified = classifySingle(token);
if (!classified) continue;
const key = normalizeForDedup(classified.value);
if (seen[classified.bucket].has(key)) continue;
seen[classified.bucket].add(key);
result[classified.bucket].push(classified.value);
}
return result;
}
/**
* 채널 중 하나라도 분석 대상이 있는지 — 분석 시작 버튼 활성화 조건.
* homepage·SNS 중 최소 1건이 있으면 true. unknown은 제외.
*/
export function hasAnalyzableChannels(classified: ClassifiedUrls): boolean {
return (
classified.homepage.length > 0 ||
classified.youtube.length > 0 ||
classified.instagram.length > 0 ||
classified.facebook.length > 0 ||
classified.naverPlace.length > 0 ||
classified.naverBlog.length > 0 ||
classified.gangnamUnni.length > 0
);
}
/**
* 분석 파이프라인의 "primary URL" 결정.
* 홈페이지가 있으면 최우선, 없으면 검출된 첫 SNS URL 반환.
* 백엔드 startAnalysis 요청의 `url` 필드 (필수)로 사용됩니다.
*/
export function pickPrimaryUrl(classified: ClassifiedUrls): string | null {
if (classified.homepage[0]) return classified.homepage[0];
// 홈페이지 없으면 SNS 중 아무거나 대표값으로
const fallback =
classified.naverPlace[0] ||
classified.instagram[0] ||
classified.youtube[0] ||
classified.facebook[0] ||
classified.naverBlog[0] ||
classified.gangnamUnni[0];
return fallback || null;
}
@@ -0,0 +1,32 @@
/**
* 다양한 입력 형식의 Instagram 핸들을 순수 username 으로 정규화.
* 백엔드 normalizeHandles 유틸의 브라우저측 사본 — 두 파일을 항상 동기화 유지.
*/
export function normalizeInstagramHandle(
raw: string | null | undefined,
): string | null {
if (!raw || typeof raw !== 'string') return null;
let handle = raw.trim();
if (!handle) return null;
if (handle.includes('instagram.com')) {
try {
const urlStr = handle.startsWith('http') ? handle : `https://${handle}`;
const url = new URL(urlStr);
const segments = url.pathname.split('/').filter(Boolean);
handle = segments[0] || '';
} catch {
const match = handle.match(/instagram\.com\/([^/?#]+)/);
handle = match?.[1] || '';
}
}
if (handle.startsWith('@')) {
handle = handle.slice(1);
}
handle = handle.replace(/\/+$/, '');
return handle || null;
}
@@ -0,0 +1,376 @@
import { useState, useCallback } from 'react';
import { useNavigate } from 'react-router';
import { motion, AnimatePresence } from 'motion/react';
import {
YoutubeFilled,
InstagramFilled,
FacebookFilled,
GlobeFilled,
TiktokFilled,
} from '@/shared/icons/FilledIcons';
import type { ComponentType } from 'react';
import { Button } from '@/shared/ui/button';
import { Input } from '@/shared/ui/input';
interface ChannelDef {
id: string;
name: string;
description: string;
icon: ComponentType<{ size?: number; className?: string }>;
brandColor: string;
bgColor: string;
borderColor: string;
fields: { key: string; label: string; placeholder: string; type?: string }[];
}
const CHANNELS: ChannelDef[] = [
{
id: 'youtube',
name: 'YouTube',
description: '채널 연동으로 영상 자동 업로드, 성과 분석',
icon: YoutubeFilled,
brandColor: '#FF0000',
bgColor: '#FFF0F0',
borderColor: '#F5D5DC',
fields: [
{ key: 'channelUrl', label: '채널 URL', placeholder: 'https://youtube.com/@YourChannel' },
],
},
{
id: 'instagram_kr',
name: 'Instagram KR',
description: '한국 계정 — Reels, Feed, Stories 자동 게시',
icon: InstagramFilled,
brandColor: '#E1306C',
bgColor: '#FFF0F5',
borderColor: '#F5D0DC',
fields: [
{ key: 'handle', label: '핸들', placeholder: '@viewclinic_kr' },
],
},
{
id: 'instagram_en',
name: 'Instagram EN',
description: '글로벌 계정 — 해외 환자 대상 콘텐츠',
icon: InstagramFilled,
brandColor: '#E1306C',
bgColor: '#FFF0F5',
borderColor: '#F5D0DC',
fields: [
{ key: 'handle', label: '핸들', placeholder: '@viewplasticsurgery' },
],
},
{
id: 'facebook_kr',
name: 'Facebook KR',
description: '한국 페이지 — 광고 리타겟, 콘텐츠 배포',
icon: FacebookFilled,
brandColor: '#1877F2',
bgColor: '#F0F4FF',
borderColor: '#C5D5F5',
fields: [
{ key: 'pageUrl', label: '페이지 URL', placeholder: 'https://facebook.com/YourPage' },
],
},
{
id: 'facebook_en',
name: 'Facebook EN',
description: '글로벌 페이지 — 해외 환자 유입',
icon: FacebookFilled,
brandColor: '#1877F2',
bgColor: '#F0F4FF',
borderColor: '#C5D5F5',
fields: [
{ key: 'pageUrl', label: '페이지 URL', placeholder: 'https://facebook.com/YourPageEN' },
],
},
{
id: 'naver_blog',
name: 'Naver Blog',
description: 'SEO 블로그 포스트 자동 게시, 키워드 최적화',
icon: GlobeFilled,
brandColor: '#03C75A',
bgColor: '#F0FFF5',
borderColor: '#C5F5D5',
fields: [
{ key: 'blogUrl', label: '블로그 URL', placeholder: 'https://blog.naver.com/yourblog' },
{ key: 'apiKey', label: 'API Key', placeholder: 'Naver Open API Key', type: 'password' },
],
},
{
id: 'naver_place',
name: 'Naver Place',
description: '플레이스 정보 동기화, 리뷰 모니터링',
icon: GlobeFilled,
brandColor: '#03C75A',
bgColor: '#F0FFF5',
borderColor: '#C5F5D5',
fields: [
{ key: 'placeUrl', label: '플레이스 URL', placeholder: 'https://map.naver.com/...' },
],
},
{
id: 'tiktok',
name: 'TikTok',
description: 'Shorts 크로스포스팅, 트렌드 콘텐츠',
icon: TiktokFilled,
brandColor: '#000000',
bgColor: '#F5F5F5',
borderColor: '#E0E0E0',
fields: [
{ key: 'handle', label: '핸들', placeholder: '@yourclinic' },
],
},
{
id: 'gangnamunni',
name: '강남언니',
description: '리뷰 모니터링, 평점 추적, 시술 정보 동기화',
icon: GlobeFilled,
brandColor: '#6B2D8B',
bgColor: '#F3F0FF',
borderColor: '#D5CDF5',
fields: [
{ key: 'hospitalUrl', label: '병원 페이지 URL', placeholder: 'https://gangnamunni.com/hospitals/...' },
],
},
{
id: 'website',
name: 'Website',
description: '홈페이지 SEO 모니터링, 트래킹 픽셀 관리',
icon: GlobeFilled,
brandColor: '#6C5CE7',
bgColor: '#F3F0FF',
borderColor: '#D5CDF5',
fields: [
{ key: 'url', label: '웹사이트 URL', placeholder: 'https://www.yourclinic.com' },
{ key: 'gaId', label: 'Google Analytics ID', placeholder: 'G-XXXXXXXXXX' },
],
},
];
type ConnectionStatus = 'disconnected' | 'connecting' | 'connected';
interface ChannelState {
status: ConnectionStatus;
values: Record<string, string>;
}
export default function ChannelConnectPage() {
const navigate = useNavigate();
const [channels, setChannels] = useState<Record<string, ChannelState>>(() => {
const init: Record<string, ChannelState> = {};
for (const ch of CHANNELS) {
init[ch.id] = { status: 'disconnected', values: {} };
}
return init;
});
const [expandedId, setExpandedId] = useState<string | null>(null);
const handleFieldChange = useCallback((channelId: string, fieldKey: string, value: string) => {
setChannels(prev => ({
...prev,
[channelId]: {
...prev[channelId],
values: { ...prev[channelId].values, [fieldKey]: value },
},
}));
}, []);
const handleConnect = useCallback((channelId: string) => {
setChannels(prev => ({
...prev,
[channelId]: { ...prev[channelId], status: 'connecting' },
}));
// 연결 시뮬레이션
setTimeout(() => {
setChannels(prev => ({
...prev,
[channelId]: { ...prev[channelId], status: 'connected' },
}));
}, 2000);
}, []);
const handleDisconnect = useCallback((channelId: string) => {
setChannels(prev => ({
...prev,
[channelId]: { status: 'disconnected', values: {} },
}));
}, []);
const connectedCount = (Object.values(channels) as ChannelState[]).filter(c => c.status === 'connected').length;
return (
<div className="pt-20 min-h-screen">
{/* Header */}
<div className="bg-gradient-to-r from-brand-grad-peach via-brand-grad-violet to-brand-grad-sky py-16 px-6">
<div className="max-w-5xl mx-auto">
<p className="text-xs font-semibold text-brand-purple-vivid tracking-widest uppercase mb-3">Channel Integration</p>
<h1 className="font-serif text-3xl md:text-4xl font-bold text-brand-purple-deep mb-3">
채널 연결
</h1>
<p className="text-brand-purple-deep/60 max-w-xl">
소셜 미디어와 플랫폼을 연결하여 콘텐츠를 자동으로 배포하고 성과를 추적하세요.
</p>
{/* Connection Summary + Distribute Button */}
<div className="flex items-center gap-4 mt-8">
<div className="flex items-center gap-2 px-4 py-2 rounded-full bg-white/70 backdrop-blur-sm border border-white/40">
<div className={`w-3 h-3 rounded-full ${connectedCount > 0 ? 'bg-brand-purple-vivid' : 'bg-slate-300'}`} />
<span className="text-sm font-medium text-brand-purple-deep">
{connectedCount} / {CHANNELS.length} 연결됨
</span>
</div>
{connectedCount > 0 && (
<Button
onClick={() => navigate('/distribute')}
className="flex items-center gap-2 px-5 py-2 h-auto rounded-full bg-gradient-to-r from-brand-purple to-brand-purple-deep text-white text-sm font-medium shadow-md hover:shadow-lg transition-all"
>
콘텐츠 배포하기
<svg width="16" height="16" viewBox="0 0 16 16" fill="none">
<path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</Button>
)}
</div>
</div>
</div>
{/* Channel Grid */}
<div className="max-w-5xl mx-auto px-6 py-12">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{CHANNELS.map(ch => {
const state = channels[ch.id];
const isExpanded = expandedId === ch.id;
const Icon = ch.icon;
const allFieldsFilled = ch.fields.every(f => (state.values[f.key] ?? '').trim().length > 0);
return (
<motion.div
key={ch.id}
layout
className={`rounded-2xl border-2 overflow-hidden transition-all ${
state.status === 'connected'
? 'border-brand-tint-lavender bg-brand-tint-purple/20'
: isExpanded
? 'border-brand-purple-vivid bg-white shadow-[3px_4px_12px_rgba(108,92,231,0.12)]'
: 'border-slate-100 bg-white shadow-[3px_4px_12px_rgba(0,0,0,0.06)] hover:border-brand-tint-lavender'
}`}
>
{/* Card Header */}
<Button
variant="ghost"
onClick={() => setExpandedId(isExpanded ? null : ch.id)}
className="w-full h-auto flex items-center justify-start gap-4 p-5 text-left rounded-none whitespace-normal hover:bg-transparent"
>
<div
className="w-11 h-11 rounded-xl flex items-center justify-center shrink-0"
style={{ backgroundColor: ch.bgColor }}
>
<Icon size={22} style={{ color: ch.brandColor }} />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<h3 className="font-semibold text-brand-navy">{ch.name}</h3>
{state.status === 'connected' && (
<span className="px-2 py-1 rounded-full bg-brand-tint-purple text-brand-purple-muted text-xs font-semibold border border-brand-tint-lavender">
연결됨
</span>
)}
</div>
<p className="text-xs text-slate-500 mt-1 truncate">{ch.description}</p>
</div>
<svg
width="20" height="20" viewBox="0 0 20 20" fill="none"
className={`shrink-0 text-slate-400 transition-transform ${isExpanded ? 'rotate-180' : ''}`}
>
<path d="M5 7.5L10 12.5L15 7.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</Button>
{/* Expanded Content */}
<AnimatePresence>
{isExpanded && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.25 }}
className="overflow-hidden"
>
<div className="px-5 pb-5 pt-1 border-t border-slate-100">
{state.status === 'connected' ? (
<div>
<div className="flex items-center gap-2 mb-4 mt-3">
<div className="w-2 h-2 rounded-full bg-brand-purple-vivid" />
<span className="text-sm text-brand-purple-muted font-medium">연결 상태: 활성</span>
</div>
{ch.fields.map(f => (
<div key={f.key} className="mb-2">
<span className="text-xs text-slate-400">{f.label}</span>
<p className="text-sm text-slate-700 font-medium">
{f.type === 'password' ? '••••••••' : state.values[f.key]}
</p>
</div>
))}
<Button
variant="outline"
onClick={() => handleDisconnect(ch.id)}
className="mt-4 w-full h-auto py-3 rounded-full bg-white border-brand-rose-soft text-brand-rose text-sm font-medium hover:bg-brand-rose-bg"
>
연결 해제
</Button>
</div>
) : (
<div className="mt-3">
{ch.fields.map(f => (
<div key={f.key} className="mb-3">
<label className="text-xs font-medium text-slate-600 mb-1 block">{f.label}</label>
<Input
type={f.type ?? 'text'}
value={state.values[f.key] ?? ''}
onChange={e => handleFieldChange(ch.id, f.key, e.target.value)}
placeholder={f.placeholder}
className="w-full px-4 py-3 h-auto rounded-xl border-slate-200 text-sm text-slate-700 placeholder:text-slate-300 focus-visible:border-brand-purple-vivid focus-visible:ring-brand-purple-vivid/20"
/>
</div>
))}
<div className="flex gap-2 mt-4">
<Button
onClick={() => handleConnect(ch.id)}
disabled={!allFieldsFilled || state.status === 'connecting'}
className="flex-1 h-auto flex items-center justify-center gap-2 py-3 rounded-full bg-gradient-to-r from-brand-purple to-brand-purple-deep text-white text-sm font-medium shadow-md hover:shadow-lg transition-all disabled:opacity-40 disabled:cursor-not-allowed"
>
{state.status === 'connecting' ? (
<>
<div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
연결 중...
</>
) : (
'연결하기'
)}
</Button>
<Button
variant="outline"
className="h-auto px-4 py-3 rounded-full bg-white border-slate-200 text-slate-500 text-sm font-medium hover:bg-slate-50"
>
OAuth
</Button>
</div>
</div>
)}
</div>
</motion.div>
)}
</AnimatePresence>
</motion.div>
);
})}
</div>
</div>
</div>
);
}
+8
View File
@@ -0,0 +1,8 @@
import { lazy } from 'react'
import type { RouteObject } from 'react-router'
const ChannelConnectPage = lazy(() => import('./pages/ChannelConnectPage'))
export const channelsRoutes: RouteObject[] = [
{ path: 'channels', element: <ChannelConnectPage /> },
]