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

+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 || [],