refactor: SQL 쿼리 관리 모듈화 및 메일 관리 UI/UX 고도화

This commit is contained in:
2026-03-17 14:27:25 +09:00
parent 74f11d3bd4
commit d0b33edea8
22 changed files with 851 additions and 1324 deletions

View File

@@ -197,7 +197,7 @@ function scrollToProject(name) {
p = p.parentElement;
}
target.parentElement.classList.add('active');
const pos = target.getBoundingClientRect().top + window.pageYOffset - 220;
const pos = target.getBoundingClientRect().top + window.pageYOffset - 260;
window.scrollTo({ top: pos, behavior: 'smooth' });
target.style.backgroundColor = 'var(--primary-lv-1)';
setTimeout(() => target.style.backgroundColor = '', 2000);

View File

@@ -1,15 +1,6 @@
async function loadInquiries() {
// Adjust sticky thead position based on header height
const header = document.getElementById('stickyHeader');
const thead = document.querySelector('.inquiry-table thead');
if (header && thead) {
const headerHeight = header.offsetHeight;
const totalOffset = 36 + headerHeight; // topbar(36) + sticky header height
document.querySelectorAll('.inquiry-table thead th').forEach(th => {
th.style.top = totalOffset + 'px';
});
}
initStickyHeader();
const pmType = document.getElementById('filterPmType').value;
const category = document.getElementById('filterCategory').value;
@@ -19,16 +10,42 @@ async function loadInquiries() {
const params = new URLSearchParams({
pm_type: pmType,
category: category,
status: status,
keyword: keyword
});
const response = await fetch(`/api/inquiries?${params}`);
const data = await response.json();
try {
const response = await fetch(`/api/inquiries?${params}`);
const data = await response.json();
updateStats(data);
const filteredData = status ? data.filter(item => item.status === status) : data;
renderInquiryList(filteredData);
} catch (e) {
console.error("데이터 로딩 중 오류 발생:", e);
}
}
function initStickyHeader() {
const header = document.getElementById('stickyHeader');
const thead = document.querySelector('.inquiry-table thead');
if (header && thead) {
const headerHeight = header.offsetHeight;
const totalOffset = 36 + headerHeight;
document.querySelectorAll('.inquiry-table thead th').forEach(th => {
th.style.top = totalOffset + 'px';
});
}
}
function renderInquiryList(data) {
const tbody = document.getElementById('inquiryList');
tbody.innerHTML = data.map(item => `
<tr class="inquiry-row" onclick="toggleAccordion(${item.id})">
<td title="${item.no}">${item.no}</td>
<td style="text-align:center;">
${item.image_url ? `<img src="${item.image_url}" class="img-thumbnail" alt="thumbnail">` : '<span class="no-img">없음</span>'}
</td>
<td title="${item.pm_type}">${item.pm_type}</td>
<td title="${item.browser || 'Chrome'}">${item.browser || 'Chrome'}</td>
<td title="${item.category}">${item.category}</td>
@@ -40,7 +57,7 @@ async function loadInquiries() {
<td><span class="status-badge ${getStatusClass(item.status)}">${item.status}</span></td>
</tr>
<tr id="detail-${item.id}" class="detail-row">
<td colspan="10">
<td colspan="11">
<div class="detail-container">
<button class="btn-close-accordion" onclick="toggleAccordion(${item.id})">접기</button>
<div class="detail-content-wrapper">
@@ -50,10 +67,27 @@ async function loadInquiries() {
<div><span class="detail-label">시스템:</span> ${item.pm_type}</div>
<div><span class="detail-label">환경:</span> ${item.browser || 'Chrome'} / ${item.device || 'PC'}</div>
</div>
<div class="detail-q-section">
<h4 style="margin-top:0; margin-bottom:10px; color:#1e5149;">[질문 내용]</h4>
<div style="line-height:1.6; white-space: pre-wrap;">${item.content}</div>
</div>
${item.image_url ? `
<div class="detail-image-section" id="img-section-${item.id}">
<div class="image-section-header" onclick="toggleImageSection(${item.id})">
<h4>
<span>🖼️</span> [첨부 이미지]
<span style="font-size:11px; color:#888; font-weight:normal;">(클릭 시 크게 보기)</span>
</h4>
<span class="toggle-icon">▼</span>
</div>
<div class="image-section-content collapsed" id="img-content-${item.id}">
<img src="${item.image_url}" class="preview-img" alt="Inquiry Image" style="cursor: pointer;" onclick="event.stopPropagation(); openImageModal(this.src)">
</div>
</div>
` : ''}
<div class="detail-a-section">
<h4 style="margin-top:0; margin-bottom:10px; color:#1e5149;">[조치 및 답변]</h4>
<div id="reply-form-${item.id}" class="reply-edit-form readonly">
@@ -94,18 +128,15 @@ async function loadInquiries() {
function enableEdit(id) {
const form = document.getElementById(`reply-form-${id}`);
form.classList.remove('readonly');
form.classList.add('editable');
form.classList.replace('readonly', 'editable');
document.getElementById(`reply-text-${id}`).disabled = false;
document.getElementById(`reply-status-${id}`).disabled = false;
document.getElementById(`reply-handler-${id}`).disabled = false;
const elements = [`reply-text-${id}`, `reply-status-${id}`, `reply-handler-${id}`];
elements.forEach(elId => document.getElementById(elId).disabled = false);
document.getElementById(`reply-text-${id}`).focus();
}
async function cancelEdit(id) {
try {
// 서버에서 해당 항목의 원래 데이터를 다시 가져옴
const response = await fetch(`/api/inquiries/${id}`);
const item = await response.json();
@@ -114,21 +145,14 @@ async function cancelEdit(id) {
const status = document.getElementById(`reply-status-${id}`);
const handler = document.getElementById(`reply-handler-${id}`);
// 데이터 원복
txt.value = item.reply || '';
status.value = item.status;
handler.value = item.handler || '';
// UI 상태 원복 (비활성화 및 클래스 변경)
txt.disabled = true;
status.disabled = true;
handler.disabled = true;
form.classList.remove('editable');
form.classList.add('readonly');
[txt, status, handler].forEach(el => el.disabled = true);
form.classList.replace('editable', 'readonly');
} catch (e) {
console.error("취소 중 오류 발생:", e);
loadInquiries(); // 오류 시에는 전체 새로고침으로 대응
loadInquiries();
}
}
@@ -137,8 +161,7 @@ async function saveReply(id) {
const status = document.getElementById(`reply-status-${id}`).value;
const handler = document.getElementById(`reply-handler-${id}`).value;
if (!reply.trim()) return alert("답변 내용을 입력해 주세요.");
if (!handler.trim()) return alert("처리자 이름을 입력해 주세요.");
if (!reply.trim() || !handler.trim()) return alert("내용과 처리자를 모두 입력해 주세요.");
try {
const response = await fetch(`/api/inquiries/${id}/reply`, {
@@ -148,30 +171,26 @@ async function saveReply(id) {
});
const result = await response.json();
if (result.success) {
alert("답변이 저장되었습니다.");
alert("저장되었습니다.");
loadInquiries();
} else {
alert("저장에 실패했습니다: " + result.error);
}
} catch (e) {
alert("오류가 발생했습니다.");
alert("저장 중 오류가 발생했습니다.");
}
}
async function deleteReply(id) {
if (!confirm("답변을 삭제하시겠습니까? (처리 상태가 '미확인'으로 초기화됩니다.)")) return;
if (!confirm("답변을 삭제하시겠습니까?")) return;
try {
const response = await fetch(`/api/inquiries/${id}/reply`, { method: 'DELETE' });
const result = await response.json();
if (result.success) {
alert("답변이 삭제되었습니다.");
alert("삭제되었습니다.");
loadInquiries();
} else {
alert("삭제에 실패했습니다: " + result.error);
}
} catch (e) {
alert("오류가 발생했습니다.");
alert("삭제 중 오류가 발생했습니다.");
}
}
@@ -181,7 +200,6 @@ function toggleAccordion(id) {
const inquiryRow = detailRow.previousElementSibling;
const isActive = detailRow.classList.contains('active');
// Close all other active details and remove their row highlights
document.querySelectorAll('.detail-row.active').forEach(row => {
if (row.id !== `detail-${id}`) {
row.classList.remove('active');
@@ -189,42 +207,72 @@ function toggleAccordion(id) {
}
});
// Toggle current
if (isActive) {
detailRow.classList.remove('active');
inquiryRow.classList.remove('active-row');
} else {
detailRow.classList.add('active');
inquiryRow.classList.add('active-row');
// [추가] 펼쳐진 항목이 보기 편하도록 스크롤 위치 조정
setTimeout(() => {
const stickyHeader = document.getElementById('stickyHeader');
const thead = document.querySelector('.inquiry-table thead');
const topbarHeight = 36;
const stickyHeaderHeight = stickyHeader ? stickyHeader.offsetHeight : 0;
const theadHeight = thead ? thead.offsetHeight : 0;
// 모든 고정 영역의 합 (Topbar + 필터영역 + 표 헤더)
const totalOffset = topbarHeight + stickyHeaderHeight + theadHeight;
const rowPosition = inquiryRow.getBoundingClientRect().top + window.pageYOffset;
const offsetPosition = rowPosition - totalOffset;
window.scrollTo({
top: offsetPosition,
behavior: 'smooth'
});
}, 100);
scrollToRow(inquiryRow);
}
}
function getStatusClass(status) {
if (status === '완료') return 'status-complete';
if (status === '작업 중') return 'status-working';
if (status === '확인 중') return 'status-checking';
return 'status-pending';
function scrollToRow(row) {
setTimeout(() => {
const headerHeight = document.getElementById('stickyHeader').offsetHeight;
const totalOffset = 36 + headerHeight + 40;
const offsetPosition = (row.getBoundingClientRect().top + window.pageYOffset) - totalOffset;
window.scrollTo({ top: offsetPosition, behavior: 'smooth' });
}, 100);
}
function getStatusClass(status) {
const map = { '완료': 'status-complete', '작업 중': 'status-working', '확인 중': 'status-checking' };
return map[status] || 'status-pending';
}
function updateStats(data) {
const counts = {
Total: data.length,
Complete: data.filter(i => i.status === '완료').length,
Working: data.filter(i => i.status === '작업 중').length,
Checking: data.filter(i => i.status === '확인 중').length,
Pending: data.filter(i => i.status === '개발예정').length,
Unconfirmed: data.filter(i => i.status === '미확인').length
};
Object.keys(counts).forEach(k => {
const el = document.getElementById(`count${k}`);
if (el) el.textContent = counts[k].toLocaleString();
});
}
function openImageModal(src) {
const modal = document.getElementById('imageModal');
if (modal) {
document.getElementById('modalImage').src = src;
modal.style.display = 'flex';
}
}
function closeImageModal() {
const modal = document.getElementById('imageModal');
if (modal) modal.style.display = 'none';
}
function toggleImageSection(id) {
const section = document.getElementById(`img-section-${id}`);
const content = document.getElementById(`img-content-${id}`);
const icon = section.querySelector('.toggle-icon');
const isCollapsed = content.classList.toggle('collapsed');
section.classList.toggle('active', !isCollapsed);
icon.textContent = isCollapsed ? '▼' : '▲';
}
// Global Initialization
document.addEventListener('DOMContentLoaded', loadInquiries);
window.addEventListener('resize', loadInquiries);
window.addEventListener('resize', initStickyHeader);
// Global Key Events (ESC)
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') closeImageModal();
});

View File

@@ -82,6 +82,7 @@ const MAIL_SAMPLES = {
let currentMailTab = 'inbound';
let filteredMails = [];
// --- 첨부파일 데이터 로드 및 렌더링 ---
async function loadAttachments() {
try {
const res = await fetch('/attachments');
@@ -116,16 +117,16 @@ function renderFiles() {
}
item.innerHTML = `
<div class="attachment-item" onclick="showPreview(${index}, event)">
<span class="file-icon">📄</span>
<div class="file-details">
<div class="attachment-item" onclick="showPreview(${index}, event)" style="position:relative;">
<span class="file-icon" style="pointer-events:none;">📄</span>
<div class="file-details" style="pointer-events:none;">
<div class="file-name" title="${file.name}">${file.name}</div>
<div class="file-size">${file.size}</div>
</div>
<div class="btn-group">
<div class="btn-group" onclick="event.stopPropagation()" style="position:relative; z-index:2;">
<span id="recommend-${index}" class="ai-recommend path-display ${modeClass}" onclick="openPathModal(${index}, event)">${pathText}</span>
${isAiActive ? `<button class="btn-upload btn-ai" onclick="startAnalysis(${index}, event)">AI 분석</button>` : ''}
<button class="btn-upload btn-normal" onclick="confirmUpload(${index}, event)">파일 업로드</button>
<button class="btn-upload btn-normal" onclick="confirmUpload(${index}, event)">파일업로드</button>
</div>
</div>
<div id="log-area-${index}" class="file-log-area">
@@ -136,18 +137,71 @@ function renderFiles() {
});
}
// --- 미리보기 제어 ---
function togglePreviewAuto() {
const area = document.getElementById('mailPreviewArea');
const icon = document.getElementById('previewToggleIcon');
if (!area) return;
const isActive = area.classList.toggle('active');
if (icon) icon.innerText = isActive ? '▶' : '◀';
}
function showPreview(index, event) {
// 버튼 클릭 시 미리보기 방지
if (event && (event.target.closest('.btn-group') || event.target.closest('.path-display'))) return;
const file = currentFiles[index];
if (!file) return;
const previewContainer = document.getElementById('previewContainer');
const fullViewBtn = document.getElementById('fullViewBtn');
const previewArea = document.getElementById('mailPreviewArea');
const toggleIcon = document.getElementById('previewToggleIcon');
// UI 활성화
if (previewArea) {
previewArea.classList.add('active');
if (toggleIcon) toggleIcon.innerText = '▶';
}
// 파일 경로 및 유형 처리
const isPdf = file.name.toLowerCase().endsWith('.pdf');
const fileUrl = `/sample_files/${encodeURIComponent(file.name)}`;
if (fullViewBtn) {
fullViewBtn.style.display = 'block';
fullViewBtn.onclick = () => window.open(fileUrl, 'PMFullView', 'width=1000,height=800');
}
if (isPdf) {
previewContainer.innerHTML = `<iframe src="${fileUrl}#page=1" style="width:100%; height:100%; border:none;"></iframe>`;
} else {
previewContainer.innerHTML = `
<div style="width:100%; height:100%; display:flex; flex-direction:column; align-items:center; justify-content:center; padding:20px; text-align:center;">
<img src="/sample.png" style="max-width:80%; max-height:60%; margin-bottom:20px;">
<div style="font-weight:700; color:var(--primary-color);">${file.name}</div>
</div>`;
}
// 아이템 활성화 스타일
document.querySelectorAll('.attachment-item').forEach(item => item.classList.remove('active'));
if (event && event.currentTarget) event.currentTarget.classList.add('active');
}
// --- 메일 리스트 관리 ---
function renderMailList(tabType, mailsToShow = null) {
currentMailTab = tabType;
const container = document.querySelector('.mail-items-container');
if (!container) return;
const mails = mailsToShow || MAIL_SAMPLES[tabType] || [];
filteredMails = mails; // 현재 보여지는 리스트 저장
filteredMails = mails;
updateBulkActionBar();
container.innerHTML = mails.map((mail, idx) => `
<div class="mail-item ${mail.active ? 'active' : ''}" onclick="selectMailItem(this, ${idx})">
<input type="checkbox" class="mail-item-checkbox" onclick="handleCheckboxClick(event)" onchange="updateBulkActionBar()">
<input type="checkbox" class="mail-item-checkbox" onclick="event.stopPropagation()" onchange="updateBulkActionBar()">
<div class="mail-item-content">
<div class="flex-between" style="margin-bottom:6px;">
<span style="font-weight:700; font-size:14px; color:${mail.active ? 'var(--primary-color)' : 'var(--text-main)'};">
@@ -166,23 +220,73 @@ function renderMailList(tabType, mailsToShow = null) {
</div>
`).join('');
// 초기 로드 시 active가 있다면 본문도 업데이트
const activeIdx = mails.findIndex(m => m.active);
if (activeIdx !== -1) {
updateMailContent(mails[activeIdx]);
}
if (activeIdx !== -1) updateMailContent(mails[activeIdx]);
}
function handleCheckboxClick(event) {
event.stopPropagation();
function selectMailItem(el, index) {
document.querySelectorAll('.mail-item').forEach(item => {
item.classList.remove('active');
const nameSpan = item.querySelector('.mail-item-content span:first-child');
if (nameSpan) nameSpan.style.color = 'var(--text-main)';
});
el.classList.add('active');
const currentNameSpan = el.querySelector('.mail-item-content span:first-child');
if (currentNameSpan) currentNameSpan.style.color = 'var(--primary-color)';
const mail = filteredMails[index];
if (mail) updateMailContent(mail);
}
function updateMailContent(mail) {
const headerTitle = document.querySelector('.mail-content-header h2');
const senderInfo = document.querySelectorAll('.mail-content-header div')[0];
const dateInfo = document.querySelectorAll('.mail-content-header div')[1];
const bodyInfo = document.querySelector('.mail-body');
if (headerTitle) headerTitle.innerText = mail.title;
if (senderInfo) senderInfo.innerHTML = `<strong>${currentMailTab === 'outbound' ? '받는사람' : '보낸사람'}</strong> ${mail.email} (${mail.person})`;
if (dateInfo) dateInfo.innerHTML = `<strong>날짜</strong> ${mail.time}`;
if (bodyInfo) bodyInfo.innerHTML = mail.summary.replace(/\n/g, '<br>') + "<br><br>본 내용은 샘플 데이터입니다.";
}
function switchMailTab(el, tabType) {
document.querySelectorAll('.mail-tab').forEach(tab => tab.classList.remove('active'));
el.classList.add('active');
MAIL_SAMPLES[tabType].forEach((m, idx) => m.active = (idx === 0));
renderMailList(tabType);
}
// --- 검색 및 필터 ---
function searchMails() {
const query = document.querySelector('.search-bar input[type="text"]').value.toLowerCase();
const startDate = document.getElementById('startDate').value;
const endDate = document.getElementById('endDate').value;
const results = (MAIL_SAMPLES[currentMailTab] || []).filter(mail => {
const matchQuery = mail.title.toLowerCase().includes(query) ||
mail.person.toLowerCase().includes(query) ||
mail.summary.toLowerCase().includes(query);
let matchDate = true;
if (startDate) matchDate = matchDate && (mail.time >= startDate);
if (endDate) matchDate = matchDate && (mail.time <= endDate);
return matchQuery && matchDate;
});
renderMailList(currentMailTab, results);
}
function resetSearch() {
document.querySelector('.search-bar input[type="text"]').value = '';
document.getElementById('startDate').value = '';
document.getElementById('endDate').value = '';
renderMailList(currentMailTab);
}
// --- 액션바 관리 ---
function updateBulkActionBar() {
const checkboxes = document.querySelectorAll('.mail-item-checkbox:checked');
const actionBar = document.getElementById('mailBulkActions');
const selectedCountSpan = document.getElementById('selectedCount');
const selectAllCheckbox = document.getElementById('selectAllMails');
if (!actionBar || !selectedCountSpan) return;
if (checkboxes.length > 0) {
@@ -190,13 +294,13 @@ function updateBulkActionBar() {
selectedCountSpan.innerText = `${checkboxes.length}개 선택됨`;
} else {
actionBar.classList.remove('active');
if (selectAllCheckbox) selectAllCheckbox.checked = false;
const selectAll = document.getElementById('selectAllMails');
if (selectAll) selectAll.checked = false;
}
}
function toggleSelectAll(el) {
const checkboxes = document.querySelectorAll('.mail-item-checkbox');
checkboxes.forEach(cb => cb.checked = el.checked);
document.querySelectorAll('.mail-item-checkbox').forEach(cb => cb.checked = el.checked);
updateBulkActionBar();
}
@@ -222,145 +326,41 @@ function deleteSelectedMails() {
renderMailList(currentMailTab);
}
function selectMailItem(el, index) {
// UI 업데이트
document.querySelectorAll('.mail-item').forEach(item => {
item.classList.remove('active');
const nameSpan = item.querySelector('.mail-item-content span:first-child');
if (nameSpan) nameSpan.style.color = 'var(--text-main)';
});
el.classList.add('active');
const currentNameSpan = el.querySelector('.mail-item-content span:first-child');
if (currentNameSpan) currentNameSpan.style.color = 'var(--primary-color)';
// 본문 업데이트
const mail = filteredMails[index];
if (mail) {
updateMailContent(mail);
}
}
function updateMailContent(mail) {
const headerTitle = document.querySelector('.mail-content-header h2');
const senderInfo = document.querySelectorAll('.mail-content-header div')[0];
const dateInfo = document.querySelectorAll('.mail-content-header div')[1];
const bodyInfo = document.querySelector('.mail-body');
if (headerTitle) headerTitle.innerText = mail.title;
if (senderInfo) senderInfo.innerHTML = `<strong>${currentMailTab === 'outbound' ? '받는사람' : '보낸사람'}</strong> ${mail.email} (${mail.person})`;
if (dateInfo) dateInfo.innerHTML = `<strong>날짜</strong> ${mail.time}`;
if (bodyInfo) bodyInfo.innerHTML = mail.summary.replace(/\n/g, '<br>') + "<br><br>" + "본 내용은 샘플 데이터입니다.";
}
function switchMailTab(el, tabType) {
document.querySelectorAll('.mail-tab').forEach(tab => tab.classList.remove('active'));
el.classList.add('active');
// 탭 이동 시 active 상태 초기화 (첫 번째 메일만 active 하거나 전부 해제)
MAIL_SAMPLES[tabType].forEach((m, idx) => m.active = (idx === 0));
renderMailList(tabType);
}
// --- 검색 기능 ---
function searchMails() {
const query = document.querySelector('.search-bar input[type="text"]').value.toLowerCase();
const startDate = document.getElementById('startDate').value;
const endDate = document.getElementById('endDate').value;
const mails = MAIL_SAMPLES[currentMailTab];
const results = mails.filter(mail => {
const matchQuery = mail.title.toLowerCase().includes(query) ||
mail.person.toLowerCase().includes(query) ||
mail.summary.toLowerCase().includes(query);
let matchDate = true;
if (startDate) matchDate = matchDate && (mail.time >= startDate);
if (endDate) matchDate = matchDate && (mail.time <= endDate);
return matchQuery && matchDate;
});
renderMailList(currentMailTab, results);
}
function resetSearch() {
document.querySelector('.search-bar input[type="text"]').value = '';
document.getElementById('startDate').value = '';
document.getElementById('endDate').value = '';
document.querySelector('.search-bar select').selectedIndex = 0;
renderMailList(currentMailTab);
}
// --- 모달 및 기타 유틸리티 ---
function togglePreview(show) {
const previewArea = document.getElementById('mailPreviewArea');
if (show) previewArea.classList.add('active');
else previewArea.classList.remove('active');
}
function showPreview(index, event) {
if (event.target.closest('.btn-group') || event.target.closest('.path-display')) return;
const file = currentFiles[index];
const previewContainer = document.getElementById('previewContainer');
const fullViewBtn = document.getElementById('fullViewBtn');
document.querySelectorAll('.attachment-item').forEach(item => item.classList.remove('active'));
event.currentTarget.classList.add('active');
togglePreview(true);
const isPdf = file.name.toLowerCase().endsWith('.pdf');
const fileUrl = `/sample_files/${encodeURIComponent(file.name)}`;
if (fullViewBtn) {
fullViewBtn.style.display = 'block';
fullViewBtn.onclick = () => window.open(fileUrl, 'PMFullView', 'width=1000,height=800');
}
if (isPdf) {
previewContainer.innerHTML = `<iframe src="${fileUrl}#page=1" style="width:100%; height:100%; border:none;"></iframe>`;
} else {
previewContainer.innerHTML = `<div style="width:100%; height:100%; display:flex; flex-direction:column; align-items:center; justify-content:center; padding:20px; text-align:center;"><img src="/sample.png" class="preview-image"><div style="margin-top:20px; font-weight:700; color:var(--primary-color);">${file.name}</div></div>`;
}
}
// --- 경로 선택 모달 ---
function openPathModal(index, event) {
if (event) event.stopPropagation();
editingIndex = index;
const modal = document.getElementById('pathModal');
const tabSelect = document.getElementById('tabSelect');
if (!tabSelect) return;
if (!modal || !tabSelect) return;
tabSelect.innerHTML = Object.keys(HIERARCHY).map(tab => `<option value="${tab}">${tab}</option>`).join('');
updateCategories();
modal.style.display = 'flex';
}
function updateCategories() {
const tabSelect = document.getElementById('tabSelect');
const tab = document.getElementById('tabSelect').value;
const catSelect = document.getElementById('categorySelect');
if (!tabSelect || !catSelect) return;
const tab = tabSelect.value;
const cats = Object.keys(HIERARCHY[tab]);
catSelect.innerHTML = cats.map(cat => `<option value="${cat}">${cat}</option>`).join('');
if (!catSelect) return;
catSelect.innerHTML = Object.keys(HIERARCHY[tab]).map(cat => `<option value="${cat}">${cat}</option>`).join('');
updateSubs();
}
function updateSubs() {
const tabSelect = document.getElementById('tabSelect');
const catSelect = document.getElementById('categorySelect');
const tab = document.getElementById('tabSelect').value;
const cat = document.getElementById('categorySelect').value;
const subSelect = document.getElementById('subSelect');
if (!tabSelect || !catSelect || !subSelect) return;
const tab = tabSelect.value;
const cat = catSelect.value;
const subs = HIERARCHY[tab][cat];
subSelect.innerHTML = subs.map(sub => `<option value="${sub}">${sub}</option>`).join('');
if (!subSelect) return;
subSelect.innerHTML = HIERARCHY[tab][cat].map(sub => `<option value="${sub}">${sub}</option>`).join('');
}
function applyPathSelection() {
const tabSelect = document.getElementById('tabSelect');
const catSelect = document.getElementById('categorySelect');
const subSelect = document.getElementById('subSelect');
const tab = tabSelect.value;
const cat = catSelect.value;
const sub = subSelect.value;
const tab = document.getElementById('tabSelect').value;
const cat = document.getElementById('categorySelect').value;
const sub = document.getElementById('subSelect').value;
const fullPath = `${tab} > ${cat} > ${sub}`;
if (!currentFiles[editingIndex].analysis) currentFiles[editingIndex].analysis = {};
currentFiles[editingIndex].analysis.suggested_path = fullPath;
currentFiles[editingIndex].analysis.isManual = true;
@@ -373,6 +373,7 @@ function closeModal() {
if (modal) modal.style.display = 'none';
}
// --- AI 분석 및 업로드 ---
async function startAnalysis(index, event) {
if (event) event.stopPropagation();
const file = currentFiles[index];
@@ -380,20 +381,21 @@ async function startAnalysis(index, event) {
const logContent = document.getElementById(`log-content-${index}`);
const recLabel = document.getElementById(`recommend-${index}`);
if (!logArea || !logContent || !recLabel) return;
logArea.classList.add('active');
logContent.innerHTML = '<div class="log-line log-info">>>> 3중 레이어 AI 분석 엔진 가동...</div>';
logContent.innerHTML = '<div class="log-line log-info">>>> AI 분석 엔진 가동...</div>';
recLabel.innerText = '분석 중...';
try {
const res = await fetch(`/analyze-file?filename=${encodeURIComponent(file.name)}`);
const analysis = await res.json();
const result = analysis.final_result;
const steps = [`1. 파일 포맷 분석: ${file.name.split('.').pop().toUpperCase()} 감지`, `2. 페이지 스캔: 총 ${analysis.total_pages}페이지 분석 완료`, `3. 문맥 추론: ${result.reason}`];
steps.forEach(step => {
const line = document.createElement('div');
line.className = 'log-line';
line.innerText = " " + step;
logContent.appendChild(line);
});
logContent.innerHTML = `
<div class="log-line">1. 파일 포맷 분석: ${file.name.split('.').pop().toUpperCase()} 감지</div>
<div class="log-line">2. 페이지 스캔: 총 ${analysis.total_pages}페이지 분석 완료</div>
<div class="log-line">3. 문맥 추론: ${result.reason}</div>
`;
currentFiles[index].analysis = { suggested_path: result.suggested_path, isManual: false };
renderFiles();
} catch (e) {
@@ -406,15 +408,13 @@ function confirmUpload(index, event) {
if (event) event.stopPropagation();
const file = currentFiles[index];
if (!file.analysis || !file.analysis.suggested_path) { alert("경로를 설정해주세요."); return; }
if (confirm(`정해진 위치로 업로드하시겠습니까?\n\n위치: ${file.analysis.suggested_path}`)) alert("업로드가 완료되었습니다.");
if (confirm(`업로드하시겠습니까?\n위치: ${file.analysis.suggested_path}`)) alert("완료되었습니다.");
}
// --- 주소록 기능 ---
// --- 주소록 ---
let addressBookData = [
{ name: "이태훈", dept: "PM Overseas / 선임연구원", email: "th.lee@projectmaster.com", phone: "010-1234-5678" },
{ name: "Pany S.", dept: "라오스 농림부 / 국장", email: "pany.s@lao.gov.la", phone: "+856-20-1234-5678" },
{ name: "김철수", dept: "현대건설 / 현장소장", email: "cs.kim@hdec.co.kr", phone: "010-9876-5432" },
{ name: "Nguyen Van A", dept: "베트남 전력청 / 팀장", email: "nva@evn.com.vn", phone: "+84-90-1234-5678" }
{ name: "Pany S.", dept: "라오스 농림부 / 국장", email: "pany.s@lao.gov.la", phone: "+856-20-1234-5678" }
];
let contactEditingIndex = -1;
@@ -425,33 +425,60 @@ function openAddressBook() {
function closeAddressBook() {
const modal = document.getElementById('addressBookModal');
if (modal) { modal.style.display = 'none'; document.getElementById('addContactForm').style.display = 'none'; contactEditingIndex = -1; }
if (modal) { modal.style.display = 'none'; document.getElementById('addContactForm').style.display = 'none'; }
}
function toggleAddContactForm() {
const form = document.getElementById('addContactForm');
if (!form) return;
if (form.style.display === 'none') {
form.style.display = 'block';
} else {
form.style.display = 'none';
contactEditingIndex = -1;
// 폼 초기화
document.getElementById('newContactName').value = '';
document.getElementById('newContactDept').value = '';
document.getElementById('newContactEmail').value = '';
document.getElementById('newContactPhone').value = '';
}
}
function editContact(index) {
const contact = addressBookData[index];
if (!contact) return;
contactEditingIndex = index;
document.getElementById('newContactName').value = contact.name;
document.getElementById('newContactDept').value = contact.dept;
document.getElementById('newContactEmail').value = contact.email;
document.getElementById('newContactPhone').value = contact.phone;
document.getElementById('addContactForm').style.display = 'block';
}
function deleteContact(index) {
if (!addressBookData[index]) return;
if (confirm(`'${addressBookData[index].name}'님을 주소록에서 삭제하시겠습니까?`)) {
addressBookData.splice(index, 1);
renderAddressBook();
}
}
function renderAddressBook() {
const body = document.getElementById('addressBookBody');
if (!body) return;
body.innerHTML = addressBookData.map((c, idx) => `<tr><td><strong>${c.name}</strong></td><td>${c.dept}</td><td>${c.email}</td><td>${c.phone}</td><td style="text-align:right;"><button class="_button-xsmall" onclick="editContact(${idx})">수정</button><button class="_button-xsmall" onclick="deleteContact(${idx})">삭제</button></td></tr>`).join('');
}
function toggleAddContactForm() {
const form = document.getElementById('addContactForm');
if (form.style.display === 'none') form.style.display = 'block';
else { form.style.display = 'none'; contactEditingIndex = -1; }
}
function editContact(index) {
const contact = addressBookData[index];
contactEditingIndex = index;
document.getElementById('newContactName').value = contact.name;
document.getElementById('newContactDept').value = contact.dept;
document.getElementById('newContactEmail').value = contact.email;
document.getElementById('newContactPhone').value = contact.phone;
document.getElementById('addContactForm').style.display = 'block';
}
function deleteContact(index) {
if (confirm(`'${addressBookData[index].name}'님을 주소록에서 삭제하시겠습니까?`)) { addressBookData.splice(index, 1); renderAddressBook(); }
body.innerHTML = addressBookData.map((c, idx) => `
<tr>
<td><strong>${c.name}</strong></td>
<td>${c.dept}</td>
<td>${c.email}</td>
<td>${c.phone}</td>
<td style="text-align:right;">
<button class="_button-xsmall" onclick="editContact(${idx})">수정</button>
<button class="_button-xsmall" style="color:var(--error-color); border-color:#feb2b2; background:#fff5f5;" onclick="deleteContact(${idx})">삭제</button>
</td>
</tr>`).join('');
}
function addContact() {
@@ -459,21 +486,17 @@ function addContact() {
const dept = document.getElementById('newContactDept').value;
const email = document.getElementById('newContactEmail').value;
const phone = document.getElementById('newContactPhone').value;
if (!name) { alert("이름을 입력해주세요."); return; }
const newData = { name, dept, email, phone };
if (contactEditingIndex > -1) { addressBookData[contactEditingIndex] = newData; contactEditingIndex = -1; }
else addressBookData.push(newData);
if (!name) return alert("이름을 입력해주세요.");
if (contactEditingIndex > -1) addressBookData[contactEditingIndex] = { name, dept, email, phone };
else addressBookData.push({ name, dept, email, phone });
renderAddressBook();
toggleAddContactForm();
}
function togglePreviewAuto() {
const area = document.getElementById('mailPreviewArea');
const icon = document.getElementById('previewToggleIcon');
const isActive = area.classList.toggle('active');
if (icon) icon.innerText = isActive ? '▶' : '◀';
document.getElementById('addContactForm').style.display = 'none';
contactEditingIndex = -1;
}
// 초기화
document.addEventListener('DOMContentLoaded', () => {
loadAttachments();
renderMailList('inbound');