feat(dental-journals): 분류 결과 저장 — CSV(엑셀, BOM)·마크다운·RIS(EndNote/Zotero) 브라우저 다운로드, 초록 포함·제외 논문 포함 옵션

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Sonnet 5.5 committed 2026-10-05 12:59:55 +09:00
1 parent 784a3c1168
commit ff53d6694e
1 file changed
+79 -2
+79 -2
View File
@@ -44,6 +44,9 @@ button:disabled{opacity:.5;cursor:default}
#clsgo{background:var(--brand);color:#fff;border:0;border-radius:8px;padding:8px 12px;font-weight:700;cursor:pointer}
#clsgo:disabled{opacity:.55;cursor:default}
#clsstat{font-size:12px;color:var(--muted)}
#clsdl{background:var(--green);color:#fff;border:0;border-radius:8px;padding:5px 12px;font-weight:700;cursor:pointer;font-size:12.5px}
#clsdl:disabled{opacity:.55}
#clssave{padding:7px 9px;border:1px dashed var(--line);border-radius:8px;background:var(--panel2)}
.cgrp{border:1px solid var(--line);border-radius:9px;background:var(--panel2);overflow:hidden}
.cgrp.ex{opacity:.85}
.cgrp>summary{cursor:pointer;padding:7px 10px;font-size:13px;font-weight:700;list-style:none;display:flex;gap:6px;align-items:center}
@@ -150,6 +153,13 @@ button:disabled{opacity:.5;cursor:default}
<div class="clsrow"><label for="clsmax">그룹 수 최대</label><select id="clsmax" style="width:auto"><option>3</option><option>4</option><option selected>5</option><option>6</option><option>8</option></select>
<button id="clsgo" onclick="runCls()">🗂 분류 실행</button></div>
<div id="clsstat"></div>
<div id="clssave" style="display:none">
<div class="clsrow"><b style="font-size:12.5px">📥 저장</b>
<select id="clsfmt" style="width:auto"><option value="csv">CSV (엑셀)</option><option value="md">마크다운</option><option value="ris">RIS (EndNote·Zotero)</option></select>
<label><input type="checkbox" id="clsabs"> 초록 포함</label>
<label><input type="checkbox" id="clsex" checked> 제외 논문 포함</label>
<button id="clsdl" onclick="clsDownload()">저장</button></div>
</div>
<div id="clsout"></div>
</div>
<div id="quick">
@@ -449,7 +459,7 @@ async function runCls(){
if(!list.length){ $('clsstat').textContent=kind==='pinned'?'지정한 논문이 없습니다. 카드의 💬 대화로 지정하세요.':'표시된 논문이 없습니다. 먼저 검색하세요.'; return; }
const by=$('clsby').value, custom=$('clscustom').value.trim(), cond=$('clscond').value.trim(), maxG=Number($('clsmax').value)||5;
if(by==='custom'&&!custom){ $('clsstat').textContent='직접 입력 기준을 적어 주세요.'; return; }
clsBusy=true; $('clsgo').disabled=true; clsClearFilter(); $('clsout').innerHTML='';
clsBusy=true; $('clsgo').disabled=true; clsClearFilter(); $('clsout').innerHTML=''; $('clssave').style.display='none';
try{
let res, src;
if(by==='design'&&!cond){ res=designGroups(list); src='PubMed 논문 유형으로 즉시 분류(모델 호출 없음)'; }
@@ -480,7 +490,7 @@ function renderCls(src){
let h=clsRes.groups.map((g,i)=>grp(g,i,false)).join('');
if(clsRes.excluded.length){ h+=`<details class="cgrp ex" open><summary>🚫 조건 제외 <small>${clsRes.excluded.length}건</small></summary><div class="cd">분류 조건에 맞지 않아 제외한 논문</div>`
+clsRes.excluded.map(e=>{const a=byP.get(e.pmid); return a?`<div class="cpaper" onclick="clsGoto('${a.pmid}')"><b>${esc(a.title)}</b><small>${esc(e.reason)} · PMID ${esc(a.pmid)}</small></div>`:'';}).join('')+'</details>'; }
$('clsout').innerHTML=h;
$('clsout').innerHTML=h; $('clssave').style.display='block';
$('clsstat').textContent=`${clsRes.groups.length}개 그룹 · ${src}${clsRes.cond?' · 조건: '+clsRes.cond.slice(0,40):''}`;
}
function clsGoto(pmid){
@@ -501,6 +511,73 @@ function clsFilterGroup(i){
}
function clsClearFilter(){ clsFilterIdx=-1; document.querySelectorAll('#results .card.hide-cls').forEach(c=>c.classList.remove('hide-cls')); $('clsfilter').style.display='none'; }
// ───────── 분류 결과 저장 (CSV / 마크다운 / RIS) ─────────
function dlText(name,text,mime){ const b=new Blob([text],{type:mime||'text/plain;charset=utf-8'}); const a=document.createElement('a'); a.href=URL.createObjectURL(b); a.download=name; document.body.appendChild(a); a.click(); a.remove(); setTimeout(()=>URL.revokeObjectURL(a.href),3000); }
const csvCell=v=>{ v=String(v??'').replace(/\r?\n/g,' ').trim(); return /[",\n]/.test(v)?'"'+v.replace(/"/g,'""')+'"':v; };
function clsRows(withEx){
const byP=new Map(clsRes.list.map(a=>[a.pmid,a])), rows=[];
clsRes.groups.forEach(g=>g.pmids.forEach(p=>{ const a=byP.get(p); if(a) rows.push({group:g.name,desc:g.desc,a,reason:''}); }));
if(withEx) clsRes.excluded.forEach(e=>{ const a=byP.get(e.pmid); if(a) rows.push({group:'조건 제외',desc:'분류 조건에 맞지 않아 제외',a,reason:e.reason}); });
return rows;
}
async function clsFetchAbstracts(rows,onProg){
const ids=[...new Set(rows.map(r=>r.a.pmid))].filter(p=>!(p in absCache)); let done=0;
const worker=async()=>{ while(ids.length){ const p=ids.shift(); try{ const d=await (await fetch('/api/dental-journals/abstract?pmid='+p,{credentials:'include',headers:authH()})).json(); absCache[p]=d.abstract||''; }catch(e){ absCache[p]=''; } onProg(++done); } };
await Promise.all([worker(),worker(),worker()]);
}
function clsMeta(){
const li=lastInfo||{}; const src=(li.sources||[]).map(id=>(journals.find(j=>j.id===id)||{}).short||id).join(', ');
return {date:new Date().toLocaleString('ko-KR',{hour12:false}), q:li.q||'', qEn:li.qEn||'', src, types:(li.types||[]).join('·'), by:clsRes.by==='custom'?($('clscustom').value.trim()||'직접 입력'):(CLS_BY_LABEL[clsRes.by]||clsRes.by), cond:clsRes.cond||'', term:li.term||''};
}
function buildCsv(rows,withAbs){
const head=['그룹','PMID','제목','저자','저널','연도','논문 유형','DOI','PubMed 링크'].concat(withAbs?['초록']:[]).concat(['제외 이유']);
const L=[head.map(csvCell).join(',')];
for(const r of rows){ const a=r.a, doi=(a.doi||'').replace(/^doi:\s*/i,'');
const cells=[r.group,a.pmid,a.title,a.authors,a.journal_short||a.journal,a.year,a.pub_types,doi,'https://pubmed.ncbi.nlm.nih.gov/'+a.pmid+'/'].concat(withAbs?[absCache[a.pmid]||'']:[]).concat([r.reason]);
L.push(cells.map(csvCell).join(',')); }
return ''+L.join('\r\n')+'\r\n'; // BOM: 엑셀에서 한글이 깨지지 않게
}
function buildMd(rows,withAbs){
const m=clsMeta(), L=[`# 치과 저널 논문 분류`,'',`- 저장: ${m.date}`,`- 검색어: ${m.q||'(없음)'}${m.qEn&&m.qEn!==m.q?` → ${m.qEn}`:''}`,`- 소스: ${m.src}${m.types?` · 논문 종류: ${m.types}`:''}`,`- 분류 기준: ${m.by}${m.cond?` · 조건: ${m.cond}`:''}`,m.term?`- PubMed 검색식: \`${m.term.slice(0,300)}\``:'',''].filter(x=>x!==undefined);
const groups=[]; for(const r of rows){ let g=groups.find(x=>x.name===r.group); if(!g){ g={name:r.group,desc:r.desc,items:[]}; groups.push(g); } g.items.push(r); }
for(const g of groups){ L.push(`## ${g.name} (${g.items.length}건)`,''); if(g.desc) L.push(`> ${g.desc}`,'');
for(const r of g.items){ const a=r.a, doi=(a.doi||'').replace(/^doi:\s*/i,'');
L.push(`- **${a.title}** `,` ${a.authors||'저자 미상'} — ${a.journal_short||a.journal} ${a.year} — [PMID ${a.pmid}](https://pubmed.ncbi.nlm.nih.gov/${a.pmid}/)${doi?` · [DOI](https://doi.org/${doi})`:''}${a.pub_types?` · ${a.pub_types}`:''}`);
if(r.reason) L.push(` - 제외 이유: ${r.reason}`);
if(withAbs&&absCache[a.pmid]) L.push(` - 초록: ${absCache[a.pmid].replace(/\s+/g,' ')}`); }
L.push(''); }
return L.join('\n');
}
function buildRis(rows,withAbs){
const L=[];
for(const r of rows){ const a=r.a, doi=(a.doi||'').replace(/^doi:\s*/i,'');
L.push('TY - JOUR','TI - '+a.title);
String(a.authors||'').replace(/\s*et al\.?$/i,'').split(/,\s*/).filter(Boolean).forEach(x=>L.push('AU - '+x));
L.push('JO - '+(a.journal_short||a.journal),'JF - '+a.journal,'PY - '+a.year);
if(doi) L.push('DO - '+doi);
L.push('AN - '+a.pmid,'UR - https://pubmed.ncbi.nlm.nih.gov/'+a.pmid+'/','KW - '+r.group);
L.push('N1 - 분류: '+r.group+(r.reason?' (제외 이유: '+r.reason+')':''));
if(withAbs&&absCache[a.pmid]) L.push('AB - '+absCache[a.pmid].replace(/\s+/g,' '));
L.push('ER - ',''); }
return L.join('\r\n');
}
async function clsDownload(){
if(!clsRes){ return; }
const fmt=$('clsfmt').value, withAbs=$('clsabs').checked, rows=clsRows($('clsex').checked);
if(!rows.length){ $('clsstat').textContent='저장할 논문이 없습니다.'; return; }
$('clsdl').disabled=true;
try{
if(withAbs){ const need=[...new Set(rows.map(r=>r.a.pmid))].filter(p=>!(p in absCache)).length; if(need){ $('clsstat').textContent=`초록 불러오는 중… (0/${need})`; await clsFetchAbstracts(rows,n=>{ $('clsstat').textContent=`초록 불러오는 중… (${n}/${need})`; }); } }
const day=new Date().toISOString().slice(0,10).replace(/-/g,''), q=((lastInfo&&lastInfo.q)||'분류').replace(/[\\/:*?"<>|\s]+/g,'_').slice(0,30);
const base=`치과저널-분류-${day}-${q}`;
if(fmt==='csv') dlText(base+'.csv',buildCsv(rows,withAbs),'text/csv;charset=utf-8');
else if(fmt==='md') dlText(base+'.md',buildMd(rows,withAbs),'text/markdown;charset=utf-8');
else dlText(base+'.ris',buildRis(rows,withAbs),'application/x-research-info-systems');
$('clsstat').textContent=`💾 ${rows.length}건을 ${fmt.toUpperCase()}로 저장했습니다 (${base}.${fmt})`;
}catch(e){ $('clsstat').textContent='저장 실패: '+e.message; }
finally{ $('clsdl').disabled=false; }
}
function md(src){
let t=esc(src);
t=t.replace(/```([\s\S]*?)```/g,(_,c)=>`<pre>${c.replace(/^\w*\n/,'')}</pre>`);