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:
Haewon KamandClaude Sonnet 4.6 committed 2026-04-07 09:33:25 +09:00
1 parent ec991057e6
commit d5f7f24e0a
51 files changed
+5390 -252

No files matched your search

+260 -55
View File
@@ -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
View File
@@ -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();
}
+41 -7
View File
@@ -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,