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
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user