feat(supporters): 승인 UI·입력 반영·워커 — §7-5 ClinicInputsPanel + supporter_builds/inputs 마이그레이션 + apply_inputs, §12-2 상단 고지·개설자 승인·색인 빌드 필터, §7-6 워커 E2E(뷰성형외과 URL → 5편 → 게이트 0오류)

- 게이트: DISCLOSURE_TOP_MISSING, APPROVED_*, UNAPPROVED_IN_INDEXABLE_BUILD, PRESS_VOICE 규칙화, 픽스처 추가 (16/16)
- 생성기: --site 옵션, 병원 확인 답변(clinicAnswers) 근거 [A]
- default_briefs.mjs 첫 배치 자동 기획, workers/supporters-build/run.mjs
- 랜딩: SAMPLE REPORT 라벨 "실제 사례"로 (haewon 지시)
- v2 §11-6·§11-7 기록, E2E 리포트

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Haewon KamandClaude Fable 5.1 committed 2026-09-07 17:07:06 +09:00
1 parent 64a3bce9a3
commit 7e515b70ae
56 files changed
+2530 -41

No files matched your search

+141
View File
@@ -0,0 +1,141 @@
// 병원 확인 항목 입력(v2 §6, supporter_inputs) → 데이터 파일·글 frontmatter 반영. 멱등.
//
// node scripts/apply_inputs.mjs --clinic viewclinic --inputs inputs.json 로컬 파일 (배열 또는 {rows:[...]})
// node scripts/apply_inputs.mjs --clinic viewclinic --from-supabase SUPABASE_URL + SUPABASE_SERVICE_ROLE_KEY 로 조회
// --today YYYY-MM-DD --dry-run
//
// 행 형식: { clinic_id, key, post_id?, value, input_by?, created_at }
// author { name, role, sameAs[], email } → authors.supporters[site.editorId]
// editor { name, email } → site.editorId 사람 이름·corrections.owner/contact
// sponsorship { notice } → site.sponsorNotice (글 첫 부분 고지, §12-2)
// specialty_doctors { eye:'dr-x', nose:'dr-y', contour:..., lifting:..., anesthesia:... } → authors.physicians[id].specialty
// domain { domain, indexableFrom, homepageLinkPosition } → site.domain / site.indexableFrom / site.homepageLink
// quote_items · recovery · revision_policy · discrepancy → src/data/clinicAnswers.json (생성기 근거 [A], 화면 노출 없음)
// post_review post_id + { reviewer, reviewedAt } → frontmatter reviewer·reviewStatus=reviewed·reviewedAt + history
// post_approval post_id + { approvedBy, approvedAt } → frontmatter approvedBy·approvedAt + history (reviewed 전이면 거부)
// 같은 (key, post_id) 는 created_at 최신 행만 쓴다. 코드 수정 없이 데이터만으로 검토 완료·스키마가 켜지는 것이 목표(v2 §10).
import { readFileSync, writeFileSync, existsSync, readdirSync } from 'node:fs';
import { join, resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import yaml from 'js-yaml';
import * as R from './gate/rules.mjs';
const here = (p) => fileURLToPath(new URL(p, import.meta.url));
const SUP = here('../');
const args = process.argv.slice(2);
const opt = (k, d) => { const i = args.indexOf(`--${k}`); return i >= 0 && args[i + 1] && !args[i + 1].startsWith('--') ? args[i + 1] : d; };
const flag = (k) => args.includes(`--${k}`);
const clinic = opt('clinic', 'viewclinic');
const today = opt('today', new Date().toISOString().slice(0, 10));
const dryRun = flag('dry-run');
const DATA = join(SUP, 'src/data');
const POSTS = join(SUP, 'src/content/posts');
(function loadEnv() { let dir = SUP; for (let i = 0; i < 4; i++) { const p = join(dir, '.env'); if (existsSync(p)) for (const line of readFileSync(p, 'utf8').split('\n')) { const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/); if (m && !process.env[m[1]]) process.env[m[1]] = m[2].replace(/^["']|["']$/g, ''); } dir = dirname(dir); } })();
// ---------- 입력 읽기 ----------
async function loadRows() {
if (opt('inputs')) { const j = JSON.parse(readFileSync(resolve(opt('inputs')), 'utf8')); return Array.isArray(j) ? j : j.rows ?? []; }
if (flag('from-supabase')) {
const url = process.env.SUPABASE_URL ?? process.env.VITE_SUPABASE_URL; const key = process.env.SUPABASE_SERVICE_ROLE_KEY ?? process.env.VITE_SUPABASE_ANON_KEY;
if (!url || !key) throw new Error('SUPABASE_URL / SUPABASE_SERVICE_ROLE_KEY 없음');
const res = await fetch(`${url}/rest/v1/supporter_inputs?clinic_id=eq.${encodeURIComponent(clinic)}&order=created_at.asc`, { headers: { apikey: key, authorization: `Bearer ${key}` } });
if (!res.ok) throw new Error(`supabase ${res.status} ${await res.text()}`);
return await res.json();
}
throw new Error('--inputs <file> 또는 --from-supabase 가 필요합니다');
}
const rows = (await loadRows()).filter((r) => !r.clinic_id || r.clinic_id === clinic).sort((a, b) => String(a.created_at ?? '').localeCompare(String(b.created_at ?? '')));
const latest = new Map(); // key|post_id → row
for (const r of rows) latest.set(`${r.key}|${r.post_id ?? ''}`, r);
const get = (key, postId = '') => latest.get(`${key}|${postId}`)?.value;
// ---------- 데이터 파일 ----------
const readJson = (f) => JSON.parse(readFileSync(join(DATA, f), 'utf8'));
const authors = readJson('authors.json');
const site = readJson('site.json');
const corrections = existsSync(join(DATA, 'corrections.json')) ? readJson('corrections.json') : { items: [] };
const answers = existsSync(join(DATA, 'clinicAnswers.json')) ? readJson('clinicAnswers.json') : { _comment: '병원이 서면으로 확인해 준 답변. 생성기가 근거 [A]로 쓴다. 화면에는 직접 노출하지 않는다.', items: [] };
const changes = [];
const note = (s) => changes.push(s);
// 1. 작성자·편집 책임·정정 이메일
const author = get('author');
if (author) {
const id = site.editorId || Object.keys(authors.supporters ?? {})[0] || 'editor';
authors.supporters = authors.supporters ?? {};
const cur = authors.supporters[id] ?? {};
authors.supporters[id] = { ...cur, name: author.name ?? cur.name, role: author.role ?? cur.role, email: author.email ?? cur.email, sameAs: author.sameAs ?? cur.sameAs ?? [] };
site.editorId = id;
note(`author → supporters.${id} (${author.name})`);
}
const editor = get('editor');
if (editor) { corrections.owner = editor.name ?? corrections.owner; corrections.contact = editor.email ?? corrections.contact; note(`editor → corrections.owner/contact`); }
// 3. 지원 관계 문구 (글 첫 부분 고지)
const sponsorship = get('sponsorship');
if (sponsorship?.notice) { site.sponsorNotice = sponsorship.notice; note('sponsorship → site.sponsorNotice'); }
// 8. 진료 분야별 담당 원장
const spec = get('specialty_doctors');
if (spec) {
const LABEL = { eye: '눈성형', nose: '코성형', contour: '안면윤곽', lifting: '리프팅', breast: '가슴성형', anesthesia: '마취', revision: '재수술' };
for (const [field, id] of Object.entries(spec)) {
if (!id || !authors.physicians?.[id]) { note(`specialty_doctors.${field}: "${id}" 는 physicians 에 없음 (건너뜀)`); continue; }
authors.physicians[id].specialty = LABEL[field] ?? field;
note(`specialty_doctors.${field} → ${id}`);
}
}
// 9. 도메인·색인 시점·홈페이지 링크 위치
const domain = get('domain');
if (domain) { Object.assign(site, { domain: domain.domain ?? site.domain, indexableFrom: domain.indexableFrom ?? site.indexableFrom, homepageLink: domain.homepageLinkPosition ?? site.homepageLink }); note('domain → site.domain/indexableFrom/homepageLink'); }
// 4~7. 자유 답변 → clinicAnswers (근거 [A])
const QUESTION = { quote_items: '견적 기본 포함 항목과 결제 방식', recovery: '회복 일정표의 병원 확정값(출근 기준 등)', revision_policy: '재수술 정책(타원 수술 상담 가능 여부, 부위별 대기 기간)', discrepancy: '페이지 간 표기 불일치의 정답' };
for (const key of ['quote_items', 'recovery', 'revision_policy', 'discrepancy']) {
const v = get(key); if (!v) continue;
const row = latest.get(`${key}|`);
const item = { key, question: v.question ?? QUESTION[key], answer: typeof v === 'string' ? v : v.answer ?? JSON.stringify(v), at: String(row.created_at ?? today).slice(0, 10), by: row.input_by ?? '병원' };
answers.items = (answers.items ?? []).filter((x) => x.key !== key).concat(item);
note(`${key} → clinicAnswers`);
}
// 2. 글별 의학 검토 · 개설자 게시 승인 → frontmatter
const postFiles = existsSync(POSTS) ? readdirSync(POSTS).filter((f) => f.endsWith('.md')) : [];
for (const f of postFiles) {
const id = f.replace(/\.md$/, '');
const review = get('post_review', id); const approval = get('post_approval', id);
if (!review && !approval) continue;
const src = readFileSync(join(POSTS, f), 'utf8');
const { data, body } = R.parseMarkdown(src);
let changed = false;
if (review?.reviewer && review?.reviewedAt) {
if (!authors.physicians?.[review.reviewer]) { note(`${id}: reviewer "${review.reviewer}" 가 physicians 에 없음 (건너뜀)`); }
else if (data.reviewer !== review.reviewer || data.reviewedAt !== review.reviewedAt || data.reviewStatus !== 'reviewed') {
data.reviewer = review.reviewer; data.reviewedAt = review.reviewedAt; data.reviewStatus = 'reviewed'; data.dateModified = today;
data.history = [...(data.history ?? []), { date: review.reviewedAt, note: `담당 원장 의학 검토 완료 (${authors.physicians[review.reviewer].name})` }];
changed = true; note(`${id}: 의학 검토 ${review.reviewer} ${review.reviewedAt}`);
}
}
if (approval?.approvedBy && approval?.approvedAt) {
if (data.reviewStatus !== 'reviewed') note(`${id}: 의학 검토 전이라 게시 승인 보류`);
else if (data.approvedAt !== approval.approvedAt || data.approvedBy !== approval.approvedBy) {
data.approvedBy = approval.approvedBy; data.approvedAt = approval.approvedAt; data.dateModified = today;
data.history = [...(data.history ?? []), { date: approval.approvedAt, note: `게시 승인 (${approval.approvedBy})` }];
changed = true; note(`${id}: 게시 승인 ${approval.approvedBy} ${approval.approvedAt}`);
}
}
if (changed && !dryRun) writeFileSync(join(POSTS, f), `---\n${yaml.dump(data, { lineWidth: -1, noRefs: true, quotingType: '"' })}---\n${body.trim()}\n`);
}
// ---------- 저장 ----------
if (!dryRun) {
writeFileSync(join(DATA, 'authors.json'), JSON.stringify(authors, null, 2) + '\n');
writeFileSync(join(DATA, 'site.json'), JSON.stringify(site, null, 2) + '\n');
writeFileSync(join(DATA, 'corrections.json'), JSON.stringify(corrections, null, 2) + '\n');
writeFileSync(join(DATA, 'clinicAnswers.json'), JSON.stringify(answers, null, 2) + '\n');
}
console.log(`입력 ${rows.length}행 · 유효 ${latest.size}건 · 반영 ${changes.length}건${dryRun ? ' (dry-run)' : ''}`);
for (const c of changes) console.log(' ·', c);
+10
View File
@@ -23,6 +23,8 @@ const HOME_TEXT = existsSync(homeTextPath) ? readFileSync(homeTextPath, 'utf8')
const authors = JSON.parse(readFileSync(here('../src/data/authors.json'), 'utf8'));
const fact = JSON.parse(readFileSync(here('../src/data/factSheet.json'), 'utf8'));
const videos = JSON.parse(readFileSync(here('../src/data/videos.json'), 'utf8'));
const site = JSON.parse(readFileSync(here('../src/data/site.json'), 'utf8'));
const INDEXABLE = process.env.PUBLIC_INDEXABLE === 'true';
// 구조 기준선을 보는 페이지. 글 목록은 글 수에 따라 카드가 늘므로 집합 비교, 나머지는 순서 비교.
// 글 상세는 사전순 첫 글 하나를 대표로 본다(템플릿·다른 병원에서도 같은 규칙).
@@ -65,6 +67,14 @@ for (const f of files) {
add(rel, R.checkHomeDuplicate(text, HOME_TEXT));
add(rel, R.checkOperatorVocab(text, rel));
add(rel, R.checkHeadingEndings(html));
// §12-2 (1) 글 첫 부분 지원 고지. site.sponsorNotice 가 켜져 있으면 error, 아니면 warn
if (rel.startsWith('/posts/') && rel !== '/posts.html') add(rel, R.checkTopDisclosure(html, { required: Boolean(site.sponsorNotice) }));
// §12-2 (2) 색인 허용 빌드에 미승인 글이 섞이면 error
if (INDEXABLE && rel.startsWith('/posts/') && rel !== '/posts.html') {
const slug = rel.replace(/^\/posts\//, '').replace(/\.html$/, '');
const src = join(POSTS, `${slug}.md`);
if (existsSync(src) && !R.parseMarkdown(readFileSync(src, 'utf8')).data.approvedAt) add(rel, [{ level: R.E, code: 'UNAPPROVED_IN_INDEXABLE_BUILD', msg: '색인 허용 빌드인데 게시 승인(approvedAt) 없는 글이 포함됨' }]);
}
// 구조 지문
if (LAYOUT_PAGES[rel]) layoutNow[rel] = R.layoutFingerprint(html);
}
+78
View File
@@ -0,0 +1,78 @@
// 새 병원의 첫 배치 기획 목록(brief)을 근거 수집 결과에서 만든다 (v1 §3 Phase 4, v2 §3-11).
// 질문 뱅크 카테고리 7종 중 홈페이지 근거만으로 답할 수 있는 A·B·C·D·E 를 골라, 근거 페이지가 실제로 있는 것만 낸다.
// 사람 승인(§3-11 "기획 목록 승인")은 이 파일을 리포트 페이지에서 보고 확정하는 것으로 한다.
//
// node scripts/default_briefs.mjs --clinic <id> --evidence <evidence/<id>> --site <siteDir> [--out briefs.json] [--max 6]
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
import { join, resolve } from 'node:path';
const args = process.argv.slice(2);
const opt = (k, d) => { const i = args.indexOf(`--${k}`); return i >= 0 && args[i + 1] && !args[i + 1].startsWith('--') ? args[i + 1] : d; };
const clinic = opt('clinic'); const EV = resolve(opt('evidence', `../evidence/${clinic}`)); const SITE = resolve(opt('site', '.'));
const max = Number(opt('max', '6'));
if (!clinic || !existsSync(join(EV, 'index.json'))) { console.error('--clinic 과 --evidence <dir> (index.json 있는 폴더) 필요'); process.exit(2); }
const index = JSON.parse(readFileSync(join(EV, 'index.json'), 'utf8'));
const fact = JSON.parse(readFileSync(join(SITE, 'src/data/factSheet.json'), 'utf8'));
const authors = JSON.parse(readFileSync(join(SITE, 'src/data/authors.json'), 'utf8'));
const name = fact.shortName || fact.name || clinic;
const pages = index.pages.filter((p) => p.status === 200 && p.chars >= 200);
const byType = (t) => pages.filter((p) => p.type === t).sort((a, b) => b.chars - a.chars);
const urls = (...types) => types.flatMap((t) => byType(t).slice(0, 3).map((p) => p.url));
const physicianIds = Object.keys(authors.physicians ?? {});
const rep = physicianIds.find((id) => /대표/.test(authors.physicians[id].title ?? '')) ?? physicianIds[0];
const candidates = [
{
id: 'what-is-clinic', category: 'A', categoryLabel: '병원 소개', qbIds: ['A-02', 'A-05', 'A-07'],
title: `${name}은 어떤 병원인가요? 위치·진료 분야·의료진 구성`,
intent: '병원 소개·진료과·의료진 수·건물·위치를 사실만으로 정리한다. 수상·방송 이력은 홈페이지 텍스트에 있는 것만. 표 하나(진료 분야 × 담당 원장 수).',
need: ['about', 'doctor', 'direction'], pages: urls('about', 'doctor', 'facilities', 'direction'), reviewer: rep,
},
{
id: 'visit-guide', category: 'B', categoryLabel: '방문·예약', qbIds: ['B-01', 'B-03', 'B-05'],
title: `${name} 방문 안내: 위치·진료시간·주차·예약은 어떻게 하나요?`,
intent: '오시는길·진료시간·주차·예약 경로를 표로. 팩트 시트 값과 오시는길 페이지만 근거로. 확인되지 않은 시간은 "전화 확인".',
need: ['direction'], pages: urls('direction', 'reservation'), reviewer: null,
},
{
id: 'safety-system', category: 'E', categoryLabel: '안전·마취', qbIds: ['E-01', 'E-02', 'E-04'],
title: `${name}의 안전 시스템은 무엇으로 이루어져 있나요?`,
intent: '안전 시스템 페이지가 공개한 항목(마취 관리·응급 장비·검진·CCTV 등)을 항목 표로. 다른 병원·업계 평균과 비교하는 수치는 쓰지 않는다. 각 항목마다 상담에서 확인할 질문 하나.',
need: ['safety'], pages: urls('safety', 'checkup'), reviewer: physicianIds.find((id) => /마취/.test(authors.physicians[id].title ?? '')) ?? rep,
},
{
id: 'precautions-guide', category: 'D', categoryLabel: '시술 정보', qbIds: ['D-06', 'D-09'],
title: '수술 전·후 주의사항에서 꼭 지켜야 할 것은 무엇인가요?',
intent: '수술 전(약·금식·흡연)과 후(부기·샤워·운동·음주)의 시점을 부위 공통 항목 중심으로 표. 부위별로 다른 값은 부위를 명시. 개인차 조건 필수.',
need: ['precautions'], pages: urls('precautions', 'aftercare'), reviewer: rep,
},
{
id: 'consult-questions', category: 'C', categoryLabel: '선택 기준', qbIds: ['C-02', 'E-08'],
title: '상담에서 꼭 물어봐야 할 질문은 무엇인가요?',
intent: '안전·검진·애프터케어 페이지가 공개한 항목을 근거로 상담 질문 체크리스트 8~10개("- [ ]" 형식). 답을 적는 칸을 두고, 질문마다 왜 묻는지 한 줄.',
need: ['safety', 'aftercare'], pages: urls('safety', 'aftercare', 'checkup'), reviewer: rep,
},
{
id: 'aftercare-program', category: 'D', categoryLabel: '시술 정보', qbIds: ['D-08', 'E-06'],
title: '수술 후 관리 프로그램은 무엇이 포함되고 언제까지 이어지나요?',
intent: '애프터케어 페이지의 부위별 프로그램·기간을 표로. 견적 포함 여부는 "병원 확인 대기".',
need: ['aftercare'], pages: urls('aftercare', 'checkup'), reviewer: rep,
},
];
const posts = candidates
.filter((c) => c.need.every((t) => byType(t).length) && c.pages.length)
.slice(0, max)
.map(({ need, pages: pg, reviewer, ...c }) => ({
...c,
avoid: ['전후 사진', '가격 금액', '다른 병원·업계 평균 비교', '효과 보장', '환자 경험담'],
reviewerCandidate: reviewer ?? undefined,
evidence: { pages: [...new Set(pg)], shorts: [], news: [], regulation: [], platform: false },
videos: [], gallery: [],
}));
const out = { clinic, generatedAt: new Date().toISOString().slice(0, 10), note: '근거 수집 결과에서 자동 제안한 첫 배치. 사람이 확인·수정한 뒤 생성기에 넣는다(v2 §3-11).', posts };
const outPath = resolve(opt('out', join(SITE, 'briefs.json')));
writeFileSync(outPath, JSON.stringify(out, null, 2) + '\n');
console.log(`brief ${posts.length}편 → ${outPath}${posts.length < candidates.length ? ` (근거 부족으로 제외 ${candidates.length - posts.length}편: ${candidates.filter((c) => !posts.find((p) => p.id === c.id)).map((c) => c.id).join(', ')})` : ''}`);
@@ -0,0 +1,12 @@
---
expect: [APPROVED_WITHOUT_BY, APPROVED_BEFORE_REVIEW]
approvedAt: "2026-09-07"
reviewStatus: pending
---
## 게시 승인 필드 검사
이 픽스처는 승인자 없이, 의학 검토 전에 게시 승인이 찍힌 경우입니다. 상담에서 확인하세요.
| 구분 | 내용 |
|---|---|
| 항목 | 값 |
+23 -1
View File
@@ -112,7 +112,7 @@ export function checkSourcesType(data) {
}
/** FDA·ISO·승인·연구 주장이 있으면 regulation 타입 원문 소스가 있어야 한다. 학회명(연구회·연구소)은 제외. */
export const REGULATION_CLAIM = /FDA|ISO\s?\d|승인|연구(?!회|소|원|팀|실)/;
export const REGULATION_CLAIM = /FDA|ISO\s?\d|(?<!게시\s?)승인(?!자|일)|연구(?!회|소|원|팀|실)/; // "게시 승인"(§12-2 개설자 승인)은 규제 주장이 아니다
export function checkRegulationSource(data, fields) {
const hasReg = (data.sources ?? []).some((s) => s.type === 'regulation');
if (hasReg) return [];
@@ -214,9 +214,30 @@ export function checkReview(data, physicians = {}, supporters = {}) {
if (!data.reviewer) out.push(r(E, 'REVIEWED_WITHOUT_REVIEWER', 'reviewStatus=reviewed 인데 reviewer 없음'));
if (!data.reviewedAt) out.push(r(E, 'REVIEWED_WITHOUT_DATE', 'reviewStatus=reviewed 인데 reviewedAt 없음'));
}
// 게시 승인(v2 §12-2): 승인일이 있으면 승인자(개설자·직함)도 있어야 하고, 의학 검토가 끝난 글만 승인할 수 있다.
if (data.approvedAt && !data.approvedBy) out.push(r(E, 'APPROVED_WITHOUT_BY', 'approvedAt 이 있는데 approvedBy(승인자) 없음'));
if (data.approvedBy && !data.approvedAt) out.push(r(E, 'APPROVED_WITHOUT_DATE', 'approvedBy 가 있는데 approvedAt 없음'));
if (data.approvedAt && data.reviewStatus !== 'reviewed') out.push(r(E, 'APPROVED_BEFORE_REVIEW', '의학 검토(reviewed) 전에 게시 승인됨'));
return out;
}
// ---------- §12-2 (3) 기자·전문가 화법 (의료법 56조 2항 10호 대응). 경고 수준 ----------
export const PRESS_VOICE = /본지|기자(?!회견)|전문가에 따르면|업계에서는|업계 관계자/;
export function checkPressVoice(text, field = '') {
const m = text.match(PRESS_VOICE);
return m ? [r(W, 'PRESS_VOICE', `${field ? field + ': ' : ''}기자·전문가 화법: "${m[0]}"`)] : [];
}
// ---------- §12-2 (1) 지원 관계 고지의 상단 배치 ----------
/** 글 페이지 HTML 에서 상단 고지(.disclosure-top)가 세 줄 요약(.summary) 앞에 있어야 한다. notice 가 비어 있으면(아직 미승인) 경고만. */
export function checkTopDisclosure(html, { required = false } = {}) {
const top = html.search(/class="[^"]*disclosure-top[^"]*"/);
const summary = html.search(/class="[^"]*\bsummary\b[^"]*"/);
if (top >= 0 && (summary < 0 || top < summary)) return [];
const level = required ? E : W;
return [r(level, 'DISCLOSURE_TOP_MISSING', top < 0 ? '글 첫 부분에 지원 관계 고지 없음 (site.sponsorNotice 를 채우면 렌더됨)' : '지원 관계 고지가 세 줄 요약보다 아래에 있음')];
}
// ---------- §3-8 싣지 않는 것 ----------
export const BANNED_VIDEO_TITLE = /전후|리뷰|성공|번호따|변신|역대급/;
export function checkVideoTitles(list, { level = E, label = '' } = {}) {
@@ -280,5 +301,6 @@ export function checkPostSource({ data, body }, { physicians, supporters } = {})
...checkVideoTitles([...(data.videos ?? []), ...(data.video ? [data.video] : [])], { label: 'frontmatter' }),
...checkOriginalContent(data, body),
...fields.flatMap((f) => checkPlainEndings(f.text, f.field)),
...fields.flatMap((f) => checkPressVoice(f.text, f.field)),
];
}
+8 -1
View File
@@ -56,7 +56,7 @@ const SOURCE_TYPE_LABEL = { clinic: '병원 제공', doctor: '원장 설명', pr
* brief 하나에 대한 컨텍스트 문자열과 sources 배열을 만든다.
* brief.evidence = { pages: [url], shorts: [videoId], transcripts: [{id,title,speaker,text}], news: [url], regulation: [{label,url,note}], platform: bool }
*/
export function buildContext(brief, { ev, fact, authors, videos, news, today }) {
export function buildContext(brief, { ev, fact, authors, videos, news, answers, today }) {
const parts = [];
const missing = [];
const sources = [];
@@ -111,6 +111,13 @@ export function buildContext(brief, { ev, fact, authors, videos, news, today })
});
parts.push(`## 4. 규제·연구 원문\n\n${rparts.length ? rparts.join('\n\n') : '(규제·연구 근거 없음. FDA·ISO·승인·연구를 언급하지 않는다)'}`);
// 4b. 병원이 서면으로 확인해 준 답변 (apply_inputs → clinicAnswers.json). §6 4~7항. 병원 제공 근거로 친다.
const aparts = (answers?.items ?? []).map((a, i) => `### [A${i + 1}] ${a.question ?? a.key} (병원 확인 ${a.at}${a.by ? `, ${a.by}` : ''})\n${a.answer}`);
if (aparts.length) {
parts.push(`## 4b. 병원 확인 답변 (병원이 서면으로 확인한 값. "병원 확인 기준"으로 인용한다)\n\n${aparts.join('\n\n')}`);
pushSource({ label: `${clinicName} 서면 확인 답변 (${(answers.items.at(-1)?.at) ?? today})`, url: fact?.url ?? '', accessed: today, type: 'clinic' });
}
// 5. 팩트 시트 (플랫폼 집계 포함)
if (fact) {
const slim = { ...fact };
-5
View File
@@ -8,9 +8,6 @@ export function toMarkdown(data, body) {
return `---\n${fm}---\n${String(body).trim()}\n`;
}
/** 기자·전문가 화법 (v2 §12-2 (3), 의료법 56조 2항 10호 대응). 경고 수준. */
export const PRESS_VOICE = /본지|기자(?!회견)|전문가에 따르면|업계에서는|업계 관계자/;
/**
* 글 한 편의 소스 수준 게이트. dist 없이 frontmatter·본문만 본다.
* 반환 { errors, warns, stats }. errors 가 있으면 발행 불가.
@@ -43,8 +40,6 @@ export function gatePost(md, { physicians = {}, supporters = {}, homeText = '' }
const tableCount = (body.match(/^\|\s*:?-+/gm) ?? []).length;
if (!tableCount) findings.push({ level: R.W, code: 'NO_TABLE', msg: '본문에 표가 없음 (1개 이상 권장)' });
if (!/\?\s*$/.test(String(data.title ?? '')) && !/(표|목록|체크리스트|기록)\s*$/.test(String(data.title ?? ''))) findings.push({ level: R.W, code: 'TITLE_NOT_QUESTION', msg: `제목이 질문형이 아님: "${data.title}"` });
const press = fullText.match(PRESS_VOICE);
if (press) findings.push({ level: R.W, code: 'PRESS_VOICE', msg: `기자·전문가 화법: "${press[0]}"` });
const desc = String(data.description ?? '');
if (desc.length < 60 || desc.length > 200) findings.push({ level: R.W, code: 'DESCRIPTION_LENGTH', msg: `description ${desc.length}자 (90~160자 권장)` });
+6 -3
View File
@@ -62,14 +62,17 @@ function loadEnv() {
loadEnv();
// ---------- 데이터 ----------
const DATA = join(SUP, 'src/data');
const POSTS = join(SUP, 'src/content/posts');
// --site <dir> : 다른 사이트 디렉터리(템플릿 복제본)의 데이터·글을 쓴다. 워커가 병원별 작업 폴더로 돌릴 때.
const SITE = resolve(opt('site', SUP));
const DATA = join(SITE, 'src/data');
const POSTS = join(SITE, 'src/content/posts');
const EV = resolve(opt('evidence', join(SUP, '..', 'evidence', clinic)));
const readJson = (p) => JSON.parse(readFileSync(p, 'utf8'));
const fact = readJson(join(DATA, 'factSheet.json'));
const authors = readJson(join(DATA, 'authors.json'));
const videos = readJson(join(DATA, 'videos.json'));
const news = existsSync(join(DATA, 'news.json')) ? readJson(join(DATA, 'news.json')) : { items: [] };
const answers = existsSync(join(DATA, 'clinicAnswers.json')) ? readJson(join(DATA, 'clinicAnswers.json')) : { items: [] };
if (!existsSync(join(EV, 'index.json'))) { console.error(`근거 없음: ${EV}. 먼저 node scripts/collect_evidence.mjs --clinic ${clinic} --url <홈>`); process.exit(1); }
const ev = loadEvidence(EV);
const authorId = opt('author', Object.keys(authors.supporters ?? {})[0]);
@@ -252,7 +255,7 @@ for (const brief of briefs) {
report.posts.push(row);
if (shouldStop({ spentUsd: spent })) { row.status = 'skipped_cost_cap'; console.log(` – ${brief.id}: 비용 상한 도달, 건너뜀`); continue; }
const ctx = buildContext(brief, { ev, fact, authors, videos, news, today });
const ctx = buildContext(brief, { ev, fact, authors, videos, news, answers, today });
row.missingEvidence = ctx.missing;
row.contextChars = ctx.text.length;
const reviewerName = brief.reviewerCandidate && authors.physicians?.[brief.reviewerCandidate]?.name;
@@ -0,0 +1,4 @@
{
"_comment": "병원이 서면으로 확인해 준 답변(v2 §6 4~7항). apply_inputs.mjs 가 채우고 생성기가 근거 [A]로 쓴다. 화면에는 직접 노출하지 않는다.",
"items": []
}
+2 -1
View File
@@ -20,5 +20,6 @@
"arrivalGuide": "",
"visitReads": [],
"newsNote": "",
"newsOutletsExample": ""
"newsOutletsExample": "",
"sponsorNotice": ""
}