feat(dental-journals): 논문 종류 필터 — RCT·임상시험·체계적 문헌고찰·메타분석·리뷰·관찰연구·증례보고·가이드라인(PubMed [pt], 복수 선택 OR, 저널·검색어와 AND), 선택 기억, 채팅 컨텍스트에 반영

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Sonnet 5.5 committed 2026-10-05 12:53:26 +09:00
1 parent 76c6790110
commit 1896e2a12f
2 files changed
+42 -9

No files matched your search

+22 -4
View File
@@ -18,6 +18,18 @@ export const DENTAL_JOURNALS: { id: string; short: string; name: string; ta: str
{ id: 'jcd', short: 'J Conserv Dent', name: 'Journal of Conservative Dentistry', ta: 'J Conserv Dent', area: '보존치의학' },
];
// 논문 종류 필터 — PubMed [pt](Publication Type). 여러 개를 고르면 OR, 저널·검색어와는 AND.
export const PAPER_TYPES: { id: string; label: string; pt: string }[] = [
{ id: 'rct', label: 'RCT', pt: 'Randomized Controlled Trial' },
{ id: 'ct', label: '임상시험', pt: 'Clinical Trial' },
{ id: 'sr', label: '체계적 문헌고찰', pt: 'Systematic Review' },
{ id: 'ma', label: '메타분석', pt: 'Meta-Analysis' },
{ id: 'review', label: '리뷰', pt: 'Review' },
{ id: 'obs', label: '관찰연구', pt: 'Observational Study' },
{ id: 'case', label: '증례보고', pt: 'Case Reports' },
{ id: 'guide', label: '가이드라인', pt: 'Practice Guideline' },
];
// 저널 제한 없이 PubMed 전체를 검색하는 소스. 켜면 저널 카드와 무관하게 전체 범위(치과 외 논문도 섞임).
export const PUBMED_ALL = { id: 'pubmed', short: 'PubMed', name: 'PubMed 전체', area: '저널 제한 없음' };
@@ -38,7 +50,7 @@ export function journalShort(abbr: string, full: string): string {
export function registerDentalJournalRoutes(app: express.Application, requireGatewayAuth: express.RequestHandler): void {
app.get('/api/dental-journals/list', requireGatewayAuth, (_req, res) => {
res.json({ journals: [...DENTAL_JOURNALS.map(({ id, short, name, area }) => ({ id, short, name, area })), PUBMED_ALL] });
res.json({ journals: [...DENTAL_JOURNALS.map(({ id, short, name, area }) => ({ id, short, name, area })), PUBMED_ALL], types: PAPER_TYPES.map(({ id, label }) => ({ id, label })) });
});
// GET /api/dental-journals/search?journal=all|joe,jad,…&q=&sub=&min_year=&sort=relevance|date&offset=&max=
@@ -65,11 +77,17 @@ export function registerDentalJournalRoutes(app: express.Application, requireGat
const subs = await Promise.all(rawSubs.map(x => toPaperSearchQuery(x)));
const parts = [q, ...subs].filter(Boolean);
const queryText = parts.map(x => `(${x})`).join(' AND ');
const typeIds = String(req.query.types || '').split(',').map(x => x.trim()).filter(Boolean);
const pickedTypes = PAPER_TYPES.filter(t => typeIds.includes(t.id));
if (typeIds.length && pickedTypes.length !== new Set(typeIds).size) { res.status(400).json({ error: `알 수 없는 논문 종류: ${typeIds.filter(x => !PAPER_TYPES.some(t => t.id === x)).join(', ')}` }); return; }
const typeClause = pickedTypes.length ? '(' + pickedTypes.map(t => `"${t.pt}"[pt]`).join(' OR ') + ')' : '';
const journalClause = '(' + picked.map(j => `"${j.ta}"[ta]`).join(' OR ') + ')';
// 사용자가 쓴 PubMed 문법(AND/OR 등)이 우선순위를 망치지 않도록 괄호로 감싼다.
// PubMed 전체가 켜져 있으면 저널 조건을 걸지 않는다(저널 논문도 모두 포함되는 상위 집합).
const term = wholePubmed ? queryText : (queryText ? `${queryText} AND ${journalClause}` : journalClause);
if (!term) { res.status(400).json({ error: 'PubMed 전체 검색은 검색어가 필요합니다.' }); return; }
const base = wholePubmed ? queryText : (queryText ? `${queryText} AND ${journalClause}` : journalClause);
// 논문 종류는 저널·검색어 조건에 AND로 덧붙인다(종류만 골라도 선택한 저널의 해당 종류 논문이 나온다).
const term = typeClause ? (base ? `${base} AND ${typeClause}` : typeClause) : base;
if (!term || (wholePubmed && !queryText)) { res.status(400).json({ error: 'PubMed 전체 검색은 검색어가 필요합니다.' }); return; }
const maxResults = Math.min(Math.max(Number(req.query.max) || 20, 1), 50);
const offset = Math.max(Number(req.query.offset) || 0, 0);
@@ -85,7 +103,7 @@ export function registerDentalJournalRoutes(app: express.Application, requireGat
translated: !!q && q !== rawQ,
subs_used: subs,
// 모델 채팅이 앱과 똑같은 결과를 pubmed_search로 재현·페이징할 수 있도록 실제 검색식을 돌려준다.
term, sort, min_year: minYear ?? null,
term, sort, min_year: minYear ?? null, types: pickedTypes.map(t => t.id),
total: r.data?.total_count ?? 0,
offset,
results: (r.data?.results ?? []).map((a: any) => ({ ...a, journal_short: journalShort(a.journal_abbr, a.journal) })),
+20 -5
View File
@@ -29,6 +29,10 @@ button:disabled{opacity:.5;cursor:default}
.b-j{background:rgba(99,102,241,.18);color:var(--brand2)}.b-pmc{background:rgba(34,197,94,.18);color:var(--green)}.b-t{background:rgba(251,191,36,.18);color:#b88a0c}
.links{margin-top:6px;display:flex;gap:12px;flex-wrap:wrap;font-size:12px}
.links a,.links button{color:var(--brand2);background:none;border:0;cursor:pointer;font-size:12px;text-decoration:none;padding:0}
.tchips{display:flex;flex-wrap:wrap;gap:6px;align-items:center;margin-bottom:10px}
.tchips .tl{font-size:12px;color:var(--muted);font-weight:600;margin-right:2px}
.tchip{border:1px solid var(--line);background:var(--panel);color:var(--muted);border-radius:14px;padding:4px 11px;font-size:12px;font-weight:600;cursor:pointer}
.tchip.on{border-color:var(--green);color:var(--green);background:rgba(34,197,94,.12)}
.subrow{display:none;gap:8px;flex-wrap:wrap;align-items:center;margin-bottom:10px;padding:8px 10px;background:var(--panel2);border:1px dashed var(--line);border-radius:var(--r)}
.subrow input{flex:1;min-width:180px;background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:6px 9px;font-size:13px;color:var(--text)}
.subrow button.add{background:var(--brand);color:#fff;border:0;border-radius:8px;padding:6px 12px;font-weight:600;cursor:pointer;font-size:13px}
@@ -76,6 +80,7 @@ button:disabled{opacity:.5;cursor:default}
<div class="layout">
<main>
<div class="chips" id="chips"></div>
<div class="tchips" id="tchips" title="논문 종류 — 여러 개를 고르면 OR, 비우면 전체"></div>
<div class="row">
<input id="q" placeholder="검색어 (한국어도 OK, 비우면 선택한 저널의 최신 논문)" onkeydown="if(event.key==='Enter')newSearch()">
<input id="yr" type="number" placeholder="연도~" min="1990" max="2100">
@@ -111,13 +116,13 @@ button:disabled{opacity:.5;cursor:default}
<script>
const $=id=>document.getElementById(id);
const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
let lastInfo=null, shown=[], journals=[], sel=new Set(), offset=0, total=0, busy=false, pending=false, baseQ='', subs=[];
let ptypes=[], tsel=new Set(), lastInfo=null, shown=[], journals=[], sel=new Set(), offset=0, total=0, busy=false, pending=false, baseQ='', subs=[];
async function init(){
loadBudget();
try{
const d=await (await fetch('/api/dental-journals/list',{credentials:'include'})).json();
journals=d.journals||[];
journals=d.journals||[]; ptypes=d.types||[];
}catch(e){ $('status').textContent='저널 목록 로드 실패: '+e.message; }
let saved=null;
try{ saved=JSON.parse(localStorage.getItem('dj-sel')||'null'); }catch(e){}
@@ -129,9 +134,17 @@ async function init(){
if(Array.isArray(saved)) ids.filter(x=>x!=='pubmed'&&!known.includes(x)).forEach(x=>sel.add(x));
try{ localStorage.setItem('dj-known',JSON.stringify(ids)); }catch(e){}
if(Array.isArray(saved)) saveSel();
renderChips();
try{ const t=JSON.parse(localStorage.getItem('dj-types')||'[]'); if(Array.isArray(t)) tsel=new Set(t.filter(x=>ptypes.some(p=>p.id===x))); }catch(e){}
renderChips(); renderTypes();
doSearch(true);
}
function renderTypes(){
$('tchips').innerHTML='<span class="tl">논문 종류</span>'
+ptypes.map(t=>`<button class="tchip ${tsel.has(t.id)?'on':''}" onclick="toggleType('${t.id}')" aria-pressed="${tsel.has(t.id)}">${tsel.has(t.id)?'✔ ':''}${esc(t.label)}</button>`).join('')
+(tsel.size?'<button class="tchip" onclick="clearTypes()">✕ 전체</button>':'');
}
function toggleType(id){ tsel.has(id)?tsel.delete(id):tsel.add(id); try{ localStorage.setItem('dj-types',JSON.stringify([...tsel])); }catch(e){} renderTypes(); doSearch(true); }
function clearTypes(){ tsel.clear(); try{ localStorage.setItem('dj-types','[]'); }catch(e){} renderTypes(); doSearch(true); }
function renderChips(){
const dj=journals.filter(j=>j.id!=='pubmed'); const djOn=dj.filter(j=>sel.has(j.id)).length; const allOn=dj.length&&djOn===dj.length;
$('chips').innerHTML=`<button class="chip ${allOn?'on':''}" onclick="toggleAll()">${allOn?'전체 해제':'전체 선택'}<small>치과 저널 ${djOn}/${dj.length}개 켜짐</small></button>`
@@ -172,15 +185,17 @@ async function doSearch(reset){
try{
const p=new URLSearchParams({journal:[...sel].join(','),q:baseQ,sort:$('sort').value,offset,max:20});
subs.forEach(x=>p.append('sub',x));
if(tsel.size) p.set('types',[...tsel].join(','));
if($('yr').value){ const y=Number($('yr').value); if(!Number.isInteger(y)||y<1800||y>2100) throw new Error('연도는 1800~2100 사이의 숫자여야 합니다.'); p.set('min_year',y); }
const r=await fetch('/api/dental-journals/search?'+p,{credentials:'include'});
const d=await r.json();
if(!r.ok) throw new Error(d.error||r.status);
total=d.total; offset+=d.results.length; shown.push(...d.results); lastInfo={q:baseQ,qEn:d.query_used,subs:[...subs],sources:[...sel],total,term:d.term,sort:d.sort,minYear:d.min_year};
total=d.total; offset+=d.results.length; shown.push(...d.results); lastInfo={q:baseQ,qEn:d.query_used,subs:[...subs],sources:[...sel],total,term:d.term,sort:d.sort,minYear:d.min_year,types:(d.types||[]).map(id=>(ptypes.find(t=>t.id===id)||{}).label||id)};
$('results').insertAdjacentHTML('beforeend',d.results.map(card).join(''));
let s=`${total.toLocaleString()}건 중 ${offset}건 표시`;
if(sel.has('pubmed')) s+=' · PubMed 전체 포함(치과 외 논문 섞임, 저널 카드 무관)';
if(subs.length) s+=` · 좁힘: ${subs.join(' + ')}`;
if(tsel.size) s+=` · 종류: ${ptypes.filter(t=>tsel.has(t.id)).map(t=>t.label).join(' / ')}`;
if(d.translated) s+=` · 검색어 변환: “${d.query_used}”`;
if(!d.results.length && reset) s='결과 없음';
$('status').textContent=s;
@@ -269,7 +284,7 @@ function buildContext(){
L.push('규칙: ⓪논문 목록·검색은 web_search가 아니라 pubmed_search로 한다. ①한국어로 답하되 전문용어는 영어 병기. ②번역 요청이면 요약하지 말고 원문에 충실하게 문장 단위로 번역. ③아래 초록/목록에 없는 내용(수치·결론)을 지어내지 말 것 — 모자라면 "초록에는 없다"고 말하고, 필요하면 pubmed_fetch / pubmed_fulltext(PMC 전문) / openalex_search 도구로 확인. ④논문을 언급할 때 PMID를 붙일 것(목록 번호 1,2,…가 아니라 PMID로). ⑤임상 조언은 근거 수준(RCT/SR/in vitro 등)을 함께 밝힐 것. ⑥치의학 용어는 한국 치과 관용어로 옮긴다 — restoration=수복, postoperative sensitivity=수복 후(술후) 민감증("수술 후"로 옮기지 말 것), caries=치아우식, pulp=치수, root canal=근관, bulk-fill=벌크필 레진, adhesive=접착제/접착 시스템, bond strength=접착 강도. ⑦목록을 정리·요약할 때는 실제로 본 건수(아래 "화면에 표시된" 목록)와 전체 검색 건수를 구분해서 말하고, 못 본 논문까지 정리한 것처럼 쓰지 말 것.');
if(lastInfo){
const names=lastInfo.sources.map(id=>(journals.find(j=>j.id===id)||{}).short||id).join(', ');
L.push(`현재 검색: 소스=${names||'없음'} / 검색어="${lastInfo.q||'(없음, 최신순)'}"${lastInfo.qEn&&lastInfo.qEn!==lastInfo.q?` (영문 변환 "${lastInfo.qEn}")`:''}${lastInfo.subs.length?` / 결과 내 좁힘=${lastInfo.subs.join(' + ')}`:''} / 총 ${lastInfo.total}건 중 ${shown.length}건 로드됨`);
L.push(`현재 검색: 소스=${names||'없음'} / 검색어="${lastInfo.q||'(없음, 최신순)'}"${lastInfo.qEn&&lastInfo.qEn!==lastInfo.q?` (영문 변환 "${lastInfo.qEn}")`:''}${lastInfo.subs.length?` / 결과 내 좁힘=${lastInfo.subs.join(' + ')}`:''}${lastInfo.types&&lastInfo.types.length?` / 논문 종류=${lastInfo.types.join('·')}(검색식에 이미 반영됨)`:''} / 총 ${lastInfo.total}건 중 ${shown.length}건 로드됨`);
}
if(lastInfo&&lastInfo.term){
const pages=Math.max(1,Math.ceil(lastInfo.total/200)), offs=Array.from({length:Math.min(pages,3)},(_,i)=>i*200).join(', ');