fix: 파이프라인 3대 핵심 버그 수정

- generate-report: Harness 4 groundTruth 주입 레이어 추가 (IG/YT/FB/NaverBlog/NaverPlace/GangnamUnni 필드 강제 주입, diagnosis 폴백, qualityReport DB 저장)
- discover-channels: CLINIC_NOT_REGISTERED 조기 종료 제거 + clinics 캐시 fast-path 추가 (14일 TTL, Firecrawl fallback 재활성화)
- collect-channel-data: silent skip → {status, reason, attemptedAt} 구조적 기록 (naverBlog/naverPlace/googleMaps/gangnamUnni)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Haewon KamandClaude Opus 4.6 committed 2026-04-10 13:41:05 +09:00
1 parent aabba1534b
commit c753d8593f
3 files changed
+398 -36

No files matched your search

+127 -14
View File
@@ -284,23 +284,122 @@ Deno.serve(async (req) => {
}
// ═══════════════════════════════════════════
// NOT REGISTERED: Return error for unregistered domains
// (Registry-only mode — no API fallback)
// REGISTRY MISS — secondary fast-path via `clinics` cache
// If this domain was previously auto-discovered and cached in `clinics.verified_channels`,
// reuse it instead of re-running the full Firecrawl+Perplexity discovery.
// Fresh runs only re-discover after 14 days so stale handles eventually refresh.
// ═══════════════════════════════════════════
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" } },
);
console.log(`[registry] Miss: ${registryDomain} — trying clinics cache + Firecrawl fallback`);
if (registryDomain) {
try {
const { data: cachedClinic } = await supabase
.from("clinics")
.select("id, name, name_en, address, phone, services, branding, verified_channels, last_analyzed_at")
.eq("domain", registryDomain)
.maybeSingle();
const cachedChannels = cachedClinic?.verified_channels as VerifiedChannels | null | undefined;
const hasAny = cachedChannels && (
((cachedChannels as Record<string, unknown>).instagram as unknown[] | undefined)?.length
|| (cachedChannels as Record<string, unknown>).youtube
|| (cachedChannels as Record<string, unknown>).facebook
|| (cachedChannels as Record<string, unknown>).naverBlog
);
const lastAnalyzed = cachedClinic?.last_analyzed_at ? new Date(cachedClinic.last_analyzed_at).getTime() : 0;
const CACHE_TTL_MS = 14 * 24 * 60 * 60 * 1000;
const cacheFresh = lastAnalyzed > 0 && (Date.now() - lastAnalyzed) < CACHE_TTL_MS;
if (cachedClinic && hasAny && cacheFresh) {
console.log(`[clinics-cache] Hit: ${cachedClinic.name} (${registryDomain}) — reusing cached channels`);
const scrapeDataFromCache = {
clinic: {
clinicName: cachedClinic.name,
clinicNameEn: cachedClinic.name_en,
address: cachedClinic.address,
phone: cachedClinic.phone,
services: cachedClinic.services || [],
},
branding: cachedClinic.branding || {},
siteLinks: [],
siteMap: [],
sourceUrl: url,
scrapedAt: new Date().toISOString(),
source: "clinics-cache",
};
const { data: saved, error: saveError } = await supabase
.from("marketing_reports")
.insert({
url,
clinic_name: cachedClinic.name,
status: "discovered",
verified_channels: cachedChannels,
scrape_data: scrapeDataFromCache,
report: {},
pipeline_started_at: new Date().toISOString(),
})
.select("id")
.single();
if (saveError) throw new Error(`DB save failed: ${saveError.message}`);
// Refresh last_analyzed_at so the cache stays warm
await supabase.from("clinics")
.update({ last_analyzed_at: new Date().toISOString() })
.eq("id", cachedClinic.id);
// V3 run record
let runId: string | null = null;
try {
const { data: runRow } = await supabase
.from("analysis_runs")
.insert({
clinic_id: cachedClinic.id,
status: "discovering",
scrape_data: scrapeDataFromCache,
discovered_channels: cachedChannels,
trigger: "manual",
pipeline_started_at: new Date().toISOString(),
})
.select("id")
.single();
runId = runRow?.id || null;
} catch (e) {
console.error("V3 dual-write error (clinics-cache):", e);
}
return new Response(
JSON.stringify({
success: true,
reportId: saved.id,
clinicId: cachedClinic.id,
runId,
clinicName: cachedClinic.name,
verifiedChannels: cachedChannels,
address: cachedClinic.address || "",
services: cachedClinic.services || [],
scrapeData: scrapeDataFromCache,
source: "clinics-cache",
}),
{ headers: { ...corsHeaders, "Content-Type": "application/json" } },
);
} else if (cachedClinic && !cacheFresh) {
console.log(`[clinics-cache] Stale for ${registryDomain} — re-running discovery`);
}
} catch (e) {
console.warn("[clinics-cache] Lookup failed, falling through to full discovery:", e instanceof Error ? e.message : e);
}
}
// ═══════════════════════════════════════════
// LEGACY FALLBACK: Full API discovery (disabled — registry-only mode)
// Kept for reference; unreachable in production
// FULL DISCOVERY: Firecrawl + extractSocialLinks + verifyHandles
// Runs for: unregistered domains, stale cache, or cache miss.
// Deterministic footer/link extraction (Source 1-3) is prioritized;
// Perplexity/Apify/Naver (Source 4-5) are AI fallbacks that only contribute
// when the regex path is empty. Everything that succeeds gets saved to
// `clinics.verified_channels` so the next run hits the cache fast-path above.
// ═══════════════════════════════════════════
const FIRECRAWL_API_KEY = Deno.env.get("FIRECRAWL_API_KEY") || "";
@@ -806,6 +905,19 @@ Deno.serve(async (req) => {
} catch { /* ignore secondary failure */ }
}
// Log deterministic vs AI contribution so we can see whether the footer
// scraping alone was sufficient for this clinic (the developer's hypothesis).
const deterministicCount =
(linkHandles.instagram?.length || 0) +
(linkHandles.youtube?.length || 0) +
(linkHandles.facebook?.length || 0) +
(linkHandles.naverBlog?.length || 0) +
(buttonHandles.instagram?.length || 0) +
(buttonHandles.youtube?.length || 0) +
(buttonHandles.facebook?.length || 0) +
(buttonHandles.naverBlog?.length || 0);
console.log(`[discover] ${registryDomain} — deterministic handles: ${deterministicCount}, final verified channels: ig=${(verified.instagram || []).length}, yt=${verified.youtube ? 1 : 0}, fb=${verified.facebook ? 1 : 0}, blog=${verified.naverBlog ? 1 : 0}`);
return new Response(
JSON.stringify({
success: true, reportId: saved.id,
@@ -815,6 +927,7 @@ Deno.serve(async (req) => {
address: clinic.address || "",
services: clinic.services || [],
scrapeData: scrapeDataFull,
source: "firecrawl-fallback",
}),
{ headers: { ...corsHeaders, "Content-Type": "application/json" } },
);