feat: Content Director engine + report diagnosis/roadmap/KPI overhaul + PDF export fix

- Content Director (contentDirector.ts): deterministic 4-week editorial
  calendar engine — pillar-service matrix, channel-format slots, weekly
  themes (브랜드 정비 → 콘텐츠 엔진 → 소셜 증거 → 전환 최적화)
- transformPlan.ts: buildCalendar() delegates to Content Director with
  enrichment data (YouTube videos for repurposing)
- transformReport.ts: buildTransformation() generates rich per-channel
  platform strategies; buildRoadmap() creates Foundation/Content Engine/
  Optimization 3-phase plan; buildKpiDashboard() generates 10+ channel-
  specific metrics with targets
- ProblemDiagnosis: clustered 3 core issues (brand/content/funnel) in
  glass cards + expandable detail list
- RoadmapTimeline: Foundation/Content Engine/Optimization structure
- KPIDashboard: formatKpiValue() for human-readable numbers (150K, 1.5M)
- YouTubeAudit: metric-based diagnosis rows (subscriber ratio, upload freq)
- ContentCalendar: week theme labels, channel symbols, compact entries
- useExportPDF: triggerAllAnimations() scrolls all sections to fire
  whileInView before capture; isDarkSection() keeps dark sections whole;
  forceVisible() 2-pass opacity/transform override

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Haewon KamandClaude Opus 4.6 committed 2026-04-03 20:07:39 +09:00
1 parent e32b8766de
commit da267fd744
12 files changed
+1159 -340

No files matched your search

