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

+192
View File
@@ -0,0 +1,192 @@
/**
* Missing Value Guard & Report Quality Validator — Harness 3
*
* Detects all known variants of "no data" from LLM outputs and
* provides a quality score for generated reports.
*
* Usage:
* - isMissingValue(val) → boolean (use everywhere you check for missing data)
* - validateReportQuality(report) → DataQualityReport (use before saving reports)
*/
// ─── Missing Value Detection ───
/**
* All known LLM expressions for "no data available".
* Normalized to lowercase for comparison.
*/
const MISSING_PATTERNS: ReadonlyArray<string> = [
// Korean
"데이터 없음", "데이터없음", "데이터 미확인", "데이터미확인",
"정보없음", "정보 없음", "정보 미제공", "미제공",
"확인불가", "확인 불가", "미확인", "미발견",
"알 수 없음", "알수없음", "해당 없음", "해당없음",
"없음", "미정",
// English
"n/a", "na", "none", "null", "undefined",
"not available", "unknown", "not found", "no data",
// Symbols
"-", "—", "–", ".", "...", "N/A",
];
/**
* Check if a value represents missing/unavailable data.
* Handles null, undefined, empty strings, zero, and LLM "no data" variants.
*/
export function isMissingValue(val: unknown): boolean {
if (val == null) return true;
if (typeof val === "number") return val === 0 || isNaN(val);
const s = String(val).trim().toLowerCase();
if (s === "" || s === "0") return true;
return MISSING_PATTERNS.some((p) => s === p.toLowerCase());
}
/**
* Clean a value: return it if valid, or return the fallback if missing.
* Useful for providing defaults without silent data loss.
*/
export function cleanValue<T>(val: unknown, fallback: T): T | unknown {
return isMissingValue(val) ? fallback : val;
}
// ─── Report Quality Validation ───
export interface DataQualityReport {
score: number; // 0-100
missingCritical: string[]; // Missing critical fields
missingImportant: string[]; // Missing important fields
missingOptional: string[]; // Missing optional fields
warnings: string[]; // Human-readable warnings
}
/** Fields that MUST be present for a valid report */
const CRITICAL_FIELDS = [
"clinicInfo.name",
"clinicInfo.established",
];
/** Fields that significantly impact report quality */
const IMPORTANT_FIELDS = [
"clinicInfo.doctors",
"channelAnalysis.youtube",
"channelAnalysis.instagram",
"channelAnalysis.naverBlog",
"channelAnalysis.gangnamUnni",
];
/** Nice-to-have fields */
const OPTIONAL_FIELDS = [
"channelAnalysis.facebook",
"channelAnalysis.tiktok",
"channelAnalysis.naverPlace",
"channelAnalysis.googleMaps",
"clinicInfo.location",
];
/**
* Validate report data quality and return a score with details.
*
* Scoring:
* - Each critical field missing: -20 points
* - Each important field missing: -5 points
* - Each optional field missing: -2 points
*/
export function validateReportQuality(
report: Record<string, unknown>,
): DataQualityReport {
const result: DataQualityReport = {
score: 100,
missingCritical: [],
missingImportant: [],
missingOptional: [],
warnings: [],
};
// Check critical fields
for (const path of CRITICAL_FIELDS) {
const val = getNestedValue(report, path);
if (isMissingValue(val)) {
result.missingCritical.push(path);
result.score -= 20;
result.warnings.push(`❌ Critical: '${path}' is missing`);
}
}
// Check important fields
for (const path of IMPORTANT_FIELDS) {
const val = getNestedValue(report, path);
if (isMissingValue(val)) {
result.missingImportant.push(path);
result.score -= 5;
result.warnings.push(`⚠️ Important: '${path}' is missing`);
}
}
// Check optional fields
for (const path of OPTIONAL_FIELDS) {
const val = getNestedValue(report, path);
if (isMissingValue(val)) {
result.missingOptional.push(path);
result.score -= 2;
}
}
result.score = Math.max(0, result.score);
return result;
}
// ─── Helpers ───
/**
* Traverse a nested object by dot-separated path.
* e.g., getNestedValue({ a: { b: 1 } }, "a.b") → 1
*/
function getNestedValue(obj: Record<string, unknown>, path: string): unknown {
return path.split(".").reduce(
(current, key) => {
if (current == null || typeof current !== "object") return undefined;
return (current as Record<string, unknown>)[key];
},
obj as unknown,
);
}
// ─── Self-Test ───
const MISSING_VALUE_TEST_CORPUS: ReadonlyArray<readonly [unknown, boolean]> = [
[null, true],
[undefined, true],
["", true],
[" ", true],
[0, true],
["데이터 없음", true],
["데이터없음", true],
["N/A", true],
["n/a", true],
["확인 불가", true],
["미확인", true],
["unknown", true],
["-", true],
["—", true],
["none", true],
// Valid values
["뷰성형외과", false],
[4.5, false],
["2004", false],
[387, false],
["https://example.com", false],
];
export function validateDataQuality(): { pass: boolean; failures: string[] } {
const failures: string[] = [];
for (const [val, expected] of MISSING_VALUE_TEST_CORPUS) {
const result = isMissingValue(val);
if (result !== expected) {
failures.push(`isMissingValue(${JSON.stringify(val)}): expected ${expected}, got ${result}`);
}
}
return { pass: failures.length === 0, failures };
}
@@ -0,0 +1,100 @@
/**
* Founding Year Extraction Guard — Harness 2
*
* Regex-based founding year extraction to complement Gemini Vision.
* Acts as a fallback when the LLM misses patterns like "2004년개원 이래".
*
* Defense layers:
* 1. Gemini Vision (primary)
* 2. This module on scraped text (secondary)
* 3. generate-report post-processing on all channel_data text (tertiary)
*/
// ─── Patterns ───
/**
* Regex patterns for founding year detection.
* Each captures a numeric group that is either:
* - A 4-digit year (1950–currentYear)
* - A 1-2 digit number to subtract from currentYear
*/
const FOUNDING_PATTERNS: RegExp[] = [
// Direct year expressions
/(\d{4})년\s*개원/, // "2004년개원", "2004년 개원"
/(\d{4})년개원\s*이래/, // "2004년개원 이래" ← 그랜드 패턴
/개원\s*(\d{4})년/, // "개원 2004년"
/설립\s*(\d{4})년/, // "설립 2004년"
/(\d{4})년\s*설립/, // "2004년 설립"
/since\s*(\d{4})/i, // "SINCE 2004"
/established\s*(?:in\s*)?(\d{4})/i, // "Established in 2004"
/(\d{4})년\s*오픈/, // "2004년 오픈"
/(\d{4})년\s*개업/, // "2004년 개업"
/개원일?\s*:\s*(\d{4})/, // "개원: 2004", "개원일: 2004"
// Anniversary / relative year expressions
/(\d{1,2})주년/, // "22주년" → currentYear-22
/(\d{1,2})년\s*전통/, // "20년 전통" → currentYear-20
/(\d{1,2})년\s*동안/, // "22년 동안" → currentYear-22
/개원\s*(\d{1,2})주년/, // "개원 15주년" → currentYear-15
/(\d{1,2})년\s*역사/, // "20년 역사" → currentYear-20
];
// ─── Extraction Function ───
/**
* Extract founding year from arbitrary text.
* Returns a 4-digit year or null if no pattern matches.
*
* @param text - Any text (HTML markdown, scraped content, vision output)
* @param currentYear - For relative calculations (default: current year)
*/
export function extractFoundingYear(
text: string,
currentYear: number = new Date().getFullYear(),
): number | null {
for (const pattern of FOUNDING_PATTERNS) {
const match = text.match(pattern);
if (!match) continue;
const num = parseInt(match[1], 10);
// 4-digit: direct year
if (num >= 1950 && num <= currentYear) return num;
// 1-2 digit: years ago → subtract from currentYear
if (num >= 1 && num <= 80) return currentYear - num;
}
return null;
}
// ─── Test Corpus ───
export const FOUNDING_YEAR_TEST_CORPUS: ReadonlyArray<readonly [string, number | null]> = [
["2004년개원 이래 중국, 베트남 환자들이 찾아오고 있습니다", 2004],
["SINCE 2004", 2004],
["22주년 기념 이벤트", 2004], // 2026-22
["개원 15주년을 맞이하여", 2011], // 2026-15
["20년 전통의 성형외과", 2006], // 2026-20
["2005년 설립된 뷰성형외과", 2005],
["설립 2010년, 강남에 위치한", 2010],
["Established in 2003", 2003],
["2018년 오픈한 신규 클리닉", 2018],
["개원: 2015", 2015],
["아무 관련 없는 텍스트입니다", null],
["전화번호 02-1234-5678", null],
];
/**
* Self-test: validate all known patterns.
* Uses fixed currentYear=2026 for deterministic results.
*/
export function validateFoundingYearExtractor(): { pass: boolean; failures: string[] } {
const failures: string[] = [];
for (const [text, expected] of FOUNDING_YEAR_TEST_CORPUS) {
const result = extractFoundingYear(text, 2026);
if (result !== expected) {
failures.push(`"${text.slice(0, 30)}...": expected ${expected}, got ${result}`);
}
}
return { pass: failures.length === 0, failures };
}
+120
View File
@@ -0,0 +1,120 @@
/**
* URL Classification Guard — Harness 1
*
* Separates URL classification into a testable pure function with
* an embedded test corpus. Prevents misclassification bugs like
* `/about/meet-our-doctors.php` being tagged as an "about" page.
*
* Priority: doctor > surgery > about (specific → general)
*/
// ─── Pattern Definitions ───
const PAGE_PATTERNS = {
doctor: {
positive: [
"/doctor", "/doctors", "/team", "/staff", "/specialist", "/professor",
"/의료진", "/원장", "meet-our-doctor", "/physicians", "/surgeon",
"our-team", "our-doctors",
],
},
surgery: {
positive: [
"/surgery", "/service", "/procedure", "/treatment", "/시술", "/수술",
"/procedures", "/treatments", "/services", "/진료",
],
},
about: {
positive: [
"/about", "/intro", "/소개", "/greeting", "/인사말", "/history", "/연혁",
"/company", "/clinic-info",
],
negative: [
"/doctor", "/doctors", "/procedure", "/surgery", "/service",
"/treatment", "meet-our", "/team", "/staff", "/specialist",
"/의료진", "/원장", "/시술", "/수술", "/진료",
"our-team", "our-doctors",
],
},
} as const;
// ─── Classification Function ───
/**
* Classify a URL into one of: 'doctor' | 'surgery' | 'about' | null.
* Uses priority ordering (doctor > surgery > about) so that
* compound URLs like `/about/meet-our-doctors.php` correctly resolve
* to the more specific category.
*/
export function classifyPageUrl(url: string): "doctor" | "surgery" | "about" | null {
const lower = url.toLowerCase();
// Priority 1: Doctor pages
if (PAGE_PATTERNS.doctor.positive.some((p) => lower.includes(p))) {
return "doctor";
}
// Priority 2: Surgery/service pages
if (PAGE_PATTERNS.surgery.positive.some((p) => lower.includes(p))) {
return "surgery";
}
// Priority 3: About pages (with negative exclusion)
if (PAGE_PATTERNS.about.positive.some((p) => lower.includes(p))) {
if (PAGE_PATTERNS.about.negative.some((p) => lower.includes(p))) {
return null; // Contains about + doctor/surgery keyword → ambiguous, skip
}
return "about";
}
return null;
}
// ─── Test Corpus ───
/**
* Known failure cases and expected classifications.
* Used by validateClassifier() for regression prevention.
*/
export const CLASSIFICATION_TEST_CORPUS: ReadonlyArray<readonly [string, "doctor" | "surgery" | "about" | null]> = [
// Bug cases (historically misclassified)
["/about/meet-our-doctors.php", "doctor"], // 그랜드성형외과 bug
["/about/procedures.php", "surgery"], // 그랜드성형외과
// Standard doctor pages
["/doctors", "doctor"],
["/의료진", "doctor"],
["/team/professor-kim", "doctor"],
["/about/our-team", "doctor"],
// Standard surgery pages
["/surgery/rhinoplasty", "surgery"],
["/시술안내", "surgery"],
["/services/breast", "surgery"],
// Standard about pages
["/about/", "about"],
["/about/greeting.php", "about"],
["/about/intro", "about"],
["/about/history", "about"],
["/소개", "about"],
["/인사말", "about"],
// Null cases
["/gallery", null],
["/contact", null],
["/blog/post-123", null],
];
// ─── Self-Test ───
/**
* Run classification against the test corpus.
* Call during Edge Function cold-start for automatic regression detection.
*/
export function validateClassifier(): { pass: boolean; failures: string[] } {
const failures: string[] = [];
for (const [url, expected] of CLASSIFICATION_TEST_CORPUS) {
const result = classifyPageUrl(url);
if (result !== expected) {
failures.push(`${url}: expected '${expected}', got '${result}'`);
}
}
return { pass: failures.length === 0, failures };
}
+18 -37
View File
@@ -7,6 +7,13 @@
*/
import { fetchWithRetry } from "./retry.ts";
import { classifyPageUrl, validateClassifier } from "./urlClassifier.ts";
// Run URL classifier self-test on cold-start
const classifierValidation = validateClassifier();
if (!classifierValidation.pass) {
console.warn(`[harness] URL classifier self-test FAILED:`, classifierValidation.failures);
}
const FIRECRAWL_BASE = "https://api.firecrawl.dev/v1";
@@ -124,54 +131,28 @@ async function captureScreenshot(
/**
* Find relevant sub-pages from siteMap for additional screenshots.
* Delegates classification to urlClassifier.ts for testability.
*/
export function findRelevantPages(
siteMap: string[],
baseUrl: string,
_baseUrl: string,
): { doctorPage?: string; surgeryPage?: string; aboutPage?: string } {
const result: { doctorPage?: string; surgeryPage?: string; aboutPage?: string } = {};
// Phase 1: Classify each URL into one category (doctor > surgery > about priority)
const doctorUrls: string[] = [];
const surgeryUrls: string[] = [];
const aboutUrls: string[] = [];
for (const url of siteMap) {
const lower = url.toLowerCase();
const isDoctor = (
lower.includes('/doctor') || lower.includes('/doctors') ||
lower.includes('/team') || lower.includes('/staff') ||
lower.includes('/specialist') || lower.includes('/professor') ||
lower.includes('/의료진') || lower.includes('/원장') ||
lower.includes('meet-our-doctor') // 하이픈 패턴 (그랜드성형외과 등)
);
const isSurgery = (
lower.includes('/surgery') || lower.includes('/service') || lower.includes('/procedure') ||
lower.includes('/treatment') || lower.includes('/시술') || lower.includes('/수술')
);
const isAbout = (
lower.includes('/about') || lower.includes('/intro') || lower.includes('/소개') ||
lower.includes('/greeting') || lower.includes('/인사말') || lower.includes('/history') ||
lower.includes('/연혁')
);
// Priority: specific page type > generic /about
if (isDoctor) {
doctorUrls.push(url);
} else if (isSurgery) {
surgeryUrls.push(url);
} else if (isAbout) {
aboutUrls.push(url);
}
const category = classifyPageUrl(url);
if (category === "doctor") doctorUrls.push(url);
else if (category === "surgery") surgeryUrls.push(url);
else if (category === "about") aboutUrls.push(url);
}
// Phase 2: Pick best URL per category
result.doctorPage = doctorUrls[0];
result.surgeryPage = surgeryUrls[0];
result.aboutPage = aboutUrls[0];
return result;
return {
doctorPage: doctorUrls[0],
surgeryPage: surgeryUrls[0],
aboutPage: aboutUrls[0],
};
}
/**
+239
View File
@@ -0,0 +1,239 @@
import "@supabase/functions-js/edge-runtime.d.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
import { PERPLEXITY_MODEL } from "../_shared/config.ts";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers":
"authorization, x-client-info, apikey, content-type",
};
interface AdjustStrategyRequest {
clinicId: string;
}
Deno.serve(async (req) => {
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
try {
const body = (await req.json()) as AdjustStrategyRequest;
if (!body.clinicId) throw new Error("clinicId is required");
const PERPLEXITY_API_KEY = Deno.env.get("PERPLEXITY_API_KEY");
if (!PERPLEXITY_API_KEY) throw new Error("PERPLEXITY_API_KEY not configured");
const supabaseUrl = Deno.env.get("SUPABASE_URL")!;
const supabaseKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;
const supabase = createClient(supabaseUrl, supabaseKey);
const clinicId = body.clinicId;
// ─── 1. Get channel deltas from weekly comparison view ───
const { data: deltas } = await supabase
.from("channel_weekly_delta")
.select("*")
.eq("clinic_id", clinicId);
// ─── 2. Get current active content plan ───
const { data: activePlan } = await supabase
.from("content_plans")
.select("id, channel_strategies, content_strategy, calendar")
.eq("clinic_id", clinicId)
.eq("is_active", true)
.order("created_at", { ascending: false })
.limit(1)
.single();
// ─── 3. Get latest analysis run for KPI targets ───
const { data: latestRun } = await supabase
.from("analysis_runs")
.select("id, report")
.eq("clinic_id", clinicId)
.eq("status", "complete")
.order("created_at", { ascending: false })
.limit(1)
.single();
const report = (latestRun?.report || {}) as Record<string, unknown>;
const kpiTargets = (report.kpiTargets || []) as Record<string, unknown>[];
// ─── 4. Calculate KPI progress ───
const kpiProgress = kpiTargets.map((kpi) => {
const current = parseFloat(String(kpi.current || "0").replace(/[^0-9.]/g, "")) || 0;
const target = parseFloat(String(kpi.target3Month || "0").replace(/[^0-9.]/g, "")) || 0;
const progress = target > 0 ? Math.min((current / target) * 100, 200) : 0;
return {
metric: kpi.metric,
current: kpi.current,
target: kpi.target3Month,
progress: Math.round(progress),
};
});
// ─── 5. Build channel delta summary ───
const deltaLines = (deltas || []).map((d: Record<string, unknown>) => {
const channel = d.channel as string;
const currentFollowers = d.current_followers as number || 0;
const prevFollowers = d.prev_followers as number || 0;
const change = currentFollowers - prevFollowers;
const changePercent = prevFollowers > 0
? ((change / prevFollowers) * 100).toFixed(1)
: "N/A";
return `${channel}: ${prevFollowers} → ${currentFollowers} (${change >= 0 ? "+" : ""}${changePercent}%)`;
});
const underperforming = (deltas || [])
.filter((d: Record<string, unknown>) => {
const current = d.current_followers as number || 0;
const prev = d.prev_followers as number || 0;
return prev > 0 && current <= prev;
})
.map((d: Record<string, unknown>) => d.channel as string);
// ─── 6. Call Perplexity for strategy adjustment ───
const userPrompt = `
현재 콘텐츠 전략의 성과를 분석하고 조정 추천을 해주세요.
## 채널 변화량 (최근 1주)
${deltaLines.join("\n") || "데이터 수집 중 (아직 비교 데이터 없음)"}
## KPI 달성률
${kpiProgress.map((k) => `${k.metric}: ${k.progress}% (${k.current} / ${k.target})`).join("\n") || "KPI 설정 전"}
## 부진 채널
${underperforming.join(", ") || "없음"}
## 현재 전략 요약
${JSON.stringify(activePlan?.channel_strategies || [], null, 2).slice(0, 2000)}
## 요청 출력 JSON
{
"strategySuggestions": [
{
"adjustmentType": "frequency_change|pillar_shift|channel_add|channel_pause|content_format_change|tone_shift",
"channel": "채널명",
"description": "변경 내용 설명",
"reason": "근거 (데이터 기반)",
"priority": "high|medium|low",
"beforeValue": "변경 전",
"afterValue": "변경 후"
}
],
"overallAssessment": "전체 전략 평가 (2-3문장)",
"topPerformingChannel": "가장 성과 좋은 채널",
"focusArea": "다음 2주 집중 영역"
}
`;
console.log(`[adjust-strategy] Calling Perplexity for clinic ${clinicId}...`);
const aiRes = await fetch("https://api.perplexity.ai/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${PERPLEXITY_API_KEY}`,
},
body: JSON.stringify({
model: PERPLEXITY_MODEL,
messages: [
{
role: "system",
content: "You are a Korean medical marketing performance analyst. Respond ONLY with valid JSON. Use Korean for text fields.",
},
{ role: "user", content: userPrompt },
],
temperature: 0.3,
}),
});
const aiData = await aiRes.json();
let responseText = aiData.choices?.[0]?.message?.content || "";
const jsonMatch = responseText.match(/```(?:json)?\n?([\s\S]*?)```/);
if (jsonMatch) responseText = jsonMatch[1];
if (!responseText.trim().startsWith("{")) {
const rawMatch = responseText.match(/\{[\s\S]*\}/);
if (rawMatch) responseText = rawMatch[0];
}
let adjustments: Record<string, unknown>;
try {
adjustments = JSON.parse(responseText);
} catch {
console.error("[adjust-strategy] JSON parse failed");
adjustments = {
strategySuggestions: [],
overallAssessment: "AI 분석 실패 — 수동 검토 필요",
topPerformingChannel: "N/A",
focusArea: "데이터 수집 대기",
};
}
// ─── 7. Store in performance_metrics ───
const channelDeltas: Record<string, unknown> = {};
for (const d of deltas || []) {
const ch = d.channel as string;
channelDeltas[ch] = {
currentFollowers: d.current_followers,
prevFollowers: d.prev_followers,
change: (d.current_followers as number || 0) - (d.prev_followers as number || 0),
};
}
const { data: perfMetric, error: perfErr } = await supabase
.from("performance_metrics")
.insert({
clinic_id: clinicId,
run_id: latestRun?.id || null,
prev_run_id: null,
channel_deltas: channelDeltas,
kpi_progress: kpiProgress,
top_performing_content: { channel: adjustments.topPerformingChannel },
underperforming_channels: underperforming,
strategy_suggestions: adjustments.strategySuggestions || [],
})
.select("id")
.single();
if (perfErr) console.error("[adjust-strategy] performance_metrics insert error:", perfErr);
// ─── 8. Store individual strategy_adjustments ───
const suggestions = (adjustments.strategySuggestions || []) as Record<string, unknown>[];
for (const s of suggestions) {
await supabase.from("strategy_adjustments").insert({
clinic_id: clinicId,
plan_id: activePlan?.id || null,
performance_id: perfMetric?.id || null,
adjustment_type: s.adjustmentType || "other",
description: s.description || "",
reason: s.reason || "",
before_value: { value: s.beforeValue },
after_value: { value: s.afterValue },
});
}
console.log(`[adjust-strategy] Created ${suggestions.length} adjustments for clinic ${clinicId}`);
return new Response(
JSON.stringify({
success: true,
performanceMetricId: perfMetric?.id || null,
adjustments,
channelDeltas,
kpiProgress,
underperforming,
}),
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
} catch (error) {
console.error("[adjust-strategy] Error:", error);
return new Response(
JSON.stringify({ success: false, error: error.message }),
{
status: 500,
headers: { ...corsHeaders, "Content-Type": "application/json" },
}
);
}
});
@@ -5,6 +5,21 @@ import { PERPLEXITY_MODEL } from "../_shared/config.ts";
import { captureAllScreenshots, runVisionAnalysis, screenshotErrors, type ScreenshotResult } from "../_shared/visionAnalysis.ts";
import { fetchWithRetry, fetchJsonWithRetry, wrapChannelTask, type ChannelTaskResult } from "../_shared/retry.ts";
import { searchGooglePlace } from "../_shared/googlePlaces.ts";
import { extractFoundingYear, validateFoundingYearExtractor } from "../_shared/foundingYearExtractor.ts";
import { validateClassifier } from "../_shared/urlClassifier.ts";
import { validateDataQuality } from "../_shared/dataQuality.ts";
// ─── Harness Self-Tests (cold-start) ───
const harnessResults = {
classifier: validateClassifier(),
foundingYear: validateFoundingYearExtractor(),
dataQuality: validateDataQuality(),
};
for (const [name, result] of Object.entries(harnessResults)) {
if (!result.pass) {
console.warn(`[harness] ${name} self-test FAILED:`, result.failures);
}
}
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
@@ -305,7 +320,9 @@ Deno.serve(async (req) => {
channelData.gangnamUnni = {
name: hospital.hospitalName,
rawRating: hospital.rating,
rating: typeof hospital.rating === 'number' && hospital.rating > 0 && hospital.rating <= 5 ? hospital.rating * 2 : hospital.rating,
// 강남언니 rating is always /10 (enforced in Firecrawl prompt) — trust the value directly.
// Do NOT multiply by 2: a score of 4.8 means 4.8/10, not 9.6/10.
rating: typeof hospital.rating === 'number' && hospital.rating > 0 ? hospital.rating : null,
ratingScale: "/10",
totalReviews: hospital.totalReviews, doctors: (hospital.doctors || []).slice(0, 10),
procedures: hospital.procedures || [], address: hospital.address,
@@ -475,6 +492,20 @@ Deno.serve(async (req) => {
}));
}
// ─── 9. Founding Year Text Fallback (Harness 2) ───
// If Vision didn't find foundingYear, try regex extraction from scraped text
if (!channelData.visionAnalysis?.foundingYear) {
const htmlText = row.scrape_data?.markdown || row.scrape_data?.text || "";
if (htmlText) {
const textYear = extractFoundingYear(htmlText);
if (textYear) {
channelData.visionAnalysis = channelData.visionAnalysis || {};
channelData.visionAnalysis.foundingYear = String(textYear);
console.log(`[harness] Founding year extracted from text fallback: ${textYear}`);
}
}
}
// ─── Execute all channel tasks ───
const taskResults = await Promise.all(channelTasks);
+220 -5
View File
@@ -12,6 +12,78 @@ const corsHeaders = {
const APIFY_BASE = "https://api.apify.com/v2";
// ─── Registry Helper: Convert registry row → VerifiedChannels ───
function extractHandleFromUrl(url: string, platform: string): string | null {
if (!url) return null;
try {
if (platform === 'instagram') {
const m = url.match(/instagram\.com\/([a-zA-Z0-9._]+)/);
return m ? m[1] : null;
}
if (platform === 'youtube') {
const m = url.match(/youtube\.com\/(?:@([a-zA-Z0-9._-]+)|channel\/(UC[a-zA-Z0-9_-]+)|c\/([a-zA-Z0-9._-]+)|user\/([a-zA-Z0-9._-]+))/);
if (m) return m[1] ? `@${m[1]}` : m[2] || m[3] || m[4] || null;
return null;
}
if (platform === 'facebook') {
const m = url.match(/facebook\.com\/([a-zA-Z0-9._-]+)/);
return m ? m[1] : null;
}
if (platform === 'naverBlog') {
const m = url.match(/blog\.naver\.com\/([a-zA-Z0-9_-]+)/);
return m ? m[1] : null;
}
if (platform === 'tiktok') {
const m = url.match(/tiktok\.com\/@([a-zA-Z0-9._-]+)/);
return m ? m[1] : null;
}
} catch { /* ignore */ }
return null;
}
interface RegistryRow {
name: string;
domain: string;
website_url: string;
brand_group?: string;
district?: string;
branches?: string;
website_en?: string;
youtube_url?: string;
instagram_url?: string;
instagram_en_url?: string;
facebook_url?: string;
tiktok_url?: string;
naver_blog_url?: string;
naver_place_url?: string;
gangnam_unni_url?: string;
google_maps_url?: string;
founded_year?: number;
}
function registryToVerifiedChannels(reg: RegistryRow): import("../_shared/verifyHandles.ts").VerifiedChannels {
const igHandles: import("../_shared/verifyHandles.ts").VerifiedChannel[] = [];
const igHandle = extractHandleFromUrl(reg.instagram_url || '', 'instagram');
if (igHandle) igHandles.push({ handle: igHandle, verified: true, url: reg.instagram_url! });
const igEnHandle = extractHandleFromUrl(reg.instagram_en_url || '', 'instagram');
if (igEnHandle) igHandles.push({ handle: igEnHandle, verified: true, url: reg.instagram_en_url! });
const ytHandle = extractHandleFromUrl(reg.youtube_url || '', 'youtube');
const fbHandle = extractHandleFromUrl(reg.facebook_url || '', 'facebook');
const blogHandle = extractHandleFromUrl(reg.naver_blog_url || '', 'naverBlog');
const ttHandle = extractHandleFromUrl(reg.tiktok_url || '', 'tiktok');
return {
instagram: igHandles,
youtube: ytHandle ? { handle: ytHandle, verified: true, url: reg.youtube_url! } : null,
facebook: fbHandle ? { handle: fbHandle, verified: true, url: reg.facebook_url! } : null,
naverBlog: blogHandle ? { handle: blogHandle, verified: true, url: reg.naver_blog_url! } : null,
gangnamUnni: reg.gangnam_unni_url ? { handle: reg.gangnam_unni_url, verified: true, url: reg.gangnam_unni_url } : null,
tiktok: ttHandle ? { handle: ttHandle, verified: true, url: reg.tiktok_url! } : null,
};
}
interface DiscoverRequest {
url: string;
clinicName?: string;
@@ -84,6 +156,153 @@ Deno.serve(async (req) => {
);
}
// ═══════════════════════════════════════════
// REGISTRY CHECK: Pre-verified clinic DB lookup
// If domain is registered, skip all API discovery
// ═══════════════════════════════════════════
const supabaseUrl = Deno.env.get("SUPABASE_URL")!;
const supabaseKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;
const supabase = createClient(supabaseUrl, supabaseKey);
let registryDomain: string;
try {
registryDomain = new URL(url).hostname.replace(/^www\./, '');
} catch {
registryDomain = '';
}
if (registryDomain) {
const { data: registered } = await supabase
.from("clinic_registry")
.select("*")
.eq("domain", registryDomain)
.eq("is_active", true)
.maybeSingle();
if (registered) {
console.log(`[registry] Hit: ${registered.name} (${registryDomain})`);
const verified = registryToVerifiedChannels(registered as RegistryRow);
const scrapeDataFromRegistry = {
clinic: { clinicName: registered.name },
branding: {},
siteLinks: [],
siteMap: [],
sourceUrl: url,
scrapedAt: new Date().toISOString(),
source: "registry",
registryData: {
district: registered.district,
branches: registered.branches,
brandGroup: registered.brand_group,
foundedYear: registered.founded_year,
websiteEn: registered.website_en,
naverPlaceUrl: registered.naver_place_url,
googleMapsUrl: registered.google_maps_url,
},
};
// Legacy: marketing_reports
const { data: saved, error: saveError } = await supabase
.from("marketing_reports")
.insert({
url, clinic_name: registered.name,
status: "discovered",
verified_channels: verified,
scrape_data: scrapeDataFromRegistry,
report: {},
pipeline_started_at: new Date().toISOString(),
})
.select("id")
.single();
if (saveError) throw new Error(`DB save failed: ${saveError.message}`);
// V3: clinics + analysis_runs
let clinicId: string | null = null;
let runId: string | null = null;
try {
const { data: clinicRow } = await supabase
.from("clinics")
.upsert({
url,
name: registered.name,
name_en: null,
domain: registryDomain,
address: null,
phone: null,
services: [],
branding: {},
social_handles: {
instagram: verified.instagram?.map((v: Record<string, unknown>) => v.handle) || [],
youtube: (verified.youtube as Record<string, unknown>)?.handle || null,
facebook: (verified.facebook as Record<string, unknown>)?.handle || null,
naverBlog: (verified.naverBlog as Record<string, unknown>)?.handle || null,
},
verified_channels: verified,
last_analyzed_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
}, { onConflict: 'url' })
.select("id")
.single();
clinicId = clinicRow?.id || null;
if (clinicId) {
const { data: runRow } = await supabase
.from("analysis_runs")
.insert({
clinic_id: clinicId,
status: "discovering",
scrape_data: scrapeDataFromRegistry,
discovered_channels: verified,
trigger: "manual",
pipeline_started_at: new Date().toISOString(),
})
.select("id")
.single();
runId = runRow?.id || null;
}
} catch (e) {
console.error("V3 dual-write error (registry):", e);
}
return new Response(
JSON.stringify({
success: true, reportId: saved.id,
clinicId, runId,
clinicName: registered.name,
verifiedChannels: verified,
address: "",
services: [],
scrapeData: scrapeDataFromRegistry,
source: "registry",
}),
{ headers: { ...corsHeaders, "Content-Type": "application/json" } },
);
}
}
// ═══════════════════════════════════════════
// NOT REGISTERED: Return error for unregistered domains
// (Registry-only mode — no API fallback)
// ═══════════════════════════════════════════
console.log(`[registry] Miss: ${registryDomain} — returning CLINIC_NOT_REGISTERED`);
return new Response(
JSON.stringify({
success: false,
error: "CLINIC_NOT_REGISTERED",
message: "현재 지원하지 않는 병원입니다. 등록된 병원만 분석 가능합니다.",
domain: registryDomain,
}),
{ status: 404, headers: { ...corsHeaders, "Content-Type": "application/json" } },
);
// ═══════════════════════════════════════════
// LEGACY FALLBACK: Full API discovery (disabled — registry-only mode)
// Kept for reference; unreachable in production
// ═══════════════════════════════════════════
const FIRECRAWL_API_KEY = Deno.env.get("FIRECRAWL_API_KEY") || "";
const PERPLEXITY_API_KEY = Deno.env.get("PERPLEXITY_API_KEY") || "";
const YOUTUBE_API_KEY = Deno.env.get("YOUTUBE_API_KEY") || "";
@@ -478,13 +697,9 @@ Deno.serve(async (req) => {
);
// ═══════════════════════════════════════════
// Save to DB
// Save to DB (supabase client reused from registry check above)
// ═══════════════════════════════════════════
const supabaseUrl = Deno.env.get("SUPABASE_URL")!;
const supabaseKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;
const supabase = createClient(supabaseUrl, supabaseKey);
const scrapeDataFull = {
clinic, branding: brandData.data?.json || {},
siteLinks, siteMap: mapData.links || [],
@@ -0,0 +1,456 @@
import "@supabase/functions-js/edge-runtime.d.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
import { PERPLEXITY_MODEL } from "../_shared/config.ts";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers":
"authorization, x-client-info, apikey, content-type",
};
interface ContentPlanRequest {
reportId?: string;
clinicId?: string;
runId?: string;
}
Deno.serve(async (req) => {
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
try {
const body = (await req.json()) as ContentPlanRequest;
const PERPLEXITY_API_KEY = Deno.env.get("PERPLEXITY_API_KEY");
if (!PERPLEXITY_API_KEY) throw new Error("PERPLEXITY_API_KEY not configured");
const supabaseUrl = Deno.env.get("SUPABASE_URL")!;
const supabaseKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;
const supabase = createClient(supabaseUrl, supabaseKey);
// ─── 1. Load report data ───
let report: Record<string, unknown> = {};
let clinicId = body.clinicId;
let runId = body.runId;
let clinicName = "";
let services: string[] = [];
// Try V3 analysis_runs first
if (runId) {
const { data: run } = await supabase
.from("analysis_runs")
.select("report, clinic_id")
.eq("id", runId)
.single();
if (run?.report) {
report = run.report as Record<string, unknown>;
clinicId = clinicId || run.clinic_id;
}
}
// Fallback to marketing_reports
if (Object.keys(report).length === 0 && body.reportId) {
const { data: row } = await supabase
.from("marketing_reports")
.select("report, clinic_name")
.eq("id", body.reportId)
.single();
if (row?.report) {
report = row.report as Record<string, unknown>;
clinicName = row.clinic_name || "";
}
}
if (Object.keys(report).length === 0) {
throw new Error("No report data found. Provide reportId or runId.");
}
// Resolve clinic info
if (clinicId) {
const { data: clinic } = await supabase
.from("clinics")
.select("name, services")
.eq("id", clinicId)
.single();
if (clinic) {
clinicName = clinic.name || clinicName;
services = clinic.services || [];
}
}
const clinicInfo = report.clinicInfo as Record<string, unknown> | undefined;
if (!clinicName) clinicName = (clinicInfo?.name as string) || "병원";
if (services.length === 0) services = (clinicInfo?.services as string[]) || [];
// ─── 2. Build enriched channel summary for AI prompt ───
const channelAnalysis = report.channelAnalysis as Record<string, Record<string, unknown>> | undefined;
const kpiTargets = report.kpiTargets as Record<string, unknown>[] | undefined;
const recommendations = report.recommendations as Record<string, unknown>[] | undefined;
const competitors = report.competitors as Record<string, unknown>[] | undefined;
const reportKeywords = report.keywords as { primary?: Record<string, unknown>[]; longTail?: Record<string, unknown>[] } | undefined;
// Channel-specific tone matrix (Audit C3)
const TONE_MAP: Record<string, string> = {
youtube: "교육적·권위(Long) / 캐주얼·후킹(Shorts) / 친근·대화(Live)",
instagram: "트렌디·공감(Reel) / 감성적·프리미엄(Feed) / 친근·일상(Stories)",
naverBlog: "정보성·SEO 최적화",
gangnamUnni: "전문·응대·신뢰",
facebook: "타겟팅·CTA 중심",
tiktok: "밈·교육·MZ세대",
};
const channelLines: string[] = [];
if (channelAnalysis) {
for (const [key, ch] of Object.entries(channelAnalysis)) {
const score = (ch.score as number) ?? 0;
const status = (ch.status as string) || "unknown";
const followers = ch.followers || ch.subscribers || ch.reviews || "";
const tone = TONE_MAP[key] || "전문적·친근한";
channelLines.push(`${key}: 점수 ${score}/100, 상태: ${status}${followers ? `, 규모: ${followers}` : ""}, 톤: ${tone}`);
}
}
const kpiLines = (kpiTargets || []).slice(0, 5).map(
(k) => `${k.metric}: 현재 ${k.current} → 3개월 목표 ${k.target3Month}`
);
const recLines = (recommendations || []).slice(0, 5).map(
(r) => `[${r.priority}] ${r.title}`
);
// Competitor summary (Audit: inject competitor data)
const competitorLines = (competitors || []).slice(0, 3).map(
(c) => `${c.name}: 강점=${(c.strengths as string[] || []).join(",")} 약점=${(c.weaknesses as string[] || []).join(",")}`
);
// Keyword summary (Audit C5: connect keywords to topics)
const keywordLines = (reportKeywords?.primary || []).slice(0, 10).map(
(k) => `${k.keyword} (월 ${k.monthlySearches || "?"}회 검색)`
);
// ─── 3. Call Perplexity sonar (enhanced prompt) ───
const userPrompt = `
${clinicName} 성형외과의 콘텐츠 마케팅 전략을 수립해주세요.
## 시술 분야
${services.join(", ") || "성형외과 전반"}
## 채널 현황 (채널별 톤앤매너 준수)
${channelLines.join("\n")}
## 검색 키워드 (블로그·YouTube SEO에 활용)
${keywordLines.join("\n") || "키워드 데이터 없음"}
## 경쟁사 분석
${competitorLines.join("\n") || "경쟁사 데이터 없음"}
## KPI 목표
${kpiLines.join("\n") || "설정 전"}
## 주요 추천사항
${recLines.join("\n") || "없음"}
## 고객 여정 기반 주간 테마 (반드시 적용)
- Week 1: 인지 확대 (YouTube Shorts, TikTok, Instagram Reels 집중)
- Week 2: 관심 유도 (Long-form, 블로그 SEO, Carousel 집중)
- Week 3: 신뢰 구축 (강남언니 리뷰, Before/After, 의사 소개 집중)
- Week 4: 전환 최적화 (Facebook 광고, Instagram DM CTA, 프로모션 집중)
## 필수 포함 채널 (모두 캘린더에 포함할 것)
YouTube (Shorts + Long + Live + Community), Instagram (Reel + Carousel + Feed + Stories), 강남언니 (리뷰관리 + 프로필최적화 + 이벤트), TikTok (숏폼), 네이버 블로그 (SEO글 + 의사칼럼), Facebook (오가닉 + 광고)
## 콘텐츠 필러 (5개 필러 반드시 포함)
1. 전문성·신뢰, 2. 비포·애프터, 3. 환자 후기, 4. 트렌드·교육, 5. 안전·케어
## 요청 출력 (반드시 아래 JSON 구조로)
{
"channelStrategies": [
{
"channelId": "youtube|instagram|naverBlog|facebook|tiktok",
"channelName": "한국어 채널명",
"icon": "youtube|instagram|blog|facebook|video",
"currentStatus": "현재 상태 요약",
"targetGoal": "3개월 목표",
"contentTypes": ["콘텐츠 유형 1", "콘텐츠 유형 2"],
"postingFrequency": "주 N회",
"tone": "톤앤매너",
"formatGuidelines": ["가이드라인 1"],
"priority": "P0|P1|P2"
}
],
"contentPillars": [
{
"title": "필러 제목",
"description": "설명",
"relatedUSP": "연관 USP",
"exampleTopics": ["주제 1", "주제 2", "주제 3"],
"color": "#hex"
}
],
"calendar": {
"weeks": [
{
"weekNumber": 1,
"label": "Week 1: 주제",
"entries": [
{
"id": "uuid",
"dayOfWeek": 0,
"channel": "채널명",
"channelIcon": "아이콘",
"contentType": "video|blog|social|ad",
"title": "콘텐츠 제목",
"description": "제작 가이드",
"pillar": "필러 제목",
"status": "draft",
"aiPromptSeed": "AI 재생성용 컨텍스트"
}
]
}
],
"monthlySummary": [
{"type": "video", "label": "영상", "count": 0, "color": "#6C5CE7"},
{"type": "blog", "label": "블로그", "count": 0, "color": "#00B894"},
{"type": "social", "label": "소셜", "count": 0, "color": "#E17055"},
{"type": "ad", "label": "광고", "count": 0, "color": "#FDCB6E"}
]
},
"postingSchedule": {
"bestTimes": {"youtube": "오후 6-8시", "instagram": "오후 12-1시, 오후 7-9시"},
"rationale": "근거 설명"
}
}
4주간 캘린더를 생성하되, 각 주에 최소 8-12개 엔트리를 포함하세요.
각 엔트리의 id는 고유한 UUID 형식이어야 합니다.
콘텐츠 제목은 구체적이고 실행 가능해야 합니다 (예: "코성형 전후 비교 리얼 후기" ✅, "콘텐츠 #1" ❌).
`;
console.log(`[content-plan] Calling Perplexity for ${clinicName}...`);
const aiRes = await fetch("https://api.perplexity.ai/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${PERPLEXITY_API_KEY}`,
},
body: JSON.stringify({
model: PERPLEXITY_MODEL,
messages: [
{
role: "system",
content:
"You are a Korean medical marketing content strategist. Respond ONLY with valid JSON, no markdown code blocks. Use Korean for all text fields. Generate UUID v4 for each calendar entry id.",
},
{ role: "user", content: userPrompt },
],
temperature: 0.3,
}),
});
const aiData = await aiRes.json();
let responseText = aiData.choices?.[0]?.message?.content || "";
// Strip markdown code blocks if present
const jsonMatch = responseText.match(/```(?:json)?\n?([\s\S]*?)```/);
if (jsonMatch) responseText = jsonMatch[1];
// Try raw JSON match as fallback
if (!responseText.trim().startsWith("{")) {
const rawMatch = responseText.match(/\{[\s\S]*\}/);
if (rawMatch) responseText = rawMatch[0];
}
let contentPlan: Record<string, unknown>;
try {
contentPlan = JSON.parse(responseText);
} catch {
console.error("[content-plan] JSON parse failed, using fallback");
contentPlan = buildFallbackPlan(channelAnalysis, services, clinicName);
}
// ─── 4. Store in content_plans table ───
const resolvedClinicId = clinicId || null;
const resolvedRunId = runId || null;
// Deactivate previous active plans for this clinic
if (resolvedClinicId) {
await supabase
.from("content_plans")
.update({ is_active: false })
.eq("clinic_id", resolvedClinicId)
.eq("is_active", true);
}
const { data: plan, error: insertErr } = await supabase
.from("content_plans")
.insert({
clinic_id: resolvedClinicId,
run_id: resolvedRunId,
channel_strategies: contentPlan.channelStrategies || [],
content_strategy: {
pillars: contentPlan.contentPillars || [],
typeMatrix: [],
workflow: [],
repurposingSource: "",
repurposingOutputs: [],
},
calendar: contentPlan.calendar || { weeks: [], monthlySummary: [] },
brand_guide: {},
is_active: true,
})
.select("id")
.single();
if (insertErr) {
console.error("[content-plan] DB insert error:", insertErr);
}
console.log(`[content-plan] Plan created: ${plan?.id} for ${clinicName}`);
return new Response(
JSON.stringify({
success: true,
planId: plan?.id || null,
contentPlan,
clinicName,
}),
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
} catch (error) {
console.error("[content-plan] Error:", error);
return new Response(
JSON.stringify({ success: false, error: error.message }),
{
status: 500,
headers: { ...corsHeaders, "Content-Type": "application/json" },
}
);
}
});
// ─── Fallback: Deterministic plan when AI fails ───
function buildFallbackPlan(
channelAnalysis: Record<string, Record<string, unknown>> | undefined,
services: string[],
clinicName: string,
): Record<string, unknown> {
const channels = channelAnalysis ? Object.keys(channelAnalysis) : ["youtube", "instagram"];
const svcList = services.length > 0 ? services : ["성형외과 시술"];
const PILLAR_COLORS = ["#6C5CE7", "#E17055", "#00B894", "#FDCB6E"];
const pillars = [
{ title: "전문성 · 신뢰", description: "의료진 소개, 수술 과정, 인증 콘텐츠", relatedUSP: "전문 의료진", exampleTopics: svcList.slice(0, 3).map((s) => `${s} 시술 과정 소개`), color: PILLAR_COLORS[0] },
{ title: "비포 · 애프터", description: "실제 환자 사례, 수술 전후 비교", relatedUSP: "검증된 결과", exampleTopics: svcList.slice(0, 3).map((s) => `${s} 전후 비교`), color: PILLAR_COLORS[1] },
{ title: "환자 후기", description: "실제 환자 인터뷰, 후기 콘텐츠", relatedUSP: "환자 만족도", exampleTopics: ["환자 인터뷰 영상", "리뷰 하이라이트", "회복 일기"], color: PILLAR_COLORS[2] },
{ title: "트렌드 · 교육", description: "시술 트렌드, Q&A, 의학 정보", relatedUSP: "최신 트렌드", exampleTopics: ["자주 묻는 질문 Q&A", "시술별 비용 가이드", "최신 트렌드"], color: PILLAR_COLORS[3] },
];
const WEEK_THEMES = ["브랜드 정비", "콘텐츠 엔진 가동", "소셜 증거 강화", "전환 최적화"];
const weeks = WEEK_THEMES.map((theme, wi) => {
const entries = [];
const pillar = pillars[wi % pillars.length];
let entryIdx = 0;
if (channels.includes("youtube")) {
for (let d = 0; d < 3; d++) {
entries.push({
id: crypto.randomUUID(),
dayOfWeek: d * 2,
channel: "YouTube",
channelIcon: "youtube",
contentType: "video",
title: `Shorts: ${svcList[entryIdx % svcList.length]} ${pillar.title}`,
description: `${pillar.description} 관련 숏폼 콘텐츠`,
pillar: pillar.title,
status: "draft",
aiPromptSeed: `${clinicName} ${svcList[entryIdx % svcList.length]} ${pillar.title} shorts`,
});
entryIdx++;
}
}
if (channels.includes("instagram")) {
entries.push({
id: crypto.randomUUID(),
dayOfWeek: 1,
channel: "Instagram",
channelIcon: "instagram",
contentType: "social",
title: `Carousel: ${svcList[0]} ${pillar.exampleTopics[0] || ""}`,
description: "인스타그램 카드뉴스",
pillar: pillar.title,
status: "draft",
aiPromptSeed: `${clinicName} instagram carousel ${pillar.title}`,
});
entries.push({
id: crypto.randomUUID(),
dayOfWeek: 3,
channel: "Instagram",
channelIcon: "instagram",
contentType: "video",
title: `Reel: ${svcList[0]} ${pillar.title}`,
description: "인스타그램 릴스",
pillar: pillar.title,
status: "draft",
aiPromptSeed: `${clinicName} instagram reel ${pillar.title}`,
});
}
if (channels.includes("naverBlog")) {
entries.push({
id: crypto.randomUUID(),
dayOfWeek: 2,
channel: "네이버 블로그",
channelIcon: "blog",
contentType: "blog",
title: `${svcList[entryIdx % svcList.length]} ${pillar.exampleTopics[0] || ""}`,
description: "SEO 최적화 블로그 포스트",
pillar: pillar.title,
status: "draft",
aiPromptSeed: `${clinicName} naver blog ${pillar.title}`,
});
}
entries.sort((a, b) => a.dayOfWeek - b.dayOfWeek);
return {
weekNumber: wi + 1,
label: `Week ${wi + 1}: ${theme}`,
entries,
};
});
const allEntries = weeks.flatMap((w) => w.entries);
return {
channelStrategies: channels.map((ch) => ({
channelId: ch,
channelName: ch,
icon: ch === "youtube" ? "youtube" : ch === "instagram" ? "instagram" : "globe",
currentStatus: "분석 완료",
targetGoal: "콘텐츠 전략 수립",
contentTypes: ["숏폼", "피드"],
postingFrequency: "주 2-3회",
tone: "전문적 · 친근한",
formatGuidelines: [],
priority: "P1",
})),
contentPillars: pillars,
calendar: {
weeks,
monthlySummary: [
{ type: "video", label: "영상", count: allEntries.filter((e) => e.contentType === "video").length, color: "#6C5CE7" },
{ type: "blog", label: "블로그", count: allEntries.filter((e) => e.contentType === "blog").length, color: "#00B894" },
{ type: "social", label: "소셜", count: allEntries.filter((e) => e.contentType === "social").length, color: "#E17055" },
{ type: "ad", label: "광고", count: allEntries.filter((e) => e.contentType === "ad").length, color: "#FDCB6E" },
],
},
postingSchedule: {
bestTimes: { youtube: "오후 6-8시", instagram: "오후 12-1시, 오후 7-9시" },
rationale: "한국 직장인/성형 관심층 주요 활동 시간대 기반",
},
};
}
+39 -9
View File
@@ -2,6 +2,9 @@ import "@supabase/functions-js/edge-runtime.d.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
import { normalizeInstagramHandle } from "../_shared/normalizeHandles.ts";
import { PERPLEXITY_MODEL } from "../_shared/config.ts";
import { isMissingValue, validateReportQuality } from "../_shared/dataQuality.ts";
import { extractFoundingYear } from "../_shared/foundingYearExtractor.ts";
import { fetchWithRetry } from "../_shared/retry.ts";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
@@ -110,7 +113,9 @@ ${JSON.stringify(scrapeData.branding || {}, null, 2).slice(0, 1000)}
}
`;
const aiRes = await fetch("https://api.perplexity.ai/chat/completions", {
// Use fetchWithRetry to handle transient Perplexity failures (429, 502, 503).
// 2 retries with 5s/15s backoff — total budget ~3min before giving up.
const aiRes = await fetchWithRetry("https://api.perplexity.ai/chat/completions", {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: `Bearer ${PERPLEXITY_API_KEY}` },
body: JSON.stringify({
@@ -121,7 +126,7 @@ ${JSON.stringify(scrapeData.branding || {}, null, 2).slice(0, 1000)}
],
temperature: 0.3,
}),
});
}, { maxRetries: 2, backoffMs: [5000, 15000], timeoutMs: 90000, label: "perplexity-report" });
const aiData = await aiRes.json();
let reportText = aiData.choices?.[0]?.message?.content || "";
@@ -134,19 +139,15 @@ ${JSON.stringify(scrapeData.branding || {}, null, 2).slice(0, 1000)}
// ─── Post-processing: Inject Vision Analysis data directly ───
// Perplexity may ignore Vision data in prompt, so we force-inject critical fields
const vision = channelData.visionAnalysis as Record<string, unknown> | undefined;
const isEstablishedMissing = (val: unknown): boolean => {
if (!val) return true;
const s = String(val).trim().toLowerCase();
return s === '' || s === '데이터 없음' || s === '데이터없음' || s === 'n/a' || s === '확인불가' || s === '미확인' || s === '정보없음' || s === '정보 없음';
};
// Use Harness 3's isMissingValue() — covers all known LLM "no data" variants
if (vision) {
// Force-inject foundingYear if Vision found it but Perplexity didn't
if (vision.foundingYear && isEstablishedMissing(report.clinicInfo?.established)) {
if (vision.foundingYear && isMissingValue(report.clinicInfo?.established)) {
report.clinicInfo = report.clinicInfo || {};
report.clinicInfo.established = String(vision.foundingYear);
console.log(`[report] Injected foundingYear from Vision: ${vision.foundingYear}`);
}
if (vision.operationYears && isEstablishedMissing(report.clinicInfo?.established)) {
if (vision.operationYears && isMissingValue(report.clinicInfo?.established)) {
const year = new Date().getFullYear() - Number(vision.operationYears);
report.clinicInfo = report.clinicInfo || {};
report.clinicInfo.established = String(year);
@@ -289,10 +290,39 @@ ${JSON.stringify(scrapeData.branding || {}, null, 2).slice(0, 1000)}
facebook: verified.facebook?.verified ? verified.facebook.handle : null,
};
// ─── Harness 2 (tertiary): Last-resort founding year from all channel text ───
if (isMissingValue(report.clinicInfo?.established)) {
const allTexts = [
channelData.scrapeMarkdown,
channelData.naverBlog?.description,
channelData.gangnamUnni?.description,
JSON.stringify(channelData.visionPerPage || {}),
].filter(Boolean).join(" ");
const lastResortYear = extractFoundingYear(allTexts);
if (lastResortYear) {
report.clinicInfo = report.clinicInfo || {};
report.clinicInfo.established = String(lastResortYear);
console.log(`[harness] Founding year from tertiary text scan: ${lastResortYear}`);
}
}
// ─── Harness 3: Report quality validation ───
const qualityReport = validateReportQuality(report);
report.dataQualityScore = qualityReport.score;
report.dataQualityDetails = {
missingCritical: qualityReport.missingCritical,
missingImportant: qualityReport.missingImportant,
warnings: qualityReport.warnings,
};
if (qualityReport.score < 60) {
console.warn(`[harness] Low report quality (${qualityReport.score}/100):`, qualityReport.warnings);
}
// Legacy: marketing_reports
await supabase.from("marketing_reports").update({
report,
status: "complete",
data_quality_score: qualityReport.score,
pipeline_completed_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
}).eq("id", body.reportId);
@@ -0,0 +1,61 @@
-- ═══════════════════════════════════════════════════════════════
-- Clinic Registry: Pre-verified channel database
-- ═══════════════════════════════════════════════════════════════
-- 사전 검증된 병원 채널 DB. discover-channels에서 API 검색 전에
-- domain으로 조회하여 검증된 채널을 즉시 반환.
-- 미등록 도메인은 기존 API 기반 discovery fallback 사용.
CREATE TABLE IF NOT EXISTS clinic_registry (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
-- 병원 식별
name TEXT NOT NULL, -- 한국어 병원명 (ex: "아이디병원")
name_aliases TEXT[] DEFAULT '{}', -- 별칭 (ex: {"아이디성형외과", "ID Hospital"})
domain TEXT UNIQUE NOT NULL, -- 도메인 (www 제외, lookup key)
website_url TEXT NOT NULL, -- 전체 URL
-- 기본 정보
brand_group TEXT, -- 그룹/카테고리 (ex: "프리미엄/하이타깃 후보")
district TEXT, -- 지역구 (ex: "강남", "서초")
branches TEXT, -- 분점 정보
founded_year INT, -- 개원 연도
-- 영문 사이트
website_en TEXT,
-- 소셜 채널 (사전 검증 완료)
youtube_url TEXT,
instagram_url TEXT,
instagram_en_url TEXT,
facebook_url TEXT,
tiktok_url TEXT,
naver_blog_url TEXT,
naver_place_url TEXT,
gangnam_unni_url TEXT,
google_maps_url TEXT,
-- 메타
verified_by TEXT DEFAULT 'scrape', -- 'manual' | 'scrape' | 'llm'
verified_at TIMESTAMPTZ DEFAULT now(),
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
-- 인덱스: domain lookup (primary query path)
CREATE INDEX IF NOT EXISTS idx_clinic_registry_domain ON clinic_registry (domain);
-- GIN 인덱스: 별칭 검색
CREATE INDEX IF NOT EXISTS idx_clinic_registry_aliases ON clinic_registry USING gin (name_aliases);
-- 지역 필터
CREATE INDEX IF NOT EXISTS idx_clinic_registry_district ON clinic_registry (district);
-- RLS (서비스 키로만 접근, 프론트엔드에서는 Edge Function 통해서만)
ALTER TABLE clinic_registry ENABLE ROW LEVEL SECURITY;
-- 서비스 역할만 CRUD 가능
CREATE POLICY "service_role_full_access" ON clinic_registry
FOR ALL USING (auth.role() = 'service_role');
-- anon/authenticated는 읽기만
CREATE POLICY "public_read_registry" ON clinic_registry
FOR SELECT USING (true);