feat: clinic registry DB + pipeline audit P0 fixes
## Clinic Registry - data/clinic-registry/clinic_registry_working.csv — 91개 병원 채널 마스터 DB - data/clinic-registry/INFINITH_Outbound_List.csv — BD팀 아웃바운드 리스트 (17컬럼) - data/clinic-registry/update_csv.py — 안전 CSV 업데이트 스크립트 (빈 필드만 채움) - data/clinic-registry/extract_place_ids.py — 네이버 플레이스 ID 추출기 - scripts/import-registry.ts — CSV → Supabase clinic_registry 테이블 임포트 - supabase/migrations/20260406_clinic_registry.sql — clinic_registry 테이블 스키마 ## Pipeline P0 Bug Fixes (전수 감사 후) - fix(collect-channel-data): 강남언니 rating 0-10 스케일 오변환 제거 - 기존: rating ≤ 5이면 ×2 → 4.8/10을 9.6/10으로 잘못 변환 - 수정: Firecrawl 프롬프트가 이미 0-10 지시 → rawValue 직접 신뢰 - fix(generate-report): Perplexity 단일 fetch → fetchWithRetry 교체 - maxRetries:2, backoffMs:[5000,15000], timeoutMs:90s - 기존: 타임아웃/429 시 리포트 생성 전체 실패 - 수정: 자동 재시도로 일시적 API 오류 극복 ## Docs - docs/PIPELINE_IMPROVEMENT_PLAN.md — Sprint 0/1/2 완료 표시 + 전수 감사 결과 추가 - docs/REGISTRY_FUNCTIONAL_SPECS.md, DB_SCHEMA_V3.md 외 기획 문서 다수 추가 ## New Components & Features - supabase/functions/generate-content-plan, adjust-strategy — 콘텐츠 플랜/전략 조정 - src/components/plan/EditEntryModal, StrategyAdjustmentSection — 플랜 편집 UI - supabase/functions/_shared/dataQuality, foundingYearExtractor, urlClassifier — 데이터 품질 유틸 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
ec991057e6
commit
d5f7f24e0a
51 files changed
+5390
-252
No files matched your search
@@ -1,3 +1,4 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import {
|
||||
VideoFilled,
|
||||
@@ -6,10 +7,13 @@ import {
|
||||
MegaphoneFilled,
|
||||
} from '../icons/FilledIcons';
|
||||
import { SectionWrapper } from '../report/ui/SectionWrapper';
|
||||
import EditEntryModal from './EditEntryModal';
|
||||
import type { CalendarData, ContentCategory, CalendarEntry } from '../../types/plan';
|
||||
|
||||
interface ContentCalendarProps {
|
||||
data: CalendarData;
|
||||
planId?: string;
|
||||
onEntryUpdate?: (entryId: string, updates: Partial<CalendarEntry>) => void;
|
||||
}
|
||||
|
||||
const contentTypeColors: Record<ContentCategory, { bg: string; text: string; entry: string; border: string; shadow: string }> = {
|
||||
@@ -44,9 +48,118 @@ const channelEmojiMap: Record<string, string> = {
|
||||
video: '▷',
|
||||
};
|
||||
|
||||
const statusDotColors: Record<string, string> = {
|
||||
draft: 'bg-slate-300',
|
||||
approved: 'bg-purple-400',
|
||||
published: 'bg-green-400',
|
||||
};
|
||||
|
||||
const dayHeaders = ['월', '화', '수', '목', '금', '토', '일'];
|
||||
|
||||
export default function ContentCalendar({ data }: ContentCalendarProps) {
|
||||
export default function ContentCalendar({ data, planId, onEntryUpdate }: ContentCalendarProps) {
|
||||
const [weeks, setWeeks] = useState(data.weeks);
|
||||
const [editingEntry, setEditingEntry] = useState<CalendarEntry | null>(null);
|
||||
const [filterType, setFilterType] = useState<ContentCategory | null>(null);
|
||||
const [viewMode, setViewMode] = useState<'weekly' | 'monthly'>('weekly');
|
||||
|
||||
const handleEntryClick = useCallback((entry: CalendarEntry) => {
|
||||
setEditingEntry(entry);
|
||||
}, []);
|
||||
|
||||
const handleSave = useCallback((updated: CalendarEntry) => {
|
||||
setWeeks((prev) =>
|
||||
prev.map((week) => ({
|
||||
...week,
|
||||
entries: week.entries.map((e) =>
|
||||
(e.id && e.id === updated.id) ? updated : e
|
||||
),
|
||||
}))
|
||||
);
|
||||
if (onEntryUpdate && updated.id) {
|
||||
onEntryUpdate(updated.id, updated);
|
||||
}
|
||||
setEditingEntry(null);
|
||||
}, [onEntryUpdate]);
|
||||
|
||||
const handleClose = useCallback(() => {
|
||||
setEditingEntry(null);
|
||||
}, []);
|
||||
|
||||
const toggleFilter = (type: ContentCategory) => {
|
||||
setFilterType((prev) => (prev === type ? null : type));
|
||||
};
|
||||
|
||||
// Monthly view: flatten all weeks into one 7-day grid
|
||||
const renderMonthlyView = () => {
|
||||
const allEntries = weeks.flatMap((w) => w.entries);
|
||||
const filtered = filterType
|
||||
? allEntries.filter((e) => e.contentType === filterType)
|
||||
: allEntries;
|
||||
|
||||
const dayCells: CalendarEntry[][] = Array.from({ length: 7 }, () => []);
|
||||
for (const entry of filtered) {
|
||||
if (entry.dayOfWeek >= 0 && entry.dayOfWeek <= 6) {
|
||||
dayCells[entry.dayOfWeek].push(entry);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-white rounded-2xl p-5 shadow-[3px_4px_12px_rgba(0,0,0,0.06)]">
|
||||
<p className="text-sm font-bold text-[#0A1128] mb-3">월간 종합</p>
|
||||
<div className="grid grid-cols-7 gap-2">
|
||||
{dayHeaders.map((day) => (
|
||||
<div key={day} className="text-xs text-slate-400 uppercase tracking-wide text-center mb-1 font-medium">
|
||||
{day}
|
||||
</div>
|
||||
))}
|
||||
{dayCells.map((entries, dayIdx) => (
|
||||
<div
|
||||
key={dayIdx}
|
||||
className={`min-h-[100px] rounded-xl p-1.5 ${
|
||||
entries.length > 0
|
||||
? 'bg-slate-50/50 border border-slate-100'
|
||||
: 'border border-dashed border-slate-200/60'
|
||||
}`}
|
||||
>
|
||||
{entries.map((entry, entryIdx) => renderEntry(entry, entryIdx))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const renderEntry = (entry: CalendarEntry, entryIdx: number) => {
|
||||
const colors = contentTypeColors[entry.contentType];
|
||||
const Icon = contentTypeIcons[entry.contentType];
|
||||
const channelSymbol = channelEmojiMap[entry.channelIcon] || '·';
|
||||
const statusDot = statusDotColors[entry.status || 'draft'];
|
||||
|
||||
return (
|
||||
<div
|
||||
key={entry.id || entryIdx}
|
||||
className={`${colors.entry} border rounded-lg p-1.5 mb-1 last:mb-0 cursor-pointer hover:ring-2 hover:ring-purple-200 transition-all group relative`}
|
||||
onClick={() => handleEntryClick(entry)}
|
||||
>
|
||||
<div className="flex items-center gap-1 mb-0.5">
|
||||
<span className={`w-1.5 h-1.5 rounded-full ${statusDot} flex-shrink-0`} />
|
||||
<span className={`text-[9px] font-bold ${colors.text} leading-none`}>
|
||||
{channelSymbol}
|
||||
</span>
|
||||
<Icon size={10} className={colors.text} />
|
||||
</div>
|
||||
<p className="text-[11px] text-slate-700 leading-tight line-clamp-2">
|
||||
{entry.title}
|
||||
</p>
|
||||
{entry.description && (
|
||||
<p className="text-[9px] text-slate-400 leading-tight mt-0.5 line-clamp-1 hidden group-hover:block">
|
||||
{entry.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<SectionWrapper
|
||||
id="content-calendar"
|
||||
@@ -54,18 +167,57 @@ export default function ContentCalendar({ data }: ContentCalendarProps) {
|
||||
subtitle="콘텐츠 캘린더 (월간)"
|
||||
dark
|
||||
>
|
||||
{/* Toolbar: View Toggle + Filters */}
|
||||
<div className="flex items-center justify-between mb-4 flex-wrap gap-2" data-no-print>
|
||||
{/* View toggle */}
|
||||
<div className="flex bg-slate-100 rounded-xl p-0.5">
|
||||
<button
|
||||
onClick={() => setViewMode('weekly')}
|
||||
className={`px-3 py-1.5 text-xs font-medium rounded-lg transition-all ${
|
||||
viewMode === 'weekly'
|
||||
? 'bg-white text-[#0A1128] shadow-sm'
|
||||
: 'text-slate-500 hover:text-slate-700'
|
||||
}`}
|
||||
>
|
||||
주간
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setViewMode('monthly')}
|
||||
className={`px-3 py-1.5 text-xs font-medium rounded-lg transition-all ${
|
||||
viewMode === 'monthly'
|
||||
? 'bg-white text-[#0A1128] shadow-sm'
|
||||
: 'text-slate-500 hover:text-slate-700'
|
||||
}`}
|
||||
>
|
||||
월간
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Status legend */}
|
||||
<div className="flex gap-3 text-[10px] text-slate-400">
|
||||
<span className="flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-slate-300" />초안</span>
|
||||
<span className="flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-purple-400" />승인</span>
|
||||
<span className="flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-green-400" />게시됨</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Monthly Summary */}
|
||||
<div className="flex flex-wrap gap-4 mb-8">
|
||||
{data.monthlySummary.map((item) => {
|
||||
const colors = contentTypeColors[item.type];
|
||||
const isActive = filterType === item.type;
|
||||
return (
|
||||
<motion.div
|
||||
key={item.type}
|
||||
className={`flex-1 min-w-[140px] rounded-2xl border p-4 ${colors.bg} ${colors.border} ${colors.shadow}`}
|
||||
className={`flex-1 min-w-[140px] rounded-2xl border p-4 cursor-pointer transition-all ${colors.bg} ${colors.border} ${colors.shadow} ${
|
||||
isActive ? 'ring-2 ring-purple-400 ring-offset-1' : ''
|
||||
} ${filterType && !isActive ? 'opacity-40' : ''}`}
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
whileInView={{ opacity: 1, y: 0 }}
|
||||
viewport={{ once: true }}
|
||||
transition={{ duration: 0.3 }}
|
||||
onClick={() => toggleFilter(item.type)}
|
||||
data-no-print={undefined}
|
||||
>
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<span
|
||||
@@ -80,91 +232,95 @@ export default function ContentCalendar({ data }: ContentCalendarProps) {
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Weekly Calendar Grid */}
|
||||
{data.weeks.map((week, weekIdx) => {
|
||||
const dayCells: CalendarEntry[][] = Array.from({ length: 7 }, () => []);
|
||||
for (const entry of week.entries) {
|
||||
const dayIndex = entry.dayOfWeek;
|
||||
if (dayIndex >= 0 && dayIndex <= 6) {
|
||||
dayCells[dayIndex].push(entry);
|
||||
{/* Calendar Content */}
|
||||
{viewMode === 'monthly' ? (
|
||||
renderMonthlyView()
|
||||
) : (
|
||||
/* Weekly Calendar Grid */
|
||||
weeks.map((week, weekIdx) => {
|
||||
const dayCells: CalendarEntry[][] = Array.from({ length: 7 }, () => []);
|
||||
for (const entry of week.entries) {
|
||||
if (filterType && entry.contentType !== filterType) continue;
|
||||
const dayIndex = entry.dayOfWeek;
|
||||
if (dayIndex >= 0 && dayIndex <= 6) {
|
||||
dayCells[dayIndex].push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
key={week.weekNumber}
|
||||
className="bg-white rounded-2xl p-5 mb-4 shadow-[3px_4px_12px_rgba(0,0,0,0.06)]"
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
whileInView={{ opacity: 1, y: 0 }}
|
||||
viewport={{ once: true }}
|
||||
transition={{ duration: 0.4, delay: weekIdx * 0.1 }}
|
||||
>
|
||||
{/* Week header with theme */}
|
||||
<p className="text-sm font-bold text-[#0A1128] mb-3">{week.label}</p>
|
||||
return (
|
||||
<motion.div
|
||||
key={week.weekNumber}
|
||||
className="bg-white rounded-2xl p-5 mb-4 shadow-[3px_4px_12px_rgba(0,0,0,0.06)]"
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
whileInView={{ opacity: 1, y: 0 }}
|
||||
viewport={{ once: true }}
|
||||
transition={{ duration: 0.4, delay: weekIdx * 0.1 }}
|
||||
>
|
||||
<p className="text-sm font-bold text-[#0A1128] mb-3">{week.label}</p>
|
||||
|
||||
<div className="grid grid-cols-7 gap-2">
|
||||
{/* Day headers */}
|
||||
{dayHeaders.map((day) => (
|
||||
<div
|
||||
key={day}
|
||||
className="text-xs text-slate-400 uppercase tracking-wide text-center mb-1 font-medium"
|
||||
>
|
||||
{day}
|
||||
</div>
|
||||
))}
|
||||
<div className="grid grid-cols-7 gap-2">
|
||||
{dayHeaders.map((day) => (
|
||||
<div
|
||||
key={day}
|
||||
className="text-xs text-slate-400 uppercase tracking-wide text-center mb-1 font-medium"
|
||||
>
|
||||
{day}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Day cells */}
|
||||
{dayCells.map((entries, dayIdx) => (
|
||||
<div
|
||||
key={dayIdx}
|
||||
className={`min-h-[80px] rounded-xl p-1.5 ${
|
||||
entries.length > 0
|
||||
? 'bg-slate-50/50 border border-slate-100'
|
||||
: 'border border-dashed border-slate-200/60'
|
||||
}`}
|
||||
>
|
||||
{entries.map((entry, entryIdx) => {
|
||||
const colors = contentTypeColors[entry.contentType];
|
||||
const Icon = contentTypeIcons[entry.contentType];
|
||||
const channelSymbol = channelEmojiMap[entry.channelIcon] || '·';
|
||||
return (
|
||||
<div
|
||||
key={entryIdx}
|
||||
className={`${colors.entry} border rounded-lg p-1.5 mb-1 last:mb-0`}
|
||||
>
|
||||
<div className="flex items-center gap-1 mb-0.5">
|
||||
<span className={`text-[9px] font-bold ${colors.text} leading-none`}>
|
||||
{channelSymbol}
|
||||
</span>
|
||||
<Icon size={10} className={colors.text} />
|
||||
</div>
|
||||
<p className="text-[11px] text-slate-700 leading-tight line-clamp-2">
|
||||
{entry.title}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
{dayCells.map((entries, dayIdx) => (
|
||||
<div
|
||||
key={dayIdx}
|
||||
className={`min-h-[80px] rounded-xl p-1.5 ${
|
||||
entries.length > 0
|
||||
? 'bg-slate-50/50 border border-slate-100'
|
||||
: 'border border-dashed border-slate-200/60'
|
||||
}`}
|
||||
>
|
||||
{entries.map((entry, entryIdx) => renderEntry(entry, entryIdx))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
|
||||
{/* Color Legend */}
|
||||
{/* Color Legend (clickable filter) */}
|
||||
<div className="flex flex-wrap gap-3 mt-4">
|
||||
{(Object.keys(contentTypeColors) as ContentCategory[]).map((type) => {
|
||||
const colors = contentTypeColors[type];
|
||||
const isActive = filterType === type;
|
||||
return (
|
||||
<span
|
||||
<button
|
||||
key={type}
|
||||
className={`${colors.bg} ${colors.text} border ${colors.border} rounded-full px-3 py-1 text-xs font-medium ${colors.shadow}`}
|
||||
onClick={() => toggleFilter(type)}
|
||||
className={`${colors.bg} ${colors.text} border ${colors.border} rounded-full px-3 py-1 text-xs font-medium ${colors.shadow} transition-all ${
|
||||
isActive ? 'ring-2 ring-purple-300' : ''
|
||||
} ${filterType && !isActive ? 'opacity-40' : ''}`}
|
||||
>
|
||||
{contentTypeLabels[type]}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{filterType && (
|
||||
<button
|
||||
onClick={() => setFilterType(null)}
|
||||
className="text-xs text-slate-400 hover:text-slate-600 px-2 py-1 transition-colors"
|
||||
>
|
||||
필터 해제
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Edit Modal */}
|
||||
{editingEntry && (
|
||||
<EditEntryModal
|
||||
entry={editingEntry}
|
||||
onSave={handleSave}
|
||||
onClose={handleClose}
|
||||
/>
|
||||
)}
|
||||
</SectionWrapper>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { motion, AnimatePresence } from 'motion/react';
|
||||
import type { CalendarEntry, ContentCategory } from '../../types/plan';
|
||||
|
||||
interface EditEntryModalProps {
|
||||
entry: CalendarEntry | null;
|
||||
onSave: (updated: CalendarEntry) => void;
|
||||
onClose: () => void;
|
||||
onRegenerate?: (entry: CalendarEntry) => void;
|
||||
}
|
||||
|
||||
const CHANNELS = [
|
||||
{ id: 'YouTube', icon: 'youtube' },
|
||||
{ id: 'Instagram', icon: 'instagram' },
|
||||
{ id: '네이버 블로그', icon: 'blog' },
|
||||
{ id: 'Facebook', icon: 'facebook' },
|
||||
{ id: 'TikTok', icon: 'video' },
|
||||
];
|
||||
|
||||
const CONTENT_TYPES: { value: ContentCategory; label: string }[] = [
|
||||
{ value: 'video', label: '영상' },
|
||||
{ value: 'blog', label: '블로그' },
|
||||
{ value: 'social', label: '소셜' },
|
||||
{ value: 'ad', label: '광고' },
|
||||
];
|
||||
|
||||
const DAYS = ['월', '화', '수', '목', '금', '토', '일'];
|
||||
|
||||
const STATUS_OPTIONS: { value: CalendarEntry['status']; label: string; color: string }[] = [
|
||||
{ value: 'draft', label: '초안', color: 'bg-slate-200 text-slate-600' },
|
||||
{ value: 'approved', label: '승인', color: 'bg-purple-100 text-purple-700' },
|
||||
{ value: 'published', label: '게시됨', color: 'bg-green-100 text-green-700' },
|
||||
];
|
||||
|
||||
export default function EditEntryModal({ entry, onSave, onClose, onRegenerate }: EditEntryModalProps) {
|
||||
const [title, setTitle] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [channel, setChannel] = useState('YouTube');
|
||||
const [channelIcon, setChannelIcon] = useState('youtube');
|
||||
const [contentType, setContentType] = useState<ContentCategory>('video');
|
||||
const [dayOfWeek, setDayOfWeek] = useState(0);
|
||||
const [status, setStatus] = useState<CalendarEntry['status']>('draft');
|
||||
|
||||
useEffect(() => {
|
||||
if (!entry) return;
|
||||
setTitle(entry.title || '');
|
||||
setDescription(entry.description || '');
|
||||
setChannel(entry.channel || 'YouTube');
|
||||
setChannelIcon(entry.channelIcon || 'youtube');
|
||||
setContentType(entry.contentType || 'video');
|
||||
setDayOfWeek(entry.dayOfWeek);
|
||||
setStatus(entry.status || 'draft');
|
||||
}, [entry]);
|
||||
|
||||
if (!entry) return null;
|
||||
|
||||
const handleChannelChange = (channelId: string) => {
|
||||
const ch = CHANNELS.find((c) => c.id === channelId);
|
||||
if (ch) {
|
||||
setChannel(ch.id);
|
||||
setChannelIcon(ch.icon);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
onSave({
|
||||
...entry,
|
||||
title,
|
||||
description,
|
||||
channel,
|
||||
channelIcon,
|
||||
contentType,
|
||||
dayOfWeek,
|
||||
status,
|
||||
isManualEdit: true,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
|
||||
{/* Backdrop */}
|
||||
<motion.div
|
||||
className="absolute inset-0 bg-black/40 backdrop-blur-sm"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
onClick={onClose}
|
||||
/>
|
||||
|
||||
{/* Modal */}
|
||||
<motion.div
|
||||
className="relative w-full max-w-lg bg-white rounded-2xl shadow-xl overflow-hidden"
|
||||
initial={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
exit={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-6 py-4 border-b border-slate-100">
|
||||
<h3 className="text-lg font-bold text-[#0A1128]">콘텐츠 편집</h3>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-slate-400 hover:text-slate-600 transition-colors"
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
<div className="px-6 py-5 space-y-4 max-h-[60vh] overflow-y-auto">
|
||||
{/* Title */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-600 mb-1">제목</label>
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-purple-200 focus:border-purple-400 outline-none transition-all"
|
||||
placeholder="콘텐츠 제목을 입력하세요"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-600 mb-1">제작 가이드</label>
|
||||
<textarea
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
rows={3}
|
||||
className="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-purple-200 focus:border-purple-400 outline-none transition-all resize-none"
|
||||
placeholder="AI가 생성한 제작 가이드 또는 직접 메모를 입력하세요"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Channel + Content Type Row */}
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-600 mb-1">채널</label>
|
||||
<select
|
||||
value={channel}
|
||||
onChange={(e) => handleChannelChange(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-purple-200 focus:border-purple-400 outline-none bg-white"
|
||||
>
|
||||
{CHANNELS.map((ch) => (
|
||||
<option key={ch.id} value={ch.id}>{ch.id}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-600 mb-1">유형</label>
|
||||
<select
|
||||
value={contentType}
|
||||
onChange={(e) => setContentType(e.target.value as ContentCategory)}
|
||||
className="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-purple-200 focus:border-purple-400 outline-none bg-white"
|
||||
>
|
||||
{CONTENT_TYPES.map((ct) => (
|
||||
<option key={ct.value} value={ct.value}>{ct.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Day + Status Row */}
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-600 mb-1">요일</label>
|
||||
<select
|
||||
value={dayOfWeek}
|
||||
onChange={(e) => setDayOfWeek(Number(e.target.value))}
|
||||
className="w-full px-3 py-2 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-purple-200 focus:border-purple-400 outline-none bg-white"
|
||||
>
|
||||
{DAYS.map((d, i) => (
|
||||
<option key={i} value={i}>{d}요일</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-slate-600 mb-1">상태</label>
|
||||
<div className="flex gap-2">
|
||||
{STATUS_OPTIONS.map((s) => (
|
||||
<button
|
||||
key={s.value}
|
||||
onClick={() => setStatus(s.value)}
|
||||
className={`px-3 py-2 rounded-xl text-xs font-medium transition-all ${
|
||||
status === s.value
|
||||
? `${s.color} ring-2 ring-offset-1 ring-purple-300`
|
||||
: 'bg-slate-50 text-slate-400 hover:bg-slate-100'
|
||||
}`}
|
||||
>
|
||||
{s.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="flex items-center justify-between px-6 py-4 border-t border-slate-100 bg-slate-50/50">
|
||||
{onRegenerate ? (
|
||||
<button
|
||||
onClick={() => onRegenerate(entry)}
|
||||
className="flex items-center gap-1.5 px-3 py-2 text-sm text-purple-600 hover:bg-purple-50 rounded-xl transition-colors"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
|
||||
</svg>
|
||||
AI 재생성
|
||||
</button>
|
||||
) : (
|
||||
<div />
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-sm text-slate-500 hover:text-slate-700 transition-colors"
|
||||
>
|
||||
취소
|
||||
</button>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
className="px-5 py-2 text-sm font-medium text-white bg-[#6C5CE7] hover:bg-[#5A4BD6] rounded-xl transition-colors shadow-sm"
|
||||
>
|
||||
저장
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
</AnimatePresence>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { SectionWrapper } from '../report/ui/SectionWrapper';
|
||||
import { supabase, triggerStrategyAdjustment } from '../../lib/supabase';
|
||||
|
||||
interface StrategyAdjustmentSectionProps {
|
||||
clinicId: string | null;
|
||||
planId?: string;
|
||||
}
|
||||
|
||||
interface KpiProgress {
|
||||
metric: string;
|
||||
current: string;
|
||||
target: string;
|
||||
progress: number;
|
||||
}
|
||||
|
||||
interface StrategySuggestion {
|
||||
adjustmentType: string;
|
||||
channel: string;
|
||||
description: string;
|
||||
reason: string;
|
||||
priority: 'high' | 'medium' | 'low';
|
||||
beforeValue: string;
|
||||
afterValue: string;
|
||||
}
|
||||
|
||||
interface AdjustmentHistoryItem {
|
||||
id: string;
|
||||
adjustment_type: string;
|
||||
description: string;
|
||||
reason: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
const priorityColors: Record<string, { bg: string; text: string; dot: string }> = {
|
||||
high: { bg: 'bg-red-50', text: 'text-red-700', dot: 'bg-red-400' },
|
||||
medium: { bg: 'bg-amber-50', text: 'text-amber-700', dot: 'bg-amber-400' },
|
||||
low: { bg: 'bg-blue-50', text: 'text-blue-700', dot: 'bg-blue-400' },
|
||||
};
|
||||
|
||||
const typeLabels: Record<string, string> = {
|
||||
frequency_change: '게시 빈도 조정',
|
||||
pillar_shift: '콘텐츠 필러 전환',
|
||||
channel_add: '채널 추가',
|
||||
channel_pause: '채널 일시 중지',
|
||||
content_format_change: '포맷 변경',
|
||||
tone_shift: '톤 조정',
|
||||
other: '기타 조정',
|
||||
};
|
||||
|
||||
export default function StrategyAdjustmentSection({ clinicId, planId }: StrategyAdjustmentSectionProps) {
|
||||
const [kpiProgress, setKpiProgress] = useState<KpiProgress[]>([]);
|
||||
const [suggestions, setSuggestions] = useState<StrategySuggestion[]>([]);
|
||||
const [history, setHistory] = useState<AdjustmentHistoryItem[]>([]);
|
||||
const [overallAssessment, setOverallAssessment] = useState<string>('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isRunning, setIsRunning] = useState(false);
|
||||
const [hasData, setHasData] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!clinicId) return;
|
||||
loadExistingData();
|
||||
}, [clinicId]);
|
||||
|
||||
async function loadExistingData() {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
// Load latest performance metrics
|
||||
const { data: perf } = await supabase
|
||||
.from('performance_metrics')
|
||||
.select('kpi_progress, strategy_suggestions')
|
||||
.eq('clinic_id', clinicId!)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(1)
|
||||
.single();
|
||||
|
||||
if (perf) {
|
||||
setKpiProgress((perf.kpi_progress as KpiProgress[]) || []);
|
||||
setSuggestions((perf.strategy_suggestions as StrategySuggestion[]) || []);
|
||||
setHasData(true);
|
||||
}
|
||||
|
||||
// Load adjustment history
|
||||
const { data: adj } = await supabase
|
||||
.from('strategy_adjustments')
|
||||
.select('id, adjustment_type, description, reason, created_at')
|
||||
.eq('clinic_id', clinicId!)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(10);
|
||||
|
||||
if (adj) setHistory(adj);
|
||||
} catch {
|
||||
// No data yet — show empty state
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRunAdjustment() {
|
||||
if (!clinicId || isRunning) return;
|
||||
setIsRunning(true);
|
||||
try {
|
||||
const result = await triggerStrategyAdjustment(clinicId);
|
||||
if (result.success) {
|
||||
setKpiProgress(result.kpiProgress || []);
|
||||
setSuggestions(result.adjustments?.strategySuggestions || []);
|
||||
setOverallAssessment(result.adjustments?.overallAssessment || '');
|
||||
setHasData(true);
|
||||
await loadExistingData(); // Refresh history
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Strategy adjustment failed:', err);
|
||||
} finally {
|
||||
setIsRunning(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<SectionWrapper id="strategy-adjustment" title="Strategy Adjustment" subtitle="전략 조정" dark>
|
||||
<div className="flex justify-center py-12">
|
||||
<div className="w-6 h-6 border-2 border-purple-300 border-t-purple-600 rounded-full animate-spin" />
|
||||
</div>
|
||||
</SectionWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SectionWrapper id="strategy-adjustment" title="Strategy Adjustment" subtitle="성과 기반 전략 조정" dark>
|
||||
{/* Action Button */}
|
||||
<div className="flex items-center justify-between mb-6" data-no-print>
|
||||
<p className="text-sm text-slate-500">
|
||||
채널 성과 데이터를 분석하여 콘텐츠 전략을 자동 조정합니다
|
||||
</p>
|
||||
<button
|
||||
onClick={handleRunAdjustment}
|
||||
disabled={isRunning}
|
||||
className={`flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-medium transition-all ${
|
||||
isRunning
|
||||
? 'bg-slate-100 text-slate-400 cursor-not-allowed'
|
||||
: 'bg-[#6C5CE7] text-white hover:bg-[#5A4BD6] shadow-sm'
|
||||
}`}
|
||||
>
|
||||
{isRunning ? (
|
||||
<>
|
||||
<div className="w-4 h-4 border-2 border-slate-300 border-t-slate-500 rounded-full animate-spin" />
|
||||
분석 중...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
|
||||
</svg>
|
||||
전략 조정 실행
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{!hasData ? (
|
||||
/* Empty state */
|
||||
<div className="text-center py-12 bg-white rounded-2xl border border-dashed border-slate-200">
|
||||
<div className="text-3xl mb-3">📊</div>
|
||||
<p className="text-sm font-medium text-slate-600 mb-1">아직 성과 데이터가 없습니다</p>
|
||||
<p className="text-xs text-slate-400">
|
||||
채널 분석을 2회 이상 실행하면 성과 비교 및 전략 조정이 가능합니다
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Overall Assessment */}
|
||||
{overallAssessment && (
|
||||
<motion.div
|
||||
className="bg-purple-50 border border-purple-100 rounded-2xl p-4 mb-6"
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
>
|
||||
<p className="text-sm text-purple-800">{overallAssessment}</p>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* KPI Progress */}
|
||||
{kpiProgress.length > 0 && (
|
||||
<div className="mb-8">
|
||||
<h4 className="text-sm font-bold text-[#0A1128] mb-3">KPI 달성률</h4>
|
||||
<div className="space-y-3">
|
||||
{kpiProgress.map((kpi, i) => (
|
||||
<motion.div
|
||||
key={i}
|
||||
className="bg-white rounded-xl p-4 border border-slate-100"
|
||||
initial={{ opacity: 0, x: -10 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
transition={{ delay: i * 0.05 }}
|
||||
>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="text-xs font-medium text-slate-600">{kpi.metric}</span>
|
||||
<span className={`text-xs font-bold ${
|
||||
kpi.progress >= 100 ? 'text-green-600' :
|
||||
kpi.progress >= 70 ? 'text-amber-600' : 'text-red-600'
|
||||
}`}>
|
||||
{kpi.progress}%
|
||||
</span>
|
||||
</div>
|
||||
<div className="w-full h-2 bg-slate-100 rounded-full overflow-hidden">
|
||||
<motion.div
|
||||
className={`h-full rounded-full ${
|
||||
kpi.progress >= 100 ? 'bg-green-400' :
|
||||
kpi.progress >= 70 ? 'bg-amber-400' : 'bg-red-400'
|
||||
}`}
|
||||
initial={{ width: 0 }}
|
||||
animate={{ width: `${Math.min(kpi.progress, 100)}%` }}
|
||||
transition={{ duration: 0.8, delay: i * 0.1 }}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-between mt-1.5 text-[10px] text-slate-400">
|
||||
<span>현재: {kpi.current}</span>
|
||||
<span>목표: {kpi.target}</span>
|
||||
</div>
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Strategy Suggestions */}
|
||||
{suggestions.length > 0 && (
|
||||
<div className="mb-8">
|
||||
<h4 className="text-sm font-bold text-[#0A1128] mb-3">전략 조정 제안</h4>
|
||||
<div className="space-y-3">
|
||||
{suggestions.map((s, i) => {
|
||||
const colors = priorityColors[s.priority] || priorityColors.medium;
|
||||
return (
|
||||
<motion.div
|
||||
key={i}
|
||||
className={`${colors.bg} rounded-xl p-4 border border-slate-100`}
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: i * 0.08 }}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<span className={`w-2 h-2 rounded-full ${colors.dot} mt-1.5 flex-shrink-0`} />
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className={`text-xs font-bold ${colors.text}`}>
|
||||
{typeLabels[s.adjustmentType] || s.adjustmentType}
|
||||
</span>
|
||||
{s.channel && (
|
||||
<span className="text-[10px] text-slate-400 bg-white px-2 py-0.5 rounded-full">
|
||||
{s.channel}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-slate-700 mb-1">{s.description}</p>
|
||||
<p className="text-xs text-slate-500">{s.reason}</p>
|
||||
{s.beforeValue && s.afterValue && (
|
||||
<div className="flex items-center gap-2 mt-2 text-xs">
|
||||
<span className="text-slate-400 line-through">{s.beforeValue}</span>
|
||||
<span className="text-slate-400">→</span>
|
||||
<span className={`font-medium ${colors.text}`}>{s.afterValue}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Adjustment History */}
|
||||
{history.length > 0 && (
|
||||
<div>
|
||||
<h4 className="text-sm font-bold text-[#0A1128] mb-3">조정 이력</h4>
|
||||
<div className="relative border-l-2 border-slate-200 ml-2 pl-4 space-y-4">
|
||||
{history.map((item) => (
|
||||
<div key={item.id} className="relative">
|
||||
<div className="absolute -left-[21px] top-1 w-2.5 h-2.5 rounded-full bg-purple-300 border-2 border-white" />
|
||||
<div className="bg-white rounded-xl p-3 border border-slate-100">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className="text-xs font-medium text-purple-600">
|
||||
{typeLabels[item.adjustment_type] || item.adjustment_type}
|
||||
</span>
|
||||
<span className="text-[10px] text-slate-400">
|
||||
{new Date(item.created_at).toLocaleDateString('ko-KR')}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-xs text-slate-600">{item.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</SectionWrapper>
|
||||
);
|
||||
}
|
||||
+124
-26
@@ -1,7 +1,7 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useLocation } from 'react-router';
|
||||
import type { MarketingPlan } from '../types/plan';
|
||||
import { fetchReportById } from '../lib/supabase';
|
||||
import type { MarketingPlan, ChannelStrategyCard, CalendarData, ContentStrategyData } from '../types/plan';
|
||||
import { fetchReportById, fetchActiveContentPlan, supabase } from '../lib/supabase';
|
||||
import { transformReportToPlan } from '../lib/transformPlan';
|
||||
|
||||
interface UseMarketingPlanResult {
|
||||
@@ -14,6 +14,60 @@ interface LocationState {
|
||||
report?: Record<string, unknown>;
|
||||
metadata?: Record<string, unknown>;
|
||||
reportId?: string;
|
||||
clinicId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a MarketingPlan from content_plans DB row.
|
||||
* content_plans stores AI-generated strategy in JSONB columns.
|
||||
*/
|
||||
function buildPlanFromContentPlans(
|
||||
row: Record<string, unknown>,
|
||||
clinicName: string,
|
||||
clinicNameEn: string,
|
||||
targetUrl: string,
|
||||
): MarketingPlan {
|
||||
const channelStrategies = (row.channel_strategies || []) as ChannelStrategyCard[];
|
||||
const contentStrategy = (row.content_strategy || {}) as ContentStrategyData;
|
||||
const calendar = (row.calendar || { weeks: [], monthlySummary: [] }) as CalendarData;
|
||||
|
||||
return {
|
||||
id: row.id as string,
|
||||
reportId: (row.run_id as string) || (row.id as string),
|
||||
clinicName,
|
||||
clinicNameEn,
|
||||
createdAt: (row.created_at as string) || new Date().toISOString(),
|
||||
targetUrl,
|
||||
brandGuide: (row.brand_guide as MarketingPlan['brandGuide']) || {
|
||||
colors: [],
|
||||
fonts: [],
|
||||
logoRules: [],
|
||||
toneOfVoice: {
|
||||
personality: ['전문적', '친근한', '신뢰할 수 있는'],
|
||||
communicationStyle: '의료 전문 지식을 쉽고 친근하게 전달',
|
||||
doExamples: [],
|
||||
dontExamples: [],
|
||||
},
|
||||
channelBranding: [],
|
||||
brandInconsistencies: [],
|
||||
},
|
||||
channelStrategies,
|
||||
contentStrategy: {
|
||||
pillars: contentStrategy.pillars || [],
|
||||
typeMatrix: contentStrategy.typeMatrix || [],
|
||||
workflow: contentStrategy.workflow || [
|
||||
{ step: 1, name: '기획', description: 'AI 콘텐츠 주제 선정', owner: 'INFINITH AI', duration: '자동' },
|
||||
{ step: 2, name: '제작', description: 'AI 초안 생성 + 의료진 감수', owner: 'INFINITH AI', duration: '1시간' },
|
||||
{ step: 3, name: '편집', description: '영상/이미지 편집', owner: 'INFINITH Studio', duration: '30분' },
|
||||
{ step: 4, name: '배포', description: '채널별 최적화 배포', owner: 'INFINITH Distribution', duration: '자동' },
|
||||
{ step: 5, name: '분석', description: '성과 데이터 수집 + 전략 조정', owner: 'INFINITH Analytics', duration: '자동' },
|
||||
],
|
||||
repurposingSource: contentStrategy.repurposingSource || '1개 롱폼 영상',
|
||||
repurposingOutputs: contentStrategy.repurposingOutputs || [],
|
||||
},
|
||||
calendar,
|
||||
assetCollection: { assets: [], youtubeRepurpose: [] },
|
||||
};
|
||||
}
|
||||
|
||||
export function useMarketingPlan(id: string | undefined): UseMarketingPlanResult {
|
||||
@@ -31,35 +85,79 @@ export function useMarketingPlan(id: string | undefined): UseMarketingPlanResult
|
||||
|
||||
const state = location.state as LocationState | undefined;
|
||||
|
||||
// Source 1: Report data passed via navigation state
|
||||
if (state?.report && state?.metadata) {
|
||||
async function loadPlan() {
|
||||
try {
|
||||
const plan = transformReportToPlan({
|
||||
id: (state.reportId || id),
|
||||
url: (state.metadata.url as string) || '',
|
||||
clinic_name: (state.metadata.clinicName as string) || '',
|
||||
report: state.report,
|
||||
created_at: (state.metadata.generatedAt as string) || new Date().toISOString(),
|
||||
});
|
||||
setData(plan);
|
||||
setIsLoading(false);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to build marketing plan');
|
||||
setIsLoading(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// ─── Source 1: Try content_plans table (AI-generated strategy) ───
|
||||
// First, resolve clinicId from navigation state or analysis_runs
|
||||
let clinicId = state?.clinicId || null;
|
||||
let clinicName = '';
|
||||
let clinicNameEn = '';
|
||||
let targetUrl = '';
|
||||
|
||||
// Source 2: Fetch report from Supabase and transform to plan
|
||||
fetchReportById(id)
|
||||
.then((row) => {
|
||||
if (!clinicId) {
|
||||
// Try to find clinicId from analysis_runs by run/report ID
|
||||
const { data: run } = await supabase
|
||||
.from('analysis_runs')
|
||||
.select('clinic_id')
|
||||
.eq('id', id)
|
||||
.single();
|
||||
if (run) clinicId = run.clinic_id;
|
||||
}
|
||||
|
||||
if (clinicId) {
|
||||
// Fetch clinic info for plan metadata
|
||||
const { data: clinic } = await supabase
|
||||
.from('clinics')
|
||||
.select('name, name_en, url')
|
||||
.eq('id', clinicId)
|
||||
.single();
|
||||
if (clinic) {
|
||||
clinicName = clinic.name || '';
|
||||
clinicNameEn = clinic.name_en || '';
|
||||
targetUrl = clinic.url || '';
|
||||
}
|
||||
|
||||
// Try fetching active content plan
|
||||
const contentPlan = await fetchActiveContentPlan(clinicId);
|
||||
if (contentPlan) {
|
||||
const plan = buildPlanFromContentPlans(
|
||||
contentPlan,
|
||||
clinicName,
|
||||
clinicNameEn,
|
||||
targetUrl,
|
||||
);
|
||||
setData(plan);
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Source 2: Report data from navigation state (fallback) ───
|
||||
if (state?.report && state?.metadata) {
|
||||
const plan = transformReportToPlan({
|
||||
id: (state.reportId || id),
|
||||
url: (state.metadata.url as string) || '',
|
||||
clinic_name: (state.metadata.clinicName as string) || '',
|
||||
report: state.report,
|
||||
created_at: (state.metadata.generatedAt as string) || new Date().toISOString(),
|
||||
});
|
||||
setData(plan);
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// ─── Source 3: Fetch report from Supabase and transform (fallback) ───
|
||||
const row = await fetchReportById(id);
|
||||
const plan = transformReportToPlan(row);
|
||||
setData(plan);
|
||||
})
|
||||
.catch((err) => {
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to fetch marketing plan');
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
loadPlan();
|
||||
}, [id, location.state]);
|
||||
|
||||
return { data, isLoading, error };
|
||||
|
||||
+260
-55
@@ -1,9 +1,18 @@
|
||||
/**
|
||||
* Content Director Engine
|
||||
* Content Director Engine v2
|
||||
*
|
||||
* Deterministic content planning agent that generates a 4-week editorial
|
||||
* calendar by combining channel strategies, content pillars, clinic services,
|
||||
* and existing assets. No AI API calls — all logic is data-driven.
|
||||
*
|
||||
* v2 changes (Audit-driven):
|
||||
* - Added 강남언니, TikTok, YouTube Live/Community slots
|
||||
* - Added Instagram Feed slot, Naver column format
|
||||
* - Split Facebook into organic/ad
|
||||
* - 5th Pillar: 안전·케어
|
||||
* - Customer journey-based week themes
|
||||
* - Channel-specific tone matrix
|
||||
* - Keyword-driven topic generation
|
||||
*/
|
||||
|
||||
import type {
|
||||
@@ -23,6 +32,8 @@ export interface ContentDirectorInput {
|
||||
services: string[];
|
||||
youtubeVideos?: { title: string; views: number; type: 'Short' | 'Long' }[];
|
||||
clinicName: string;
|
||||
keywords?: { keyword: string; monthlySearches?: number }[];
|
||||
gangnamUnniData?: { rating?: number; reviews?: number; doctors?: number };
|
||||
}
|
||||
|
||||
export interface ContentDirectorOutput {
|
||||
@@ -35,70 +46,165 @@ export interface ContentDirectorOutput {
|
||||
interface FormatSlot {
|
||||
channel: string;
|
||||
channelIcon: string;
|
||||
format: string; // e.g. "Shorts", "Carousel", "블로그"
|
||||
format: string;
|
||||
contentType: ContentCategory;
|
||||
preferredDays: number[]; // 0=월 ~ 6=일
|
||||
perWeek: number; // how many per week
|
||||
perWeek: number;
|
||||
titleTemplate: (topic: string, idx: number) => string;
|
||||
tone: string;
|
||||
journeyStage: 'awareness' | 'interest' | 'consideration' | 'conversion' | 'loyalty';
|
||||
}
|
||||
|
||||
// ─── YouTube: 4 formats ───
|
||||
const YOUTUBE_SLOTS: FormatSlot[] = [
|
||||
{
|
||||
channel: 'YouTube', channelIcon: 'youtube', format: 'Shorts',
|
||||
contentType: 'video', preferredDays: [0, 2, 4], perWeek: 3,
|
||||
titleTemplate: (t, i) => `Shorts: ${t} #${i + 1}`,
|
||||
tone: '캐주얼·후킹', journeyStage: 'awareness',
|
||||
},
|
||||
{
|
||||
channel: 'YouTube', channelIcon: 'youtube', format: 'Long-form',
|
||||
contentType: 'video', preferredDays: [3], perWeek: 1,
|
||||
titleTemplate: (t) => `${t} 상세 설명`,
|
||||
tone: '교육적·권위', journeyStage: 'interest',
|
||||
},
|
||||
{
|
||||
channel: 'YouTube', channelIcon: 'youtube', format: 'Live Q&A',
|
||||
contentType: 'video', preferredDays: [5], perWeek: 1,
|
||||
titleTemplate: (t) => `Live: ${t} 실시간 Q&A`,
|
||||
tone: '친근·대화', journeyStage: 'consideration',
|
||||
},
|
||||
{
|
||||
channel: 'YouTube', channelIcon: 'youtube', format: 'Community',
|
||||
contentType: 'social', preferredDays: [1, 4], perWeek: 2,
|
||||
titleTemplate: (t) => `[커뮤니티] ${t} 투표/질문`,
|
||||
tone: '친근·참여유도', journeyStage: 'loyalty',
|
||||
},
|
||||
];
|
||||
|
||||
// ─── Instagram: 4 formats ───
|
||||
const INSTAGRAM_SLOTS: FormatSlot[] = [
|
||||
{
|
||||
channel: 'Instagram', channelIcon: 'instagram', format: 'Reel',
|
||||
contentType: 'video', preferredDays: [0, 2, 4], perWeek: 3,
|
||||
titleTemplate: (t, i) => `Reel: ${t} #${i + 1}`,
|
||||
tone: '트렌디·공감', journeyStage: 'awareness',
|
||||
},
|
||||
{
|
||||
channel: 'Instagram', channelIcon: 'instagram', format: 'Carousel',
|
||||
contentType: 'social', preferredDays: [1, 4], perWeek: 2,
|
||||
titleTemplate: (t) => `Carousel: ${t}`,
|
||||
tone: '정보성·교육', journeyStage: 'interest',
|
||||
},
|
||||
{
|
||||
channel: 'Instagram', channelIcon: 'instagram', format: 'Feed',
|
||||
contentType: 'social', preferredDays: [3], perWeek: 1,
|
||||
titleTemplate: (t) => `Feed: ${t} 포트폴리오`,
|
||||
tone: '감성적·프리미엄', journeyStage: 'consideration',
|
||||
},
|
||||
{
|
||||
channel: 'Instagram', channelIcon: 'instagram', format: 'Stories',
|
||||
contentType: 'social', preferredDays: [2, 5], perWeek: 2,
|
||||
titleTemplate: (t) => `Stories: ${t}`,
|
||||
tone: '친근·일상', journeyStage: 'loyalty',
|
||||
},
|
||||
];
|
||||
|
||||
// ─── 강남언니: 3 formats (Audit C1) ───
|
||||
const GANGNAMUNNI_SLOTS: FormatSlot[] = [
|
||||
{
|
||||
channel: '강남언니', channelIcon: 'star', format: '리뷰관리',
|
||||
contentType: 'social', preferredDays: [1, 4], perWeek: 2,
|
||||
titleTemplate: (t) => `리뷰 응대: ${t}`,
|
||||
tone: '전문·응대', journeyStage: 'consideration',
|
||||
},
|
||||
{
|
||||
channel: '강남언니', channelIcon: 'star', format: '프로필최적화',
|
||||
contentType: 'social', preferredDays: [0], perWeek: 1,
|
||||
titleTemplate: (t) => `프로필 업데이트: ${t}`,
|
||||
tone: '전문·신뢰', journeyStage: 'consideration',
|
||||
},
|
||||
{
|
||||
channel: '강남언니', channelIcon: 'star', format: '이벤트/가격',
|
||||
contentType: 'ad', preferredDays: [3], perWeek: 1,
|
||||
titleTemplate: (t) => `이벤트: ${t}`,
|
||||
tone: '프로모션·CTA', journeyStage: 'conversion',
|
||||
},
|
||||
];
|
||||
|
||||
// ─── TikTok: 1 format (Audit C2) ───
|
||||
const TIKTOK_SLOTS: FormatSlot[] = [
|
||||
{
|
||||
channel: 'TikTok', channelIcon: 'video', format: '숏폼',
|
||||
contentType: 'video', preferredDays: [0, 2, 4], perWeek: 3,
|
||||
titleTemplate: (t, i) => `TikTok: ${t} #${i + 1}`,
|
||||
tone: '밈·교육', journeyStage: 'awareness',
|
||||
},
|
||||
];
|
||||
|
||||
// ─── 네이버 블로그: 2 formats (Audit H3) ───
|
||||
const NAVER_SLOTS: FormatSlot[] = [
|
||||
{
|
||||
channel: '네이버 블로그', channelIcon: 'blog', format: '블로그',
|
||||
channel: '네이버 블로그', channelIcon: 'blog', format: 'SEO글',
|
||||
contentType: 'blog', preferredDays: [1, 3], perWeek: 2,
|
||||
titleTemplate: (t) => `${t}`,
|
||||
tone: '정보성·SEO', journeyStage: 'interest',
|
||||
},
|
||||
{
|
||||
channel: '네이버 블로그', channelIcon: 'blog', format: '의사칼럼',
|
||||
contentType: 'blog', preferredDays: [5], perWeek: 1,
|
||||
titleTemplate: (t) => `[칼럼] ${t}`,
|
||||
tone: '전문·교육', journeyStage: 'consideration',
|
||||
},
|
||||
];
|
||||
|
||||
// ─── Facebook: organic + ad (Audit H4) ───
|
||||
const FACEBOOK_SLOTS: FormatSlot[] = [
|
||||
{
|
||||
channel: 'Facebook', channelIcon: 'facebook', format: '오가닉',
|
||||
contentType: 'social', preferredDays: [2], perWeek: 1,
|
||||
titleTemplate: (t) => `${t}`,
|
||||
tone: '커뮤니티·공유', journeyStage: 'interest',
|
||||
},
|
||||
{
|
||||
channel: 'Facebook', channelIcon: 'facebook', format: '광고',
|
||||
contentType: 'ad', preferredDays: [5], perWeek: 1,
|
||||
contentType: 'ad', preferredDays: [4, 6], perWeek: 2,
|
||||
titleTemplate: (t) => `광고: ${t}`,
|
||||
tone: '타겟팅·CTA', journeyStage: 'conversion',
|
||||
},
|
||||
];
|
||||
|
||||
// ─── Week Themes ───
|
||||
// ─── Customer Journey-Based Week Themes (Audit C4) ───
|
||||
|
||||
const WEEK_THEMES = [
|
||||
{ label: 'Week 1: 브랜드 정비 & 첫 콘텐츠', pillarFocus: 0 }, // 전문성·신뢰
|
||||
{ label: 'Week 2: 콘텐츠 엔진 가동', pillarFocus: 1 }, // 비포·애프터
|
||||
{ label: 'Week 3: 소셜 증거 강화', pillarFocus: 2 }, // 환자 후기
|
||||
{ label: 'Week 4: 전환 최적화', pillarFocus: 3 }, // 트렌드·교육
|
||||
{
|
||||
label: 'Week 1: 인지 확대 & 브랜드 정비',
|
||||
pillarFocus: 0, // 전문성·신뢰
|
||||
journeyFocus: 'awareness' as const,
|
||||
description: '신규 유입 극대화 — YouTube Shorts, TikTok, Instagram Reels 집중',
|
||||
},
|
||||
{
|
||||
label: 'Week 2: 관심 유도 & 교육 콘텐츠',
|
||||
pillarFocus: 1, // 비포·애프터
|
||||
journeyFocus: 'interest' as const,
|
||||
description: '정보 탐색 — Long-form, 블로그 SEO, Carousel 집중',
|
||||
},
|
||||
{
|
||||
label: 'Week 3: 신뢰 구축 & 소셜 증거',
|
||||
pillarFocus: 2, // 환자 후기
|
||||
journeyFocus: 'consideration' as const,
|
||||
description: '비교 검토 — 강남언니 리뷰, Before/After, 의사 소개 집중',
|
||||
},
|
||||
{
|
||||
label: 'Week 4: 전환 최적화 & CTA',
|
||||
pillarFocus: 3, // 트렌드·교육
|
||||
journeyFocus: 'conversion' as const,
|
||||
description: '상담 예약 유도 — Facebook 광고, Instagram DM CTA, 프로모션',
|
||||
},
|
||||
];
|
||||
|
||||
// ─── Topic Generation ───
|
||||
// ─── Topic Generation (with keyword injection — Audit C5) ───
|
||||
|
||||
interface TopicPool {
|
||||
topics: string[];
|
||||
@@ -109,46 +215,71 @@ function buildTopicPool(
|
||||
pillars: ContentPillar[],
|
||||
services: string[],
|
||||
pillarIndex: number,
|
||||
keywords?: { keyword: string; monthlySearches?: number }[],
|
||||
): TopicPool {
|
||||
const pillar = pillars[pillarIndex % pillars.length];
|
||||
const svcList = services.length > 0 ? services : ['시술'];
|
||||
|
||||
const topics: string[] = [];
|
||||
|
||||
// Inject high-volume keywords as topics (Audit C5)
|
||||
if (keywords?.length) {
|
||||
const topKeywords = keywords
|
||||
.sort((a, b) => (b.monthlySearches || 0) - (a.monthlySearches || 0))
|
||||
.slice(0, 5)
|
||||
.map(k => k.keyword);
|
||||
for (const kw of topKeywords) {
|
||||
topics.push(kw);
|
||||
}
|
||||
}
|
||||
|
||||
// Pillar-specific templates
|
||||
switch (pillarIndex % 4) {
|
||||
switch (pillarIndex % 5) {
|
||||
case 0: // 전문성·신뢰
|
||||
for (const svc of svcList) {
|
||||
topics.push(`${svc} 전문의 Q&A`);
|
||||
topics.push(`${svc} 과정 완전정복`);
|
||||
topics.push(`${svc} 수술실 CCTV 공개`);
|
||||
}
|
||||
topics.push('의료진 학회 발표·해외 연수');
|
||||
topics.push('최신 장비 도입 소개');
|
||||
topics.push('마취 안전 관리 시스템');
|
||||
topics.push('회복 관리 시스템');
|
||||
break;
|
||||
case 1: // 비포·애프터
|
||||
for (const svc of svcList) {
|
||||
topics.push(`${svc} 전후 비교`);
|
||||
topics.push(`${svc} Before/After`);
|
||||
topics.push(`${svc} Before/After 타임랩스`);
|
||||
topics.push(`${svc} 3D 시뮬레이션 미리보기`);
|
||||
}
|
||||
topics.push('자연스러운 포 라인');
|
||||
topics.push('내 얼굴에 가장 예쁜 코');
|
||||
topics.push('자연스러운 라인 완성');
|
||||
topics.push('시간별 회복 과정 기록');
|
||||
break;
|
||||
case 2: // 환자 후기
|
||||
for (const svc of svcList) {
|
||||
topics.push(`${svc} 실제 후기`);
|
||||
topics.push(`${svc} 실제 환자 인터뷰`);
|
||||
topics.push(`${svc} 회복 일기`);
|
||||
}
|
||||
topics.push('환자가 설명하는: 왜 선택?');
|
||||
topics.push('리뷰 하이라이트');
|
||||
topics.push('해외 환자 케이스');
|
||||
topics.push('환자가 말하는: 왜 여기를 선택했나');
|
||||
topics.push('리뷰 하이라이트 모음');
|
||||
break;
|
||||
case 3: // 트렌드·교육
|
||||
for (const svc of svcList) {
|
||||
topics.push(`${svc} 비용 가이드`);
|
||||
topics.push(`${svc} FAQ`);
|
||||
topics.push(`${svc} 비용 완벽 가이드`);
|
||||
topics.push(`${svc} FAQ 총정리`);
|
||||
}
|
||||
topics.push('성형 가이드: 내 얼굴 뭐 할래');
|
||||
topics.push('트렌드 분석: 자연주의 성형');
|
||||
topics.push('2026 성형 트렌드: 자연주의');
|
||||
topics.push('성형 전 필수 체크리스트');
|
||||
topics.push('시술 비교: 이걸로 고민 끝');
|
||||
break;
|
||||
case 4: // 안전·케어 (5th Pillar — Audit H5)
|
||||
for (const svc of svcList) {
|
||||
topics.push(`${svc} 수술 후 관리 가이드`);
|
||||
}
|
||||
topics.push('24시간 집중 케어 시스템');
|
||||
topics.push('전담 간호사 1:1 관리');
|
||||
topics.push('리커버리 프로그램 소개');
|
||||
topics.push('응급 상황 대응 프로토콜');
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -178,10 +309,46 @@ function buildRepurposeTopics(
|
||||
.filter(t => t.length > 2);
|
||||
}
|
||||
|
||||
// ─── 강남언니 Special Topics ───
|
||||
|
||||
function buildGangnamUnniTopics(
|
||||
services: string[],
|
||||
data?: { rating?: number; reviews?: number; doctors?: number },
|
||||
): string[] {
|
||||
const topics: string[] = [];
|
||||
const svcList = services.length > 0 ? services : ['시술'];
|
||||
|
||||
// Review management topics
|
||||
topics.push('신규 리뷰 감사 응대');
|
||||
topics.push('부정 리뷰 전문 응대');
|
||||
|
||||
// Profile optimization
|
||||
for (const svc of svcList.slice(0, 3)) {
|
||||
topics.push(`${svc} 시술 정보 업데이트`);
|
||||
}
|
||||
topics.push('의사 프로필 사진·경력 갱신');
|
||||
topics.push('대표 시술 가격 재검토');
|
||||
|
||||
// Data-driven topics
|
||||
if (data?.rating && data.rating < 9.0) {
|
||||
topics.push('평점 개선 액션 플랜');
|
||||
}
|
||||
if (data?.reviews && data.reviews < 500) {
|
||||
topics.push('리뷰 수 증가 캠페인');
|
||||
}
|
||||
|
||||
// Events
|
||||
for (const svc of svcList.slice(0, 2)) {
|
||||
topics.push(`${svc} 시즌 이벤트`);
|
||||
}
|
||||
|
||||
return topics;
|
||||
}
|
||||
|
||||
// ─── Main Engine ───
|
||||
|
||||
export function generateContentPlan(input: ContentDirectorInput): ContentDirectorOutput {
|
||||
const { channels, pillars, services, youtubeVideos, clinicName } = input;
|
||||
const { channels, pillars, services, youtubeVideos, clinicName, keywords, gangnamUnniData } = input;
|
||||
|
||||
// 1. Determine active format slots based on available channels
|
||||
const activeSlots: FormatSlot[] = [];
|
||||
@@ -189,55 +356,71 @@ export function generateContentPlan(input: ContentDirectorInput): ContentDirecto
|
||||
|
||||
if (channelIds.has('youtube')) activeSlots.push(...YOUTUBE_SLOTS);
|
||||
if (channelIds.has('instagram')) activeSlots.push(...INSTAGRAM_SLOTS);
|
||||
if (channelIds.has('gangnamunni') || channelIds.has('gangnamUnni')) activeSlots.push(...GANGNAMUNNI_SLOTS);
|
||||
if (channelIds.has('tiktok')) activeSlots.push(...TIKTOK_SLOTS);
|
||||
if (channelIds.has('naverblog') || channelIds.has('naver_blog')) activeSlots.push(...NAVER_SLOTS);
|
||||
if (channelIds.has('facebook')) activeSlots.push(...FACEBOOK_SLOTS);
|
||||
|
||||
// Fallback: if no channels matched, use YouTube + Instagram as defaults
|
||||
// Fallback: if no channels matched, use core 3 channels
|
||||
if (activeSlots.length === 0) {
|
||||
activeSlots.push(...YOUTUBE_SLOTS, ...INSTAGRAM_SLOTS);
|
||||
activeSlots.push(...YOUTUBE_SLOTS, ...INSTAGRAM_SLOTS, ...NAVER_SLOTS);
|
||||
}
|
||||
|
||||
// 2. Build repurpose topics from existing YouTube videos
|
||||
const repurposeTopics = youtubeVideos ? buildRepurposeTopics(youtubeVideos) : [];
|
||||
|
||||
// 3. Generate 4 weeks of content
|
||||
// 3. Build 강남언니 special topic pool
|
||||
const guTopics = buildGangnamUnniTopics(services, gangnamUnniData);
|
||||
let guCursor = 0;
|
||||
|
||||
// 4. Generate 4 weeks of content
|
||||
const weeks: CalendarWeek[] = [];
|
||||
|
||||
for (let weekIdx = 0; weekIdx < 4; weekIdx++) {
|
||||
const theme = WEEK_THEMES[weekIdx];
|
||||
|
||||
// Build topic pool focused on this week's pillar, with secondary pillars mixed in
|
||||
const primaryPool = buildTopicPool(pillars, services, theme.pillarFocus);
|
||||
const secondaryPool = buildTopicPool(pillars, services, (theme.pillarFocus + 1) % 4);
|
||||
// Build topic pools focused on this week's pillar + 5th pillar rotation
|
||||
const primaryPool = buildTopicPool(pillars, services, theme.pillarFocus, keywords);
|
||||
const secondaryPool = buildTopicPool(pillars, services, (theme.pillarFocus + 1) % 5, keywords);
|
||||
// 5th pillar (안전·케어) injected every other week
|
||||
const carePool = weekIdx % 2 === 1
|
||||
? buildTopicPool(pillars, services, 4, keywords)
|
||||
: null;
|
||||
|
||||
const entries: CalendarEntry[] = [];
|
||||
|
||||
// Week 1 special: add brand setup tasks
|
||||
// Week 1 special: brand setup tasks
|
||||
if (weekIdx === 0) {
|
||||
entries.push({
|
||||
dayOfWeek: 0, // 월
|
||||
dayOfWeek: 0,
|
||||
channel: clinicName,
|
||||
channelIcon: 'globe',
|
||||
contentType: 'social',
|
||||
title: `전 채널 프로필/VIEW 골드 정비`,
|
||||
});
|
||||
entries.push({
|
||||
dayOfWeek: 1, // 화
|
||||
channel: 'Instagram',
|
||||
channelIcon: 'instagram',
|
||||
contentType: 'social',
|
||||
title: `프로필 리뉴얼 고지 + 팔로워`,
|
||||
title: '전 채널 프로필/브랜드 일관성 정비',
|
||||
description: '프로필 사진, 배너, 바이오를 모든 채널에서 통일',
|
||||
pillar: '전문성 · 신뢰',
|
||||
status: 'draft',
|
||||
});
|
||||
}
|
||||
|
||||
// Fill format slots for this week
|
||||
for (const slot of activeSlots) {
|
||||
const pool = entries.length % 2 === 0 ? primaryPool : secondaryPool;
|
||||
// Use care pool occasionally
|
||||
const pool = carePool && entries.length % 5 === 0
|
||||
? carePool
|
||||
: entries.length % 2 === 0 ? primaryPool : secondaryPool;
|
||||
|
||||
for (let i = 0; i < slot.perWeek; i++) {
|
||||
// Use repurpose topics for some slots in weeks 2-4
|
||||
let topic: string;
|
||||
if (weekIdx >= 1 && repurposeTopics.length > 0 && i === 0 && slot.format === 'Shorts') {
|
||||
|
||||
// 강남언니: use dedicated topic pool
|
||||
if (slot.channel === '강남언니') {
|
||||
topic = guTopics[guCursor % guTopics.length];
|
||||
guCursor++;
|
||||
}
|
||||
// Repurpose popular YouTube content for Shorts/TikTok in weeks 2-4
|
||||
else if (weekIdx >= 1 && repurposeTopics.length > 0 && i === 0 &&
|
||||
(slot.format === 'Shorts' || slot.format === '숏폼')) {
|
||||
const rIdx = (weekIdx - 1 + i) % repurposeTopics.length;
|
||||
topic = repurposeTopics[rIdx];
|
||||
} else {
|
||||
@@ -252,29 +435,51 @@ export function generateContentPlan(input: ContentDirectorInput): ContentDirecto
|
||||
channelIcon: slot.channelIcon,
|
||||
contentType: slot.contentType,
|
||||
title: slot.titleTemplate(topic, i),
|
||||
pillar: pillars[theme.pillarFocus % pillars.length]?.title,
|
||||
status: 'draft',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Week 4 special: add conversion-focused entries
|
||||
// Week 3 special: 강남언니 리뷰 집중 (소셜 증거 강화)
|
||||
if (weekIdx === 2 && !channelIds.has('gangnamunni') && !channelIds.has('gangnamUnni')) {
|
||||
entries.push({
|
||||
dayOfWeek: 3,
|
||||
channel: '강남언니',
|
||||
channelIcon: 'star',
|
||||
contentType: 'social',
|
||||
title: '강남언니 프로필 개설/최적화',
|
||||
description: '아직 강남언니 계정이 없다면 개설, 있다면 프로필 최적화',
|
||||
pillar: '환자 후기 · 리뷰',
|
||||
status: 'draft',
|
||||
});
|
||||
}
|
||||
|
||||
// Week 4 special: conversion-focused entries
|
||||
if (weekIdx === 3) {
|
||||
entries.push({
|
||||
dayOfWeek: 5, // 토
|
||||
dayOfWeek: 5,
|
||||
channel: 'Instagram',
|
||||
channelIcon: 'instagram',
|
||||
contentType: 'social',
|
||||
title: 'Stories: 상담 예약 CTA + 카카오톡 링크',
|
||||
description: 'DM→카카오톡→전화 전환 퍼널 활성화',
|
||||
pillar: '트렌드 · 교육',
|
||||
status: 'draft',
|
||||
});
|
||||
entries.push({
|
||||
dayOfWeek: 6,
|
||||
channel: 'Facebook',
|
||||
channelIcon: 'facebook',
|
||||
contentType: 'ad',
|
||||
title: `광고: 상담 예약 CTA`,
|
||||
title: '광고: 리타겟팅 — 웹사이트 방문자 재유입',
|
||||
description: '최근 30일 웹사이트 방문자 대상 리타겟팅 광고',
|
||||
pillar: '트렌드 · 교육',
|
||||
status: 'draft',
|
||||
});
|
||||
if (!channelIds.has('facebook')) {
|
||||
// Replace channel for non-Facebook users
|
||||
entries[entries.length - 1].channel = 'Instagram';
|
||||
entries[entries.length - 1].channelIcon = 'instagram';
|
||||
entries[entries.length - 1].contentType = 'social';
|
||||
entries[entries.length - 1].title = '가슴성형 할인 이벤트 피드';
|
||||
}
|
||||
}
|
||||
|
||||
// Sort entries by day of week for clean display
|
||||
// Sort entries by day of week
|
||||
entries.sort((a, b) => a.dayOfWeek - b.dayOfWeek);
|
||||
|
||||
weeks.push({
|
||||
@@ -284,7 +489,7 @@ export function generateContentPlan(input: ContentDirectorInput): ContentDirecto
|
||||
});
|
||||
}
|
||||
|
||||
// 4. Calculate monthly summary
|
||||
// 5. Calculate monthly summary
|
||||
const allEntries = weeks.flatMap(w => w.entries);
|
||||
const monthlySummary: ContentCountSummary[] = [
|
||||
{
|
||||
|
||||
+108
-2
@@ -135,11 +135,16 @@ export async function discoverChannels(url: string, clinicName?: string) {
|
||||
}
|
||||
);
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Channel discovery failed: ${response.statusText}`);
|
||||
const err = new Error(data.error || `Channel discovery failed: ${response.statusText}`);
|
||||
(err as Error & { code?: string; domain?: string }).code = data.error;
|
||||
(err as Error & { code?: string; domain?: string }).domain = data.domain;
|
||||
throw err;
|
||||
}
|
||||
|
||||
return response.json();
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -182,3 +187,104 @@ export async function generateReportV2(reportId: string, clinicId?: string, runI
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// ─── Pipeline V2 Phase 4: Content Plan ───
|
||||
|
||||
/**
|
||||
* Phase 4: Generate AI content strategy and calendar.
|
||||
* Reads report data from DB, calls Perplexity for strategy generation,
|
||||
* stores result in content_plans table.
|
||||
*/
|
||||
export async function generateContentPlan(reportId: string, clinicId?: string, runId?: string) {
|
||||
const response = await fetch(
|
||||
`${supabaseUrl}/functions/v1/generate-content-plan`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: fnHeaders(),
|
||||
body: JSON.stringify({ reportId, clinicId, runId }),
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Content plan generation failed: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the active content plan for a clinic.
|
||||
* Returns the most recent is_active=true plan with all JSONB columns.
|
||||
*/
|
||||
export async function fetchActiveContentPlan(clinicId: string) {
|
||||
const { data, error } = await supabase
|
||||
.from("content_plans")
|
||||
.select("*")
|
||||
.eq("clinic_id", clinicId)
|
||||
.eq("is_active", true)
|
||||
.order("created_at", { ascending: false })
|
||||
.limit(1)
|
||||
.single();
|
||||
|
||||
if (error) return null;
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a single calendar entry within a content plan's JSONB.
|
||||
* Uses Postgres JSONB path update.
|
||||
*/
|
||||
export async function updateCalendarEntry(
|
||||
planId: string,
|
||||
entryId: string,
|
||||
updates: Record<string, unknown>,
|
||||
) {
|
||||
// Read current calendar
|
||||
const { data: plan, error: readErr } = await supabase
|
||||
.from("content_plans")
|
||||
.select("calendar")
|
||||
.eq("id", planId)
|
||||
.single();
|
||||
|
||||
if (readErr || !plan) throw new Error(`Plan not found: ${readErr?.message}`);
|
||||
|
||||
const calendar = plan.calendar as { weeks: { entries: Record<string, unknown>[] }[] };
|
||||
|
||||
// Find and update entry
|
||||
for (const week of calendar.weeks) {
|
||||
for (let i = 0; i < week.entries.length; i++) {
|
||||
if (week.entries[i].id === entryId) {
|
||||
week.entries[i] = { ...week.entries[i], ...updates, isManualEdit: true };
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { error: writeErr } = await supabase
|
||||
.from("content_plans")
|
||||
.update({ calendar })
|
||||
.eq("id", planId);
|
||||
|
||||
if (writeErr) throw new Error(`Update failed: ${writeErr.message}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger strategy adjustment for a clinic.
|
||||
* Compares current vs previous channel_snapshots, generates AI recommendations.
|
||||
*/
|
||||
export async function triggerStrategyAdjustment(clinicId: string) {
|
||||
const response = await fetch(
|
||||
`${supabaseUrl}/functions/v1/adjust-strategy`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: fnHeaders(),
|
||||
body: JSON.stringify({ clinicId }),
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Strategy adjustment failed: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
@@ -38,6 +38,18 @@ const CHANNEL_ICON_MAP: Record<string, string> = {
|
||||
tiktok: 'video',
|
||||
};
|
||||
|
||||
// Channel-specific tone matrix (Audit C3)
|
||||
const CHANNEL_TONE_MAP: Record<string, string> = {
|
||||
youtube: '교육적 · 권위 (Long) / 캐주얼 · 후킹 (Shorts)',
|
||||
instagram: '트렌디 · 공감 (Reel) / 감성적 · 프리미엄 (Feed)',
|
||||
naverBlog: '정보성 · SEO 최적화',
|
||||
gangnamUnni: '전문 · 응대 · 신뢰',
|
||||
facebook: '타겟팅 · CTA 중심',
|
||||
tiktok: '밈 · 교육 · MZ세대',
|
||||
naverPlace: '정보성 · 지역 SEO',
|
||||
website: '브랜드 · 프리미엄',
|
||||
};
|
||||
|
||||
function buildChannelStrategies(
|
||||
channelAnalysis: Record<string, Record<string, unknown>> | undefined,
|
||||
recommendations: Record<string, unknown>[] | undefined,
|
||||
@@ -61,7 +73,7 @@ function buildChannelStrategies(
|
||||
targetGoal: (ch.recommendation as string) || '',
|
||||
contentTypes: relatedRecs.length > 0 ? relatedRecs : ['콘텐츠 전략 수립 필요'],
|
||||
postingFrequency: score >= 80 ? '주 3-5회' : score >= 60 ? '주 2-3회' : '주 1-2회 (시작)',
|
||||
tone: '전문적 · 친근한',
|
||||
tone: CHANNEL_TONE_MAP[key] || '전문적 · 친근한',
|
||||
formatGuidelines: [],
|
||||
priority: (score < 50 ? 'P0' : score < 70 ? 'P1' : 'P2') as 'P0' | 'P1' | 'P2',
|
||||
};
|
||||
@@ -72,36 +84,43 @@ function buildContentPillars(
|
||||
recommendations: Record<string, unknown>[] | undefined,
|
||||
services: string[] | undefined,
|
||||
): ContentPillar[] {
|
||||
const PILLAR_COLORS = ['#6C5CE7', '#E17055', '#00B894', '#FDCB6E'];
|
||||
const PILLAR_COLORS = ['#6C5CE7', '#E17055', '#00B894', '#FDCB6E', '#0984E3'];
|
||||
const pillars: ContentPillar[] = [
|
||||
{
|
||||
title: '전문성 · 신뢰',
|
||||
description: '의료진 소개, 수술 과정, 인증/자격 콘텐츠로 신뢰 구축',
|
||||
description: '의료진 소개, 수술 과정, 인증/자격, 학회 발표, 해외 연수 콘텐츠로 신뢰 구축',
|
||||
relatedUSP: '전문 의료진',
|
||||
exampleTopics: services?.slice(0, 3).map(s => `${s} 시술 과정 소개`) || ['시술 과정 소개'],
|
||||
color: PILLAR_COLORS[0],
|
||||
},
|
||||
{
|
||||
title: '비포 · 애프터',
|
||||
description: '실제 환자 사례, 수술 전후 비교로 결과 시각화',
|
||||
description: '실제 환자 사례, 수술 전후 비교, 3D 시뮬레이션, 시간별 변화 기록으로 결과 시각화',
|
||||
relatedUSP: '검증된 결과',
|
||||
exampleTopics: services?.slice(0, 3).map(s => `${s} 비포/애프터`) || ['비포/애프터 사례'],
|
||||
color: PILLAR_COLORS[1],
|
||||
},
|
||||
{
|
||||
title: '환자 후기 · 리뷰',
|
||||
description: '실제 환자 인터뷰, 후기 콘텐츠로 사회적 증거 확보',
|
||||
description: '실제 환자 인터뷰, 후기 콘텐츠, 강남언니 리뷰 관리로 사회적 증거 확보',
|
||||
relatedUSP: '환자 만족도',
|
||||
exampleTopics: ['환자 인터뷰 영상', '리뷰 하이라이트', '회복 일기'],
|
||||
color: PILLAR_COLORS[2],
|
||||
},
|
||||
{
|
||||
title: '트렌드 · 교육',
|
||||
description: '시술 트렌드, Q&A, 의학 정보로 잠재 고객 유입',
|
||||
description: '시술 트렌드, Q&A, 의학 정보, 비용 가이드로 잠재 고객 유입',
|
||||
relatedUSP: '최신 트렌드',
|
||||
exampleTopics: ['자주 묻는 질문 Q&A', '시술별 비용 가이드', '최신 성형 트렌드'],
|
||||
color: PILLAR_COLORS[3],
|
||||
},
|
||||
{
|
||||
title: '안전 · 케어',
|
||||
description: '수술 후 관리, 24시간 모니터링, 전담 간호사, 리커버리 프로그램으로 프리미엄 케어 차별화',
|
||||
relatedUSP: '프리미엄 안전 관리',
|
||||
exampleTopics: ['수술 후 48시간 집중 케어', '전담 간호사 1:1 관리', '응급 대응 프로토콜'],
|
||||
color: PILLAR_COLORS[4],
|
||||
},
|
||||
];
|
||||
|
||||
return pillars;
|
||||
@@ -118,6 +137,7 @@ function buildCalendar(
|
||||
services: string[],
|
||||
enrichment: EnrichmentData | undefined,
|
||||
clinicName: string,
|
||||
report?: Record<string, unknown>,
|
||||
) {
|
||||
// Extract YouTube top videos for repurposing suggestions
|
||||
const youtubeVideos = enrichment?.youtube?.videos?.map(v => ({
|
||||
@@ -126,12 +146,26 @@ function buildCalendar(
|
||||
type: ((v.duration && parseInt(v.duration) < 60) ? 'Short' : 'Long') as 'Short' | 'Long',
|
||||
}));
|
||||
|
||||
// Extract keywords from report for topic generation (Audit C5)
|
||||
const reportKeywords = report?.keywords as { primary?: { keyword: string; monthlySearches?: number }[] } | undefined;
|
||||
const keywords = reportKeywords?.primary;
|
||||
|
||||
// Extract 강남언니 data for strategy-driven topics (Audit C1)
|
||||
const guData = enrichment?.gangnamUnni as { rating?: number; totalReviews?: number; doctors?: { name: string }[] } | undefined;
|
||||
const gangnamUnniData = guData ? {
|
||||
rating: guData.rating,
|
||||
reviews: guData.totalReviews,
|
||||
doctors: guData.doctors?.length,
|
||||
} : undefined;
|
||||
|
||||
return generateContentPlan({
|
||||
channels,
|
||||
pillars,
|
||||
services,
|
||||
youtubeVideos,
|
||||
clinicName,
|
||||
keywords,
|
||||
gangnamUnniData,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -326,7 +360,7 @@ export function transformReportToPlan(row: RawReportRow): MarketingPlan {
|
||||
const channelStrategies = buildChannelStrategies(channelAnalysis, recommendations);
|
||||
const pillars = buildContentPillars(recommendations, services);
|
||||
const clinicName = (clinicInfo?.name as string) || row.clinic_name || '';
|
||||
const calendar = buildCalendar(channelStrategies, pillars, services, enrichment, clinicName);
|
||||
const calendar = buildCalendar(channelStrategies, pillars, services, enrichment, clinicName, report);
|
||||
|
||||
return {
|
||||
id: row.id,
|
||||
|
||||
@@ -1,20 +1,22 @@
|
||||
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { useNavigate, useLocation, useParams } from 'react-router';
|
||||
import { motion } from 'motion/react';
|
||||
import { Check, AlertCircle, RefreshCw } from 'lucide-react';
|
||||
import { Check, AlertCircle, RefreshCw, ShieldX } from 'lucide-react';
|
||||
import {
|
||||
discoverChannels,
|
||||
collectChannelData,
|
||||
generateReportV2,
|
||||
generateContentPlan,
|
||||
fetchPipelineStatus,
|
||||
} from '../lib/supabase';
|
||||
|
||||
type Phase = 'resuming' | 'discovering' | 'collecting' | 'generating' | 'complete';
|
||||
type Phase = 'resuming' | 'discovering' | 'collecting' | 'generating' | 'planning' | 'complete';
|
||||
|
||||
const PHASE_STEPS = [
|
||||
{ key: 'discovering' as Phase, label: 'Scanning website & discovering channels...', labelDone: 'Channels discovered' },
|
||||
{ key: 'collecting' as Phase, label: 'Collecting channel data & market analysis...', labelDone: 'Data collected' },
|
||||
{ key: 'generating' as Phase, label: 'Generating AI marketing report...', labelDone: 'Report generated' },
|
||||
{ key: 'planning' as Phase, label: 'AI 콘텐츠 전략 생성 중...', labelDone: '콘텐츠 플랜 생성 완료' },
|
||||
{ key: 'complete' as Phase, label: 'Finalizing report...', labelDone: 'Complete' },
|
||||
];
|
||||
|
||||
@@ -49,6 +51,8 @@ function clearSession() {
|
||||
export default function AnalysisLoadingPage() {
|
||||
const [phase, setPhase] = useState<Phase>('discovering');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [errorCode, setErrorCode] = useState<string | null>(null);
|
||||
const [errorDomain, setErrorDomain] = useState<string | null>(null);
|
||||
const [errorDetails, setErrorDetails] = useState<Record<string, string> | null>(null);
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
@@ -99,20 +103,35 @@ export default function AnalysisLoadingPage() {
|
||||
}
|
||||
|
||||
// Phase 3: Generate Report
|
||||
let reportResult: Record<string, unknown> | null = null;
|
||||
if (startPhase === 'generating') {
|
||||
setPhase('generating');
|
||||
const result = await generateReportV2(reportId, clinicId, runId);
|
||||
if (!result.success) throw new Error(result.error || 'Report generation failed');
|
||||
reportResult = result;
|
||||
startPhase = 'planning';
|
||||
}
|
||||
|
||||
// Phase 4: Generate Content Plan (non-blocking — failure doesn't stop pipeline)
|
||||
if (startPhase === 'planning') {
|
||||
setPhase('planning');
|
||||
try {
|
||||
await generateContentPlan(reportId, clinicId, runId);
|
||||
} catch (planErr) {
|
||||
console.warn('[pipeline] Content plan generation failed (non-blocking):', planErr);
|
||||
}
|
||||
|
||||
// Complete — navigate to report
|
||||
setPhase('complete');
|
||||
clearSession();
|
||||
|
||||
// Use stored report result or refetch
|
||||
const result = reportResult || await generateReportV2(reportId, clinicId, runId).catch(() => null);
|
||||
setTimeout(() => {
|
||||
navigate(`/report/${reportId}`, {
|
||||
replace: true,
|
||||
state: result.report && result.metadata
|
||||
? { report: result.report, metadata: result.metadata, reportId }
|
||||
state: result?.report && result?.metadata
|
||||
? { report: result.report, metadata: result.metadata, reportId, clinicId }
|
||||
: undefined,
|
||||
});
|
||||
}, 800);
|
||||
@@ -120,6 +139,12 @@ export default function AnalysisLoadingPage() {
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : 'An error occurred';
|
||||
setError(msg);
|
||||
if (err && typeof err === 'object' && 'code' in err) {
|
||||
setErrorCode((err as { code?: string }).code || null);
|
||||
}
|
||||
if (err && typeof err === 'object' && 'domain' in err) {
|
||||
setErrorDomain((err as { domain?: string }).domain || null);
|
||||
}
|
||||
}
|
||||
}, [navigate]);
|
||||
|
||||
@@ -260,41 +285,64 @@ export default function AnalysisLoadingPage() {
|
||||
)}
|
||||
|
||||
{error ? (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
className="w-full p-6 rounded-2xl bg-red-500/10 border border-red-500/20 text-center"
|
||||
>
|
||||
<AlertCircle className="w-10 h-10 text-red-400 mx-auto mb-3" />
|
||||
<p className="text-red-300 text-sm mb-4">{error}</p>
|
||||
|
||||
{errorDetails && (
|
||||
<div className="mb-4 text-left bg-red-500/5 rounded-lg p-3">
|
||||
<p className="text-red-400/60 text-xs font-mono mb-1">Failed channels:</p>
|
||||
{Object.entries(errorDetails).map(([ch, err]) => (
|
||||
<p key={ch} className="text-red-400/80 text-xs font-mono">
|
||||
• {ch}: {err}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-3 justify-center">
|
||||
<button
|
||||
onClick={handleRetry}
|
||||
className="px-6 py-2 text-sm font-medium text-white bg-purple-600/30 rounded-lg hover:bg-purple-600/50 transition-colors flex items-center gap-2"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
Retry
|
||||
</button>
|
||||
errorCode === 'CLINIC_NOT_REGISTERED' ? (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
className="w-full p-6 rounded-2xl bg-purple-500/10 border border-purple-500/20 text-center"
|
||||
>
|
||||
<ShieldX className="w-10 h-10 text-purple-400 mx-auto mb-3" />
|
||||
<p className="text-white text-lg font-medium mb-2">미등록 병원</p>
|
||||
<p className="text-purple-300/80 text-sm mb-1">
|
||||
<span className="font-mono text-purple-200">{errorDomain}</span>
|
||||
</p>
|
||||
<p className="text-purple-300/60 text-sm mb-6">
|
||||
현재 분석 대상 병원 목록에 포함되지 않은 도메인입니다.
|
||||
</p>
|
||||
<button
|
||||
onClick={() => { clearSession(); navigate('/', { replace: true }); }}
|
||||
className="px-6 py-2 text-sm font-medium text-white bg-white/10 rounded-lg hover:bg-white/20 transition-colors"
|
||||
className="px-6 py-2 text-sm font-medium text-white bg-purple-600/30 rounded-lg hover:bg-purple-600/50 transition-colors"
|
||||
>
|
||||
Start Over
|
||||
돌아가기
|
||||
</button>
|
||||
</div>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
) : (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
className="w-full p-6 rounded-2xl bg-red-500/10 border border-red-500/20 text-center"
|
||||
>
|
||||
<AlertCircle className="w-10 h-10 text-red-400 mx-auto mb-3" />
|
||||
<p className="text-red-300 text-sm mb-4">{error}</p>
|
||||
|
||||
{errorDetails && (
|
||||
<div className="mb-4 text-left bg-red-500/5 rounded-lg p-3">
|
||||
<p className="text-red-400/60 text-xs font-mono mb-1">Failed channels:</p>
|
||||
{Object.entries(errorDetails).map(([ch, err]) => (
|
||||
<p key={ch} className="text-red-400/80 text-xs font-mono">
|
||||
• {ch}: {err}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-3 justify-center">
|
||||
<button
|
||||
onClick={handleRetry}
|
||||
className="px-6 py-2 text-sm font-medium text-white bg-purple-600/30 rounded-lg hover:bg-purple-600/50 transition-colors flex items-center gap-2"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
Retry
|
||||
</button>
|
||||
<button
|
||||
onClick={() => { clearSession(); navigate('/', { replace: true }); }}
|
||||
className="px-6 py-2 text-sm font-medium text-white bg-white/10 rounded-lg hover:bg-white/20 transition-colors"
|
||||
>
|
||||
Start Over
|
||||
</button>
|
||||
</div>
|
||||
</motion.div>
|
||||
)
|
||||
) : (
|
||||
<>
|
||||
{phase === 'resuming' ? (
|
||||
|
||||
@@ -85,7 +85,7 @@ const API_REGISTRY: ApiConfig[] = [
|
||||
{
|
||||
id: 'apify',
|
||||
name: 'Apify',
|
||||
description: 'Instagram/Facebook/Google Places 데이터 수집',
|
||||
description: 'Instagram/Facebook 데이터 수집',
|
||||
envKeys: ['APIFY_API_TOKEN'],
|
||||
layer: 'edge-function',
|
||||
docsUrl: 'https://docs.apify.com',
|
||||
@@ -95,7 +95,22 @@ const API_REGISTRY: ApiConfig[] = [
|
||||
usedInPhases: ['Phase 1: discover', 'Phase 2: collect', 'Enrich'],
|
||||
estimatedCostPerRun: '~$0.10-0.30',
|
||||
rateLimit: 'Actor-dependent (30-120s timeout)',
|
||||
notes: 'IG profile/posts/reels + FB pages + Google Places actors',
|
||||
notes: 'IG profile/posts/reels + FB pages actors',
|
||||
},
|
||||
{
|
||||
id: 'google-places',
|
||||
name: 'Google Places API (New)',
|
||||
description: 'Google Maps 장소 검색, 평점, 리뷰, 연락처 데이터',
|
||||
envKeys: ['GOOGLE_PLACES_API_KEY'],
|
||||
layer: 'edge-function',
|
||||
docsUrl: 'https://developers.google.com/maps/documentation/places/web-service',
|
||||
IconComponent: GlobeFilled,
|
||||
category: 'social',
|
||||
pricingModel: '$200/mo 무료 크레딧 포함',
|
||||
usedInPhases: ['Phase 2: collect', 'Enrich', 'Registry enrichment'],
|
||||
estimatedCostPerRun: '~$0.04',
|
||||
rateLimit: 'No hard limit (pay-as-you-go)',
|
||||
notes: 'Text Search + Place Details (1-2초 응답, Apify 대비 30x 빠름)',
|
||||
},
|
||||
{
|
||||
id: 'youtube',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useParams } from 'react-router';
|
||||
import { useParams, useLocation } from 'react-router';
|
||||
import { useMarketingPlan } from '../hooks/useMarketingPlan';
|
||||
import { ReportNav } from '../components/report/ReportNav';
|
||||
|
||||
@@ -10,6 +10,7 @@ import ContentStrategy from '../components/plan/ContentStrategy';
|
||||
import ContentCalendar from '../components/plan/ContentCalendar';
|
||||
import AssetCollection from '../components/plan/AssetCollection';
|
||||
import MyAssetUpload from '../components/plan/MyAssetUpload';
|
||||
import StrategyAdjustmentSection from '../components/plan/StrategyAdjustmentSection';
|
||||
import PlanCTA from '../components/plan/PlanCTA';
|
||||
|
||||
const PLAN_SECTIONS = [
|
||||
@@ -19,10 +20,13 @@ const PLAN_SECTIONS = [
|
||||
{ id: 'content-calendar', label: '콘텐츠 캘린더' },
|
||||
{ id: 'asset-collection', label: '에셋 수집' },
|
||||
{ id: 'my-asset-upload', label: 'My Assets' },
|
||||
{ id: 'strategy-adjustment', label: '전략 조정' },
|
||||
];
|
||||
|
||||
export default function MarketingPlanPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const location = useLocation();
|
||||
const clinicId = (location.state as { clinicId?: string } | undefined)?.clinicId || null;
|
||||
const { data, isLoading, error } = useMarketingPlan(id);
|
||||
|
||||
if (isLoading) {
|
||||
@@ -75,6 +79,10 @@ export default function MarketingPlanPage() {
|
||||
<MyAssetUpload />
|
||||
</div>
|
||||
|
||||
<div data-no-print>
|
||||
<StrategyAdjustmentSection clinicId={clinicId} planId={data.id} />
|
||||
</div>
|
||||
|
||||
<PlanCTA />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -59,6 +59,7 @@ export interface ChannelStrategyCard {
|
||||
tone: string;
|
||||
formatGuidelines: string[];
|
||||
priority: 'P0' | 'P1' | 'P2';
|
||||
customerJourneyStage?: 'awareness' | 'interest' | 'consideration' | 'conversion' | 'loyalty';
|
||||
}
|
||||
|
||||
// ─── Section 3: Content Marketing Strategy ───
|
||||
@@ -110,6 +111,13 @@ export interface CalendarEntry {
|
||||
channelIcon: string;
|
||||
contentType: ContentCategory;
|
||||
title: string;
|
||||
// AI-generated fields (optional — backward compatible with deterministic engine)
|
||||
id?: string;
|
||||
description?: string;
|
||||
pillar?: string;
|
||||
status?: 'draft' | 'approved' | 'published';
|
||||
isManualEdit?: boolean;
|
||||
aiPromptSeed?: string;
|
||||
}
|
||||
|
||||
export interface CalendarWeek {
|
||||
|
||||
Reference in new issue
Block a user