/* ═══════════════════════════════════════════════════════════ 노코딩 Python+ — Frontend Application Logic ═══════════════════════════════════════════════════════════ */ 'use strict'; // ────────────────────────────────────────────────────────────── // State // ────────────────────────────────────────────────────────────── const state = { currentStep: 1, sessionId: null, fileName: null, dfInfo: null, // 컬럼 정보 저장 currentJobId: null, pendingJobId: null, completedJobs: [], }; let analysisMode = 'structured'; // 'structured' | 'free' // ────────────────────────────────────────────────────────────── // 분석 유형 설정 (사회과학 연구 전용) // ────────────────────────────────────────────────────────────── const ANALYSIS_TYPES = [ { id: 'descriptive', label: '📊 기술통계', desc: '평균·표준편차·분포 요약', vars: [ { key: 'targets', label: '분석할 수치형 변수', type: 'numeric', multi: true } ], build(v) { return `다음 수치형 변수들의 기술통계를 분석해주세요: ${v.targets.join(', ')}. 평균, 표준편차, 최솟값, 최댓값, 중앙값, 왜도, 첨도를 포함한 표와 히스토그램, 박스플롯을 그려주세요.`; } }, { id: 'ttest', label: '📈 독립표본 t-검정', desc: '두 집단의 평균 비교', vars: [ { key: 'group', label: '집단 변수 (범주형)', type: 'categorical', multi: false }, { key: 'target', label: '종속 변수 (수치형)', type: 'numeric', multi: false } ], build(v) { return `${v.group} 변수를 기준으로 두 집단의 ${v.target} 평균 차이를 독립표본 t-검정으로 분석해주세요. 각 집단의 기술통계, Levene 등분산 검정, t통계량, p값, Cohen's d 효과크기를 포함하고 집단별 박스플롯을 그려주세요.`; } }, { id: 'paired_ttest', label: '🔄 대응표본 t-검정', desc: '사전-사후 평균 비교', vars: [ { key: 'pre', label: '사전 변수 (수치형)', type: 'numeric', multi: false }, { key: 'post', label: '사후 변수 (수치형)', type: 'numeric', multi: false } ], build(v) { return `${v.pre}(사전)과 ${v.post}(사후)의 평균 차이를 대응표본 t-검정으로 분석해주세요. 기술통계, t통계량, p값, Cohen's d 효과크기를 포함하고 사전-사후 변화 시각화를 그려주세요.`; } }, { id: 'anova', label: '📉 일원배치 ANOVA', desc: '세 집단 이상의 평균 비교', vars: [ { key: 'group', label: '집단 변수 (범주형)', type: 'categorical', multi: false }, { key: 'target', label: '종속 변수 (수치형)', type: 'numeric', multi: false } ], build(v) { return `${v.group} 변수를 기준으로 ${v.target}의 집단 간 평균 차이를 일원배치 ANOVA로 분석해주세요. F통계량, p값, 사후검정(Tukey HSD), 효과크기(η²)를 포함하고 집단별 박스플롯을 그려주세요.`; } }, { id: 'correlation', label: '🔗 상관분석', desc: '변수 간 Pearson 상관관계', vars: [ { key: 'targets', label: '분석할 수치형 변수들', type: 'numeric', multi: true } ], build(v) { return `다음 변수들 간의 Pearson 상관분석을 실시해주세요: ${v.targets.join(', ')}. 상관계수 행렬표(r값, p값 포함)와 상관행렬 히트맵을 제공해주세요.`; } }, { id: 'regression', label: '📐 회귀분석', desc: '종속~독립 변수 예측 관계', vars: [ { key: 'dependent', label: '종속 변수 (수치형)', type: 'numeric', multi: false }, { key: 'independents', label: '독립 변수들 (수치형, 다중)', type: 'numeric', multi: true } ], build(v) { return `${v.dependent}를 종속변수로, ${v.independents.join(', ')}를 독립변수로 하는 다중회귀분석을 실시해주세요. R², 수정 R², F통계량, p값, 각 독립변수의 비표준화 계수(B), 표준화 계수(β), t값, p값을 포함해주세요.`; } }, { id: 'frequency', label: '📋 빈도분석', desc: '범주형 변수 분포', vars: [ { key: 'target', label: '분석할 범주형 변수', type: 'categorical', multi: false } ], build(v) { return `${v.target} 변수의 빈도분석을 실시해주세요. 빈도표(빈도, 백분율, 누적백분율)와 막대그래프를 제공해주세요.`; } }, { id: 'crosstab', label: '📊 교차분석 (χ²)', desc: '두 범주형 변수의 관계', vars: [ { key: 'var1', label: '변수 1 (범주형)', type: 'categorical', multi: false }, { key: 'var2', label: '변수 2 (범주형)', type: 'categorical', multi: false } ], build(v) { return `${v.var1}과 ${v.var2}의 교차분석을 실시해주세요. 교차표, 카이제곱 통계량, p값, Cramér's V 효과크기를 포함하고 누적 막대그래프를 그려주세요.`; } }, { id: 'reliability', label: '🔐 신뢰도 분석 (Cronbach α)', desc: '척도 문항의 내적 일관성', vars: [ { key: 'items', label: '척도 문항들 (수치형, 다중선택)', type: 'numeric', multi: true } ], build(v) { return `다음 문항들로 구성된 척도의 신뢰도 분석(Cronbach α)을 실시해주세요: ${v.items.join(', ')}. 전체 Cronbach α값, 각 문항 제거 시 α값 변화, 문항-전체 상관계수를 포함한 결과표를 제공해주세요.`; } } ]; // ────────────────────────────────────────────────────────────── // Init // ────────────────────────────────────────────────────────────── document.addEventListener('DOMContentLoaded', () => { checkApiHealth(); restoreSession(); setupDropZone(); setupQueryInput(); }); // ────────────────────────────────────────────────────────────── // API health check // ────────────────────────────────────────────────────────────── async function checkApiHealth() { try { const res = await fetch('/api/health'); const data = await res.json(); const dot = document.getElementById('apiDot'); const txt = document.getElementById('apiStatusText'); if (data.api_key_configured) { dot.className = 'dot'; txt.textContent = 'Claude API 연결됨'; } else { dot.className = 'dot error'; txt.textContent = 'API 키 미설정'; showToast('⚠️ ANTHROPIC_API_KEY가 설정되지 않았습니다. .env 파일을 확인하세요.', 6000); } } catch { document.getElementById('apiDot').className = 'dot error'; document.getElementById('apiStatusText').textContent = '서버 연결 실패'; } } // ────────────────────────────────────────────────────────────── // Session persistence // ────────────────────────────────────────────────────────────── function saveSession() { try { localStorage.setItem('ncp_session', JSON.stringify({ sessionId: state.sessionId, fileName: state.fileName, currentStep: state.currentStep, completedJobs: state.completedJobs, })); } catch {} } async function restoreSession() { try { const raw = localStorage.getItem('ncp_session'); if (!raw) return; const saved = JSON.parse(raw); if (!saved.sessionId) return; const res = await fetch(`/api/session/${saved.sessionId}`); if (!res.ok) { localStorage.removeItem('ncp_session'); return; } state.sessionId = saved.sessionId; state.fileName = saved.fileName; state.completedJobs = saved.completedJobs || []; showFileMeta(saved.fileName, null); document.getElementById('btnToPreview').disabled = false; const step = Math.min(saved.currentStep || 1, 4); if (step >= 3) await loadPreview(); if (step >= 4) rebuildChatHistory(); goToStep(step, true); } catch { localStorage.removeItem('ncp_session'); } } // ────────────────────────────────────────────────────────────── // Step navigation // ────────────────────────────────────────────────────────────── function goToStep(step, skipSave = false) { document.querySelectorAll('.content-section').forEach(s => s.classList.remove('active')); document.getElementById(`section-${step}`).classList.add('active'); document.querySelectorAll('.step-item').forEach(el => { const n = parseInt(el.dataset.step); el.classList.remove('active', 'done', 'clickable'); if (n < step) { el.classList.add('done', 'clickable'); el.onclick = () => goToStep(n); } if (n === step) el.classList.add('active'); }); state.currentStep = step; if (!skipSave) saveSession(); if (step === 3 && state.sessionId) loadPreview(); if (step === 4) { document.getElementById('chatFileName').textContent = state.fileName ? `— ${state.fileName}` : ''; // 구조화 분석 패널 렌더링 setTimeout(() => renderStructuredPanel(), 50); } if (step === 5) renderDownloadSection(); window.scrollTo({ top: 0, behavior: 'smooth' }); } // ────────────────────────────────────────────────────────────── // File upload — drag & drop setup // ────────────────────────────────────────────────────────────── function setupDropZone() { const zone = document.getElementById('dropZone'); const input = document.getElementById('fileInput'); input.addEventListener('change', () => { if (input.files[0]) handleUpload(input.files[0]); }); zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('dragover'); }); zone.addEventListener('dragleave', () => zone.classList.remove('dragover')); zone.addEventListener('drop', e => { e.preventDefault(); zone.classList.remove('dragover'); const f = e.dataTransfer.files[0]; if (f) handleUpload(f); }); } async function handleUpload(file) { const ext = file.name.split('.').pop().toLowerCase(); if (!['xlsx', 'xls', 'csv'].includes(ext)) { showAlert('alertUpload', 'error', `지원하지 않는 파일 형식입니다 (.${ext}). xlsx, xls, csv 파일만 가능합니다.`); return; } if (file.size > 50 * 1024 * 1024) { showAlert('alertUpload', 'error', `파일 크기가 너무 큽니다 (${(file.size/1024/1024).toFixed(1)} MB). 최대 50 MB입니다.`); return; } clearAlert('alertUpload'); document.getElementById('uploadingIndicator').classList.remove('hidden'); document.getElementById('fileMeta').classList.add('hidden'); document.getElementById('btnToPreview').disabled = true; const form = new FormData(); form.append('file', file); try { const res = await fetch('/api/upload', { method: 'POST', body: form }); const data = await res.json(); if (!res.ok) { showAlert('alertUpload', 'error', data.detail || '업로드 실패'); return; } state.sessionId = data.session_id; state.fileName = data.file_name; state.completedJobs = []; saveSession(); showFileMeta(data.file_name, `${data.rows.toLocaleString()}행 × ${data.cols}열 · ${data.size_mb} MB`); document.getElementById('btnToPreview').disabled = false; showToast(`✅ "${data.file_name}" 업로드 완료!`); } catch { showAlert('alertUpload', 'error', '서버와 통신 중 오류가 발생했습니다. 다시 시도해주세요.'); } finally { document.getElementById('uploadingIndicator').classList.add('hidden'); } } function showFileMeta(name, stats) { const icons = { xlsx: '📊', xls: '📊', csv: '📋' }; const ext = (name || '').split('.').pop().toLowerCase(); document.getElementById('fileIconSpan').textContent = icons[ext] || '📄'; document.getElementById('uploadedFileName').textContent = name || '—'; document.getElementById('uploadedFileStats').textContent = stats || ''; document.getElementById('fileMeta').classList.remove('hidden'); } // ────────────────────────────────────────────────────────────── // Sample data // ────────────────────────────────────────────────────────────── async function loadSampleData() { const btn = document.getElementById('btnSample'); btn.disabled = true; btn.textContent = '⏳ 로딩 중…'; try { const res = await fetch('/api/sample/load'); const data = await res.json(); if (!res.ok) { showToast('샘플 데이터 로드 실패: ' + (data.detail || '')); return; } state.sessionId = data.session_id; state.fileName = data.file_name; state.completedJobs = []; saveSession(); showFileMeta(data.file_name, `${data.rows.toLocaleString()}행 × ${data.cols}열 · 샘플 데이터`); document.getElementById('btnToPreview').disabled = false; showToast('✅ 샘플 데이터 로드 완료! 미리보기로 이동합니다.'); goToStep(3); } catch { showToast('샘플 데이터 로드 중 오류가 발생했습니다.'); } finally { btn.disabled = false; btn.textContent = '✨ 샘플 데이터로 체험하기'; } } // ────────────────────────────────────────────────────────────── // Data preview // ────────────────────────────────────────────────────────────── async function loadPreview() { if (!state.sessionId) return; try { const res = await fetch(`/api/preview/${state.sessionId}`); const data = await res.json(); if (!res.ok) return; state.dfInfo = data.df_info; // ← 컬럼 정보 저장 renderMetaGrid(data.df_info); renderColBadges(data.df_info); renderColAccordion(data.df_info); renderPreviewTable(data.df_info, data.preview); // 이미 분석 단계에 있다면 패널 갱신 if (state.currentStep === 4) renderStructuredPanel(); } catch {} } function renderMetaGrid(info) { const [rows, cols] = info.shape; const numCols = info.columns.filter(c => c.type === '수치형').length; const catCols = info.columns.filter(c => c.type === '범주형').length; document.getElementById('metaGrid').innerHTML = `
${rows.toLocaleString()}
전체 행 수
${cols}
전체 열 수
${numCols}
수치형 변수
${catCols}
범주형 변수
${info.missing_cols}
결측치 포함 열
`; } function renderColBadges(info) { const counts = { 수치형: 0, 범주형: 0, 문자형: 0, 날짜형: 0 }; info.columns.forEach(c => { if (counts[c.type] !== undefined) counts[c.type]++; }); const map = { 수치형: 'num', 범주형: 'cat', 문자형: 'text', 날짜형: 'date' }; const labels = { 수치형: '수치형', 범주형: '범주형', 문자형: '문자형', 날짜형: '날짜형' }; let html = ''; for (const [k, v] of Object.entries(counts)) { if (v > 0) html += `${labels[k]} ${v}개`; } if (info.missing_cols > 0) html += `결측치 포함 ${info.missing_cols}열`; document.getElementById('colBadges').innerHTML = html; } function renderColAccordion(info) { const badgeClass = { 수치형: 'badge-num', 범주형: 'badge-cat', 문자형: 'badge-text', 날짜형: 'badge-date' }; const rows = info.columns.map(c => { const bc = badgeClass[c.type] || 'badge-text'; const missStr = c.missing > 0 ? `결측 ${c.missing}개 (${c.missing_pct}%)` : ''; const sampleStr = c.sample.slice(0, 5) .map(s => `${escHtml(String(s))}`) .join(' '); return ` ${escHtml(c.name)} ${c.type} ${c.unique.toLocaleString()} ${missStr || '—'} ${sampleStr} `; }).join(''); document.getElementById('colInfoAccordion').innerHTML = `
▶ 컬럼 상세 정보 (${info.columns.length}개)
${rows}
컬럼명 유형 고유값 결측치 샘플값
`; } function renderPreviewTable(info, preview) { if (!preview || preview.length === 0) { document.getElementById('previewTableWrap').innerHTML = '

데이터가 없습니다.

'; return; } const badgeClass = { 수치형: 'badge-num', 범주형: 'badge-cat', 문자형: 'badge-text', 날짜형: 'badge-date' }; const colMap = Object.fromEntries(info.columns.map(c => [c.name, c])); const cols = Object.keys(preview[0]); const ths = cols.map(col => { const meta = colMap[col]; const bc = meta ? (badgeClass[meta.type] || 'badge-text') : 'badge-text'; return `${escHtml(col)}${meta ? meta.type : ''}`; }).join(''); const trs = preview.map(row => `${cols.map(c => `${escHtml(String(row[c]))}`).join('')}` ).join(''); document.getElementById('previewTableWrap').innerHTML = ` ${ths}${trs}
`; } // ────────────────────────────────────────────────────────────── // 구조화 분석 패널 // ────────────────────────────────────────────────────────────── function renderStructuredPanel() { // .suggestions 자리에 구조화 패널 주입 const suggestionsEl = document.querySelector('.suggestions'); if (!suggestionsEl) return; if (!state.dfInfo) { suggestionsEl.innerHTML = '

데이터를 먼저 업로드해주세요.

'; return; } const typeOptions = ANALYSIS_TYPES.map(t => `` ).join(''); suggestionsEl.innerHTML = `
`; // 직접 입력 모드에서는 textarea 표시 const inputRow = document.querySelector('.chat-input-row'); if (inputRow) { inputRow.style.display = analysisMode === 'free' ? '' : 'none'; } } function setMode(mode) { analysisMode = mode; renderStructuredPanel(); } function updateVarSelectors(typeId) { const area = document.getElementById('varSelectorArea'); const notesArea = document.getElementById('additionalNotesArea'); const submitBtn = document.getElementById('btnStructuredSubmit'); if (!typeId || !state.dfInfo) { if (area) area.innerHTML = ''; if (notesArea) notesArea.style.display = 'none'; if (submitBtn) { submitBtn.disabled = true; submitBtn.style.opacity = '0.5'; } return; } const type = ANALYSIS_TYPES.find(t => t.id === typeId); if (!type) return; const numCols = state.dfInfo.columns.filter(c => c.type === '수치형').map(c => c.name); const catCols = state.dfInfo.columns.filter(c => c.type === '범주형').map(c => c.name); let html = ''; type.vars.forEach(v => { const cols = v.type === 'numeric' ? numCols : catCols; const colOptions = cols.map(col => `` ).join(''); if (cols.length === 0) { html += `
⚠️ ${escHtml(v.label)}: ${v.type === 'numeric' ? '수치형' : '범주형'} 변수가 없습니다.
`; return; } if (v.multi) { html += `
`; } else { html += `
`; } }); area.innerHTML = html; if (notesArea) notesArea.style.display = ''; if (submitBtn) { submitBtn.disabled = false; submitBtn.style.opacity = '1'; } } function buildQueryFromStructured() { const typeId = document.getElementById('analysisTypeSelect').value; const type = ANALYSIS_TYPES.find(t => t.id === typeId); if (!type) return null; const vars = {}; let valid = true; type.vars.forEach(v => { const el = document.getElementById(`var-${v.key}`); if (!el) { valid = false; return; } if (v.multi) { const selected = Array.from(el.selectedOptions).map(o => o.value).filter(Boolean); if (selected.length === 0) { valid = false; return; } vars[v.key] = selected; } else { if (!el.value) { valid = false; return; } vars[v.key] = el.value; } }); if (!valid) return null; let query = type.build(vars); const notes = document.getElementById('additionalNotes'); if (notes && notes.value.trim()) { query += ` 추가 요청: ${notes.value.trim()}`; } return query; } function submitStructuredAnalysis() { const query = buildQueryFromStructured(); if (!query) { showToast('⚠️ 분석 유형과 변수를 모두 선택해주세요.'); return; } _doSendAnalysis(query); } // ────────────────────────────────────────────────────────────── // Analysis — unified send // ────────────────────────────────────────────────────────────── function setupQueryInput() { const input = document.getElementById('queryInput'); input.addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendAnalysis(); } }); } // 직접 입력 전송 async function sendAnalysis() { const input = document.getElementById('queryInput'); const query = input.value.trim(); if (!query) return; input.value = ''; await _doSendAnalysis(query); } // 내부 공통 전송 로직 async function _doSendAnalysis(query) { if (!state.sessionId) { showToast('먼저 파일을 업로드해주세요.'); return; } if (state.pendingJobId) { showToast('이전 분석이 진행 중입니다. 잠시 기다려주세요.'); return; } // 입력 잠금 document.getElementById('queryInput').disabled = true; document.getElementById('btnSend').disabled = true; const sb = document.getElementById('btnStructuredSubmit'); if (sb) { sb.disabled = true; sb.style.opacity = '0.5'; } appendUserMessage(query); const statusId = appendStatusMessage('Claude가 분석 계획을 수립 중입니다…'); try { const res = await fetch('/api/analyze', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ session_id: state.sessionId, query, job_id: state.currentJobId || null, }), }); const data = await res.json(); if (!res.ok) { updateStatusMessage(statusId, '❌ ' + (data.detail || '요청 실패')); unlockInput(); return; } state.pendingJobId = data.job_id; pollJob(data.job_id, statusId, query); } catch { updateStatusMessage(statusId, '❌ 서버와 통신 중 오류가 발생했습니다.'); unlockInput(); } } function unlockInput() { document.getElementById('queryInput').disabled = false; document.getElementById('btnSend').disabled = false; const sb = document.getElementById('btnStructuredSubmit'); if (sb) { sb.disabled = false; sb.style.opacity = '1'; } if (analysisMode === 'free') document.getElementById('queryInput').focus(); } // ────────────────────────────────────────────────────────────── // Job polling // ────────────────────────────────────────────────────────────── const STATUS_LABELS = { pending: '분석 요청 대기 중…', generating_code: 'Claude가 Python 코드를 생성 중…', executing: '코드 실행 중… (최대 120초)', completed: '✅ 분석 완료!', error: '❌ 오류 발생', }; async function pollJob(jobId, statusId, query) { let attempts = 0; const maxAttempts = 90; const tick = async () => { try { const res = await fetch(`/api/job/${jobId}`); const job = await res.json(); attempts++; updateStatusMessage(statusId, STATUS_LABELS[job.status] || job.status); if (job.status === 'completed') { state.pendingJobId = null; state.currentJobId = jobId; state.completedJobs.push({ jobId, query, results: job.results, files: job.files || [] }); saveSession(); renderResults(job); document.getElementById('btnToDownload').disabled = false; unlockInput(); showToast('분석이 완료되었습니다!'); } else if (job.status === 'error') { state.pendingJobId = null; appendSystemMessage(`❌ ${job.error || '알 수 없는 오류'}`); unlockInput(); } else if (attempts < maxAttempts) { setTimeout(tick, 2000); } else { state.pendingJobId = null; appendSystemMessage('⏰ 응답 시간이 초과되었습니다. 다시 시도해주세요.'); unlockInput(); } } catch { if (attempts < maxAttempts) setTimeout(tick, 3000); else { state.pendingJobId = null; appendSystemMessage('⚠️ 서버 연결이 끊어졌습니다.'); unlockInput(); } } }; setTimeout(tick, 1000); } // ────────────────────────────────────────────────────────────── // Results rendering // ────────────────────────────────────────────────────────────── function renderResults(job) { const r = job.results || {}; document.getElementById('resultsEmpty').classList.add('hidden'); document.getElementById('resultsTabs').classList.remove('hidden'); document.getElementById('summaryContent').innerHTML = `
✅
${escHtml(r.summary || '분석이 완료되었습니다.')}
${r.method ? `
통계 기법: ${escHtml(r.method)}
` : ''} ${r.preprocessing && r.preprocessing.length ? `
전처리 내역
` : ''} ${r.log ? `
⚠️
${escHtml(r.log)}
` : ''}`; if (r.tables && r.tables.length) { document.getElementById('tablesContent').innerHTML = r.tables.map(t => `
${escHtml(t.title || '')}
${t.html || ''}
`).join('
'); } else { document.getElementById('tablesContent').innerHTML = '

이번 분석에서는 표 결과가 없습니다.

'; } if (r.charts && r.charts.length) { document.getElementById('chartsContent').innerHTML = r.charts.map(f => `${escHtml(f)}` ).join(''); } else { document.getElementById('chartsContent').innerHTML = '

이번 분석에서는 그래프가 생성되지 않았습니다.

'; } document.getElementById('interpContent').innerHTML = r.interpretation ? `
${escHtml(r.interpretation).replace(/\n/g, '
')}
` : '

해석 정보가 없습니다.

'; const codeHtml = job.code ? `
실행된 Python 코드
Python 코드 보기 (${(job.code.match(/\n/g)||[]).length + 1}줄)
${escHtml(job.code)}
` : ''; const prepHtml = r.preprocessing && r.preprocessing.length ? `
전처리 내역
${r.preprocessing.map(p => `${escHtml(p)}`).join('')}
` : ''; const methodHtml = r.method ? `
사용 통계 기법
${escHtml(r.method)}
` : ''; const pkgHtml = r.packages && r.packages.length ? `
사용 패키지
${r.packages.map(p => `${escHtml(p)}`).join('')}
` : ''; const errHtml = job.stderr ? `
오류 로그
${escHtml(job.stderr.slice(0, 2000))}
` : ''; document.getElementById('logContent').innerHTML = codeHtml + prepHtml + methodHtml + pkgHtml + errHtml || '

로그 정보가 없습니다.

'; if (r.charts && r.charts.length) switchTab('charts'); else if (r.tables && r.tables.length) switchTab('tables'); else switchTab('summary'); document.getElementById('resultStatus').innerHTML = `✓ 완료`; scrollChat(); } // ────────────────────────────────────────────────────────────── // Tab switching // ────────────────────────────────────────────────────────────── function switchTab(name) { document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active')); document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('active')); const btns = document.querySelectorAll('.tab-btn'); const tabMap = { summary: 0, tables: 1, charts: 2, interpretation: 3, log: 4 }; if (btns[tabMap[name]]) btns[tabMap[name]].classList.add('active'); const pane = document.getElementById(`tab-${name}`); if (pane) pane.classList.add('active'); } // ────────────────────────────────────────────────────────────── // Download section // ────────────────────────────────────────────────────────────── function renderDownloadSection() { if (!state.completedJobs.length) { document.getElementById('downloadSections').innerHTML = '
ℹ️
아직 완료된 분석이 없습니다. 먼저 분석을 수행해주세요.
'; return; } const iconMap = { png: '🖼', xlsx: '📊', csv: '📋', txt: '📝', json: '⚙️' }; const typeMap = { png: '그래프 이미지', xlsx: 'Excel 파일', csv: 'CSV 데이터', txt: '텍스트 파일', json: 'JSON 데이터' }; const html = state.completedJobs.map((job, idx) => { if (!job.files || !job.files.length) return ''; const items = job.files.map(f => { const ext = f.split('.').pop().toLowerCase(); return `
${iconMap[ext] || '📄'}
${escHtml(f)}
${typeMap[ext] || '파일'}
⬇ 다운로드
`; }).join(''); return `
분석 ${idx + 1}: ${escHtml(job.query.length > 80 ? job.query.slice(0,80)+'…' : job.query)}
${items}
`; }).join('
'); document.getElementById('downloadSections').innerHTML = html || '

다운로드할 파일이 없습니다.

'; } // ────────────────────────────────────────────────────────────── // Chat helpers // ────────────────────────────────────────────────────────────── function appendUserMessage(text) { const now = new Date().toLocaleTimeString('ko-KR', { hour: '2-digit', minute: '2-digit' }); const div = document.createElement('div'); div.className = 'msg user'; div.innerHTML = `
${escHtml(text.length > 200 ? text.slice(0,200)+'…' : text)}
${now}
`; document.getElementById('chatMessages').appendChild(div); scrollChat(); } function appendStatusMessage(text) { const id = 'status-' + Date.now(); const div = document.createElement('div'); div.className = 'msg-status'; div.id = id; div.innerHTML = `
${escHtml(text)}`; document.getElementById('chatMessages').appendChild(div); scrollChat(); return id; } function updateStatusMessage(id, text) { const el = document.getElementById(id); if (!el) return; el.innerHTML = `
${escHtml(text)}`; scrollChat(); } function appendSystemMessage(text) { const div = document.createElement('div'); div.className = 'msg system'; div.innerHTML = `
${escHtml(text)}
`; document.getElementById('chatMessages').appendChild(div); scrollChat(); } function rebuildChatHistory() { const container = document.getElementById('chatMessages'); if (state.completedJobs.length === 0) return; state.completedJobs.forEach(job => { const ud = document.createElement('div'); ud.className = 'msg user'; ud.innerHTML = `
${escHtml(job.query.length > 200 ? job.query.slice(0,200)+'…' : job.query)}
`; container.appendChild(ud); const sd = document.createElement('div'); sd.className = 'msg system'; sd.innerHTML = `
✅ 분석이 완료되었습니다. 결과 패널을 확인하세요.
`; container.appendChild(sd); }); const lastJob = state.completedJobs[state.completedJobs.length - 1]; if (lastJob) { state.currentJobId = lastJob.jobId; renderResults({ job_id: lastJob.jobId, results: lastJob.results, files: lastJob.files, code: null, stderr: null }); document.getElementById('btnToDownload').disabled = false; } } function scrollChat() { const msgs = document.getElementById('chatMessages'); msgs.scrollTop = msgs.scrollHeight; } // ────────────────────────────────────────────────────────────── // Alert helpers // ────────────────────────────────────────────────────────────── function showAlert(containerId, type, msg) { const icons = { info: 'ℹ️', warn: '⚠️', success: '✅', error: '❌' }; document.getElementById(containerId).innerHTML = `
${icons[type] || ''}
${escHtml(msg)}
`; } function clearAlert(containerId) { document.getElementById(containerId).innerHTML = ''; } // ────────────────────────────────────────────────────────────── // Toast notification // ────────────────────────────────────────────────────────────── let toastTimer = null; function showToast(msg, duration = 3500) { const toast = document.getElementById('toast'); toast.textContent = msg; toast.style.transform = 'translateY(0)'; toast.style.opacity = '1'; clearTimeout(toastTimer); toastTimer = setTimeout(() => { toast.style.transform = 'translateY(100px)'; toast.style.opacity = '0'; }, duration); } // ────────────────────────────────────────────────────────────── // Utilities // ────────────────────────────────────────────────────────────── function escHtml(str) { return String(str) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"'); }