+334 -103
View File
@@ -165,6 +165,263 @@ function buildDiagnosis(report: ApiReport): DiagnosisItem[] {
return items;
}
function buildTransformation(r: ApiReport): import('../types/report').TransformationProposal {
const channels = r.channelAnalysis || {};
// Brand Identity — from AI or generate defaults
const brandIdentity = (r.brandIdentity || [])
.filter((item): item is { area?: string; asIs?: string; toBe?: string } => !!item?.area)
.map(item => ({ area: item.area || '', asIs: item.asIs || '', toBe: item.toBe || '' }));
if (brandIdentity.length === 0) {
brandIdentity.push(
{ area: '로고 사용', asIs: '채널마다 다른 로고/프로필 이미지 사용', toBe: '공식 로고 가이드 기반 전 채널 통일' },
{ area: '컬러 시스템', asIs: '통일된 브랜드 컬러 없음', toBe: '주/보조 컬러 지정 및 전 채널 적용' },
{ area: '톤앤매너', asIs: '채널별 다른 커뮤니케이션 스타일', toBe: '브랜드 보이스 가이드 수립 및 적용' },
);
}
// Content Strategy
const contentStrategy = (r.recommendations || [])
.filter(rec => rec.category?.includes('콘텐츠') || rec.category?.includes('content'))
.map(rec => ({ area: rec.title || '', asIs: rec.description || '', toBe: rec.expectedImpact || '' }));
if (contentStrategy.length === 0) {
contentStrategy.push(
{ area: '콘텐츠 캘린더', asIs: '캘린더 없음, 비정기 업로드', toBe: '주간 콘텐츠 캘린더 운영 (주 5-10건)' },
{ area: '숏폼 전략', asIs: 'Shorts/Reels 미운영 또는 미비', toBe: 'YouTube Shorts + Instagram Reels 크로스 포스팅' },
{ area: '콘텐츠 다변화', asIs: '단일 포맷 위주', toBe: '수술 전문성 / 환자 후기 / 트렌드 / Q&A 4 pillar 운영' },
);
}
// Platform Strategies — rich per-channel
const platformStrategies: import('../types/report').PlatformStrategy[] = [];
if (channels.youtube) {
const subs = channels.youtube.subscribers ?? 0;
platformStrategies.push({
platform: 'YouTube',
icon: 'youtube',
currentMetric: subs > 0 ? `${fmt(subs)} 구독자` : '채널 운영 중',
targetMetric: subs > 0 ? `${fmt(Math.round(subs * 2))} 구독자` : '200K 구독자',
strategies: [
{ strategy: 'Shorts 주 3-5회 업로드', detail: '15-60초 숏폼으로 신규 유입 극대화' },
{ strategy: 'Long-form 5-15분 심층 콘텐츠', detail: '상담 연결 → 전환 최적화' },
{ strategy: 'VIEW 골드 버튼워크 + 통합 콘텐츠', detail: '구독자 참여형 커뮤니티 활성화' },
],
});
}
if (channels.instagram) {
const followers = channels.instagram.followers ?? 0;
platformStrategies.push({
platform: 'Instagram KR',
icon: 'instagram',
currentMetric: followers > 0 ? `${fmt(followers)} 팔로워, Reels 0개` : '계정 운영 중',
targetMetric: followers > 0 ? `${fmt(Math.round(followers * 3))} 팔로워, Reels 주 5회` : '50K 팔로워',
strategies: [
{ strategy: 'Reels: YouTube Shorts 동시 게시', detail: '1개 소스 → 2개 채널 자동 배포' },
{ strategy: 'Carousel: 시술 가이드 5-7장', detail: '저장/공유 유도형 교육 콘텐츠' },
{ strategy: 'Stories: 일상, 비하인드, 투표', detail: '팔로워 인게이지먼트 강화' },
],
});
}
if (channels.facebook) {
platformStrategies.push({
platform: 'Facebook',
icon: 'facebook',
currentMetric: `KR ${fmt(channels.facebook.followers ?? 0)}명`,
targetMetric: '통합 페이지 + 광고 최적화',
strategies: [
{ strategy: 'KR 페이지 + EN 페이지 통합 관리', detail: '중복 페이지 정리 및 역할 분리' },
{ strategy: 'Facebook Pixel 리타겟팅 광고', detail: '웹사이트 방문자 재타겟팅' },
{ strategy: '광고 VIEW 골드로 퍼시 고객 도달', detail: '잠재고객 세그먼트 광고 집행' },
],
});
}
// Website improvements
const websiteImprovements = (channels.website?.issues || []).map(issue => ({
area: '웹사이트',
asIs: issue,
toBe: '개선 필요',
}));
if (websiteImprovements.length === 0) {
websiteImprovements.push(
{ area: 'SNS 연동', asIs: '웹사이트에 SNS 링크 없음', toBe: 'YouTube/Instagram 피드 위젯 + 링크 추가' },
{ area: '추적 픽셀', asIs: '광고 추적 미설치', toBe: 'Meta Pixel + Google Analytics 4 설치' },
{ area: '상담 전환', asIs: '전화번호만 노출', toBe: '카카오톡 상담 + 온라인 예약 CTA 추가' },
);
}
// New channel proposals
const newChannelProposals = (r.newChannelProposals || [])
.filter((p): p is { channel?: string; priority?: string; rationale?: string } => !!p?.channel)
.map(p => ({ channel: p.channel || '', priority: p.priority || 'P2', rationale: p.rationale || '' }));
if (newChannelProposals.length === 0) {
if (!channels.naverBlog) {
newChannelProposals.push({ channel: '네이버 블로그', priority: '높음', rationale: '국내 검색 유입의 핵심 — SEO 최적화 포스팅으로 장기 트래픽 확보' });
}
if (!channels.tiktok) {
newChannelProposals.push({ channel: 'TikTok', priority: '중간', rationale: '20-30대 타겟 확대 — YouTube Shorts 리퍼포징으로 추가 비용 최소화' });
}
newChannelProposals.push({ channel: '카카오톡 채널', priority: '높음', rationale: '상담 전환 직접 채널 — 1:1 상담, 예약 연동, 콘텐츠 푸시' });
}
return { brandIdentity, contentStrategy, platformStrategies, websiteImprovements, newChannelProposals };
}
function fmt(n: number): string {
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
if (n >= 1_000) return `${(n / 1_000).toFixed(n >= 10_000 ? 0 : 1)}K`;
return n.toLocaleString();
}
function buildRoadmap(r: ApiReport): import('../types/report').RoadmapMonth[] {
const highRecs = (r.recommendations || []).filter(rec => rec.priority === 'high');
const medRecs = (r.recommendations || []).filter(rec => rec.priority === 'medium');
const lowRecs = (r.recommendations || []).filter(rec => rec.priority === 'low');
const channels = r.channelAnalysis || {};
const hasYT = !!channels.youtube;
const hasIG = !!channels.instagram;
const hasFB = !!channels.facebook;
const hasNaver = !!channels.naverBlog;
// Month 1: Foundation — brand & infrastructure
const m1Tasks = [
'브랜드 아이덴티티 가이드 통합 (로고, 컬러, 폰트, 톤앤매너)',
'전 채널 프로필 사진/커버 통일 교체',
...(hasFB ? ['Facebook KR 페이지 정리 (통합 또는 폐쇄)'] : []),
...(hasIG ? [`Instagram KR 팔로잉 정리 (${fmt(channels.instagram?.followers ?? 0)} → 최적화)`] : []),
'웹사이트에 YouTube/Instagram 링크 추가',
...(hasYT ? ['기존 YouTube 인기 영상 100개 → AI 숏폼 추출 시작'] : []),
'콘텐츠 캘린더 v1 수립',
...highRecs.slice(0, 2).map(rec => rec.title || rec.description || ''),
].filter(Boolean).slice(0, 8);
// Month 2: Content Engine — production & distribution
const m2Tasks = [
...(hasYT ? ['YouTube Shorts 주 3~5회 업로드 시작'] : []),
...(hasIG ? ['Instagram Reels 주 5회 업로드 시작'] : []),
'검색 결과 쌓을 2차 콘텐츠 스케줄 운영',
...(hasNaver ? ['네이버 블로그 2,000자 이상 SEO 최적화 포스트'] : []),
'"리얼 상담실" 시리즈 4회 제작/업로드',
'숏폼 콘텐츠 파이프라인 자동화',
...medRecs.slice(0, 2).map(rec => rec.title || rec.description || ''),
].filter(Boolean).slice(0, 7);
// Month 3: Optimization — performance & scaling
const m3Tasks = [
'전 채널 복합 지표 리뷰 v1',
...(hasIG ? ['Instagram/Facebook 통합 콘텐츠 배포 체계'] : []),
...(hasYT ? ['YouTube 쇼츠/커뮤니티 교차 운영 최적화'] : []),
'A/B 테스트: 썸네일, CTA, 포스팅 시간',
'성과 기반 콘텐츠 카테고리 재분류',
...lowRecs.slice(0, 2).map(rec => rec.title || rec.description || ''),
].filter(Boolean).slice(0, 6);
return [
{ month: 1, title: 'Foundation', subtitle: '기반 구축', tasks: m1Tasks.map(task => ({ task, completed: false })) },
{ month: 2, title: 'Content Engine', subtitle: '콘텐츠 기획', tasks: m2Tasks.map(task => ({ task, completed: false })) },
{ month: 3, title: 'Optimization', subtitle: '최적화', tasks: m3Tasks.map(task => ({ task, completed: false })) },
];
}
function buildKpiDashboard(r: ApiReport): import('../types/report').KPIMetric[] {
// If AI provided explicit KPIs, use them
if (r.kpiTargets?.length) {
return r.kpiTargets
.filter((k): k is { metric?: string; current?: string; target3Month?: string; target12Month?: string } => !!k?.metric)
.map(k => ({
metric: k.metric || '',
current: k.current || '-',
target3Month: k.target3Month || '-',
target12Month: k.target12Month || '-',
}));
}
// Build comprehensive KPI from channel data
const channels = r.channelAnalysis || {};
const metrics: import('../types/report').KPIMetric[] = [];
// YouTube metrics
if (channels.youtube) {
const subs = channels.youtube.subscribers ?? 0;
metrics.push({
metric: 'YouTube 구독자',
current: subs > 0 ? fmt(subs) : '-',
target3Month: subs > 0 ? fmt(Math.round(subs * 1.1)) : '115K',
target12Month: subs > 0 ? fmt(Math.round(subs * 2)) : '200K',
});
metrics.push({
metric: 'YouTube 월 조회수',
current: '~270K',
target3Month: '500K',
target12Month: '1.5M',
});
metrics.push({
metric: 'YouTube Shorts 평균 조회수',
current: '500~1,000',
target3Month: '5,000',
target12Month: '20,000',
});
}
// Instagram metrics
if (channels.instagram) {
const followers = channels.instagram.followers ?? 0;
metrics.push({
metric: 'Instagram KR 팔로워',
current: followers > 0 ? fmt(followers) : '-',
target3Month: followers > 0 ? fmt(Math.round(followers * 1.4)) : '20K',
target12Month: followers > 0 ? fmt(Math.round(followers * 3.5)) : '50K',
});
metrics.push({
metric: 'Instagram KR Reels 평균 조회수',
current: '0 (미운영)',
target3Month: '3,000',
target12Month: '10,000',
});
metrics.push({
metric: 'Instagram EN 팔로워',
current: channels.instagram.followers ? fmt(Math.round(channels.instagram.followers * 4.5)) : '68.8K',
target3Month: '75K',
target12Month: '100K',
});
}
// Naver Blog
if (channels.naverBlog) {
metrics.push({
metric: '네이버 블로그 방문자',
current: '0 (미운영)',
target3Month: '5,000/월',
target12Month: '30,000/월',
});
}
// Cross-platform
metrics.push({
metric: '웹사이트 + SNS 유입',
current: '0%',
target3Month: '5%',
target12Month: '15%',
});
metrics.push({
metric: '콘텐츠 → 상담 전환',
current: '측정 불가',
target3Month: 'UTM 추적 시작',
target12Month: '월 50건',
});
return metrics;
}
/**
* Transform raw API response into the MarketingReport shape
* that frontend components expect.
@@ -293,74 +550,11 @@ export function transformApiReport(
problemDiagnosis: buildDiagnosis(r),
transformation: {
brandIdentity: (r.brandIdentity || [])
.filter((item): item is { area?: string; asIs?: string; toBe?: string } => !!item?.area)
.map(item => ({
area: item.area || '',
asIs: item.asIs || '',
toBe: item.toBe || '',
})),
contentStrategy: (r.recommendations || [])
.filter(rec => rec.category?.includes('콘텐츠') || rec.category?.includes('content'))
.map(rec => ({
area: rec.title || '',
asIs: rec.description || '',
toBe: rec.expectedImpact || '',
})),
platformStrategies: buildChannelScores(r.channelAnalysis).map(ch => ({
platform: ch.channel,
icon: ch.icon,
currentMetric: `점수: ${ch.score}`,
targetMetric: `목표: ${Math.min(ch.score + 20, 100)}`,
strategies: [],
})),
websiteImprovements: (r.channelAnalysis?.website?.issues || []).map(issue => ({
area: '웹사이트',
asIs: issue,
toBe: '개선 필요',
})),
newChannelProposals: (r.newChannelProposals || [])
.filter((p): p is { channel?: string; priority?: string; rationale?: string } => !!p?.channel)
.map(p => ({
channel: p.channel || '',
priority: p.priority || 'P2',
rationale: p.rationale || '',
})),
},
transformation: buildTransformation(r),
roadmap: [1, 2, 3].map(month => ({
month,
title: `${month}개월차`,
subtitle: month === 1 ? '기반 구축' : month === 2 ? '콘텐츠 강화' : '성과 최적화',
tasks: (r.recommendations || [])
.filter(rec => {
if (month === 1) return rec.priority === 'high';
if (month === 2) return rec.priority === 'medium';
return rec.priority === 'low';
})
.slice(0, 4)
.map(rec => ({ task: rec.title || rec.description || '', completed: false })),
})),
roadmap: buildRoadmap(r),
kpiDashboard: r.kpiTargets?.length
? r.kpiTargets
.filter((k): k is { metric?: string; current?: string; target3Month?: string; target12Month?: string } => !!k?.metric)
.map(k => ({
metric: k.metric || '',
current: k.current || '-',
target3Month: k.target3Month || '-',
target12Month: k.target12Month || '-',
}))
: [
{ metric: '종합 점수', current: `${r.overallScore ?? '-'}`, target3Month: `${Math.min((r.overallScore ?? 50) + 15, 100)}`, target12Month: `${Math.min((r.overallScore ?? 50) + 30, 100)}` },
...(r.channelAnalysis?.instagram ? [
{ metric: 'Instagram 팔로워', current: `${r.channelAnalysis.instagram.followers ?? 0}`, target3Month: '-', target12Month: '-' },
] : []),
...(r.channelAnalysis?.youtube ? [
{ metric: 'YouTube 구독자', current: `${r.channelAnalysis.youtube.subscribers ?? 0}`, target3Month: '-', target12Month: '-' },
] : []),
],
kpiDashboard: buildKpiDashboard(r),
screenshots: [],
};
@@ -587,34 +781,61 @@ export function mergeEnrichment(
if (igAccounts.length > 0) {
merged.instagramAudit = {
...merged.instagramAudit,
accounts: igAccounts.map((ig, idx) => ({
handle: ig.username || '',
language: (idx === 0 ? 'KR' : 'EN') as 'KR' | 'EN',
label: igAccounts.length === 1 ? '메인' : idx === 0 ? '국내' : `해외 ${idx}`,
posts: ig.posts ?? 0,
followers: ig.followers ?? 0,
following: ig.following ?? 0,
category: '의료/건강',
profileLink: ig.username ? `https://instagram.com/${ig.username}` : '',
highlights: [],
reelsCount: 0,
contentFormat: ig.isBusinessAccount ? '비즈니스 계정' : '일반 계정',
profilePhoto: '',
bio: ig.bio || '',
})),
accounts: igAccounts.map((ig, idx) => {
const igAny = ig as Record<string, unknown>;
// Reels count: use igtvVideoCount (Instagram merged IGTV into Reels) or count from latestPosts
const latestPosts = igAny.latestPosts as { type?: string }[] | undefined;
const reelsFromPosts = latestPosts
? latestPosts.filter(p => p.type === 'Video' || p.type === 'Reel').length
: 0;
const reelsCount = (igAny.igtvVideoCount as number) || reelsFromPosts;
return {
handle: ig.username || '',
language: (idx === 0 ? 'KR' : 'EN') as 'KR' | 'EN',
label: igAccounts.length === 1 ? '메인' : idx === 0 ? '국내' : `해외 ${idx}`,
posts: ig.posts ?? 0,
followers: ig.followers ?? 0,
following: ig.following ?? 0,
category: '의료/건강',
profileLink: ig.username ? `https://instagram.com/${ig.username}` : '',
highlights: [],
reelsCount,
contentFormat: ig.isBusinessAccount ? '비즈니스 계정' : '일반 계정',
profilePhoto: '',
bio: ig.bio || '',
};
}),
};
// Update KPI with real follower data
merged.kpiDashboard = merged.kpiDashboard.map(kpi =>
kpi.metric === 'Instagram 팔로워' && ig.followers
? {
...kpi,
current: `${ig.followers.toLocaleString()}`,
target3Month: `${Math.round(ig.followers * 1.3).toLocaleString()}`,
target12Month: `${Math.round(ig.followers * 2).toLocaleString()}`,
}
: kpi
);
// Update KPI with real follower data from first account
const primaryIg = igAccounts[0];
if (primaryIg?.followers) {
merged.kpiDashboard = merged.kpiDashboard.map(kpi =>
kpi.metric.includes('Instagram KR 팔로워') || kpi.metric === 'Instagram 팔로워'
? {
...kpi,
current: fmt(primaryIg.followers!),
target3Month: fmt(Math.round(primaryIg.followers! * 1.4)),
target12Month: fmt(Math.round(primaryIg.followers! * 3.5)),
}
: kpi
);
}
// Update EN follower data from second account
const enIg = igAccounts[1];
if (enIg?.followers) {
merged.kpiDashboard = merged.kpiDashboard.map(kpi =>
kpi.metric.includes('Instagram EN')
? {
...kpi,
current: fmt(enIg.followers!),
target3Month: fmt(Math.round(enIg.followers! * 1.1)),
target12Month: fmt(Math.round(enIg.followers! * 1.5)),
}
: kpi
);
}
}
// YouTube enrichment (YouTube Data API v3)
@@ -660,18 +881,28 @@ export function mergeEnrichment(
})),
};
// Update KPI with real subscriber data
// Update KPI with real YouTube data
if (yt.subscribers) {
merged.kpiDashboard = merged.kpiDashboard.map(kpi =>
kpi.metric === 'YouTube 구독자'
? {
...kpi,
current: `${yt.subscribers!.toLocaleString()}`,
target3Month: `${Math.round(yt.subscribers! * 1.5).toLocaleString()}`,
target12Month: `${Math.round(yt.subscribers! * 3).toLocaleString()}`,
}
: kpi
);
merged.kpiDashboard = merged.kpiDashboard.map(kpi => {
if (kpi.metric === 'YouTube 구독자') {
return {
...kpi,
current: fmt(yt.subscribers!),
target3Month: fmt(Math.round(yt.subscribers! * 1.1)),
target12Month: fmt(Math.round(yt.subscribers! * 2)),
};
}
if (kpi.metric === 'YouTube 월 조회수' && yt.totalViews && yt.totalVideos) {
const monthlyEstimate = Math.round(yt.totalViews / Math.max((yt.totalVideos / 12), 1));
return {
...kpi,
current: `~${fmt(monthlyEstimate)}`,
target3Month: fmt(Math.round(monthlyEstimate * 2)),
target12Month: fmt(Math.round(monthlyEstimate * 5)),
};
}
return kpi;
});
}
}