security: 보안 강제 시스템 구축 + 하드코딩 비밀번호 제거

보안 감사 결과 CRITICAL 2건, HIGH 5건 발견 → 수정 완료 + 자동화 구축.

[보안 수정]
- issue-view.js: 하드코딩 비밀번호 → crypto.getRandomValues() 랜덤 생성
- pushSubscriptionController.js: ntfy 비밀번호 → process.env.NTFY_SUB_PASSWORD
- DEPLOY-GUIDE.md/PROGRESS.md/migration SQL: 평문 비밀번호 → placeholder
- docker-compose.yml/.env.example: NTFY_SUB_PASSWORD 환경변수 추가

[보안 강제 시스템 - 신규]
- scripts/security-scan.sh: 8개 규칙 (CRITICAL 2, HIGH 4, MEDIUM 2)
  3모드(staged/all/diff), severity, .securityignore, MEDIUM 임계값
- .githooks/pre-commit: 로컬 빠른 피드백
- .githooks/pre-receive-server.sh: Gitea 서버 최종 차단
  bypass 거버넌스([SECURITY-BYPASS: 사유] + 사용자 제한 + 로그)
- SECURITY-CHECKLIST.md: 10개 카테고리 자동/수동 구분
- docs/SECURITY-GUIDE.md: 운영자 가이드 (워크플로우, bypass, FAQ)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Hyungi Ahn
2026-04-10 09:44:21 +09:00
parent bbffa47a9d
commit ba9ef32808
257 changed files with 786 additions and 18 deletions

View File

@@ -0,0 +1,255 @@
/* ===== 구매 분석 페이지 ===== */
// 카테고리 — API 동적 로드
let _categories = null;
async function loadCategories() {
if (_categories) return _categories;
try { const r = await api('/consumable-categories'); _categories = r.data || []; } catch(e) { _categories = []; }
return _categories;
}
function getCatLabel(code) { return (_categories || []).find(c => c.category_code === code)?.category_name || code || '-'; }
function getCatIcon(code) { return (_categories || []).find(c => c.category_code === code)?.icon || 'fa-box'; }
function getCatBgClass(code) {
const c = (_categories || []).find(x => x.category_code === code);
if (!c) return 'bg-gray-50 text-gray-700';
// Tailwind class 생성 (인라인 스타일 대신)
return '';
}
function getCatColors(code) {
const c = (_categories || []).find(x => x.category_code === code);
return c ? { bg: c.color_bg, fg: c.color_fg } : { bg: '#f3f4f6', fg: '#374151' };
}
const STATUS_LABELS = { received: '입고완료', returned: '반품' };
const STATUS_COLORS = { received: 'badge-teal', returned: 'badge-red' };
let currentYearMonth = '';
let dateBasis = 'purchase'; // 'purchase' 또는 'received'
function setDateBasis(basis) {
dateBasis = basis;
document.getElementById('btnDatePurchase').className = basis === 'purchase'
? 'px-3 py-2 bg-orange-600 text-white' : 'px-3 py-2 bg-white text-gray-600 hover:bg-gray-50';
document.getElementById('btnDateReceived').className = basis === 'received'
? 'px-3 py-2 bg-orange-600 text-white' : 'px-3 py-2 bg-white text-gray-600 hover:bg-gray-50';
}
async function loadAnalysis() {
currentYearMonth = document.getElementById('paMonth').value;
if (!currentYearMonth) { showToast('월을 선택해주세요.', 'error'); return; }
try {
if (dateBasis === 'purchase') {
await loadPurchaseBasis();
} else {
await loadReceivedBasis();
}
} catch (e) {
showToast('데이터 로드 실패: ' + e.message, 'error');
}
}
/* ===== 구매일 기준 (기존) ===== */
async function loadPurchaseBasis() {
// 입고 섹션 숨김
document.getElementById('paReceivedSection').classList.add('hidden');
const [summaryRes, purchasesRes, priceChangesRes] = await Promise.all([
api(`/settlements/summary?year_month=${currentYearMonth}`),
api(`/settlements/purchases?year_month=${currentYearMonth}`),
api(`/settlements/price-changes?year_month=${currentYearMonth}`)
]);
renderCategorySummary(summaryRes.data?.categorySummary || []);
renderVendorSummary(summaryRes.data?.vendorSummary || []);
renderPurchaseList(purchasesRes.data || []);
renderPriceChanges(priceChangesRes.data || []);
}
/* ===== 입고일 기준 ===== */
async function loadReceivedBasis() {
const [summaryRes, listRes] = await Promise.all([
api(`/settlements/received-summary?year_month=${currentYearMonth}`),
api(`/settlements/received-list?year_month=${currentYearMonth}`)
]);
renderCategorySummary(summaryRes.data?.categorySummary || []);
// 업체/구매목록/가격변동은 빈 상태로
document.getElementById('paVendorSummary').innerHTML = '<tr><td colspan="5" class="px-4 py-4 text-center text-gray-400">입고일 기준에서는 업체별 정산이 표시되지 않습니다.</td></tr>';
document.getElementById('paPurchaseList').innerHTML = '<tr><td colspan="8" class="px-4 py-4 text-center text-gray-400">아래 입고 내역을 확인하세요.</td></tr>';
document.getElementById('paPriceChanges').innerHTML = '';
// 입고 섹션 표시
document.getElementById('paReceivedSection').classList.remove('hidden');
renderReceivedList(listRes.data || []);
}
/* ===== 렌더링 함수들 ===== */
function renderCategorySummary(data) {
const el = document.getElementById('paCategorySummary');
const cats = _categories || [];
const dataMap = {};
data.forEach(d => { dataMap[d.category] = d; });
const totalAmount = data.reduce((sum, d) => sum + Number(d.total_amount || 0), 0);
el.innerHTML = cats.map(cat => {
const d = dataMap[cat.category_code] || { count: 0, total_amount: 0 };
return `<div class="bg-white rounded-xl shadow-sm p-4">
<div class="flex items-center gap-2 mb-2">
<div class="w-8 h-8 rounded-lg flex items-center justify-center" style="background:${cat.color_bg};color:${cat.color_fg}"><i class="fas ${cat.icon} text-sm"></i></div>
<span class="text-sm font-medium text-gray-700">${escapeHtml(cat.category_name)}</span>
</div>
<div class="text-xl font-bold text-gray-800">${Number(d.total_amount || 0).toLocaleString()}<span class="text-xs font-normal text-gray-400 ml-1">원</span></div>
<div class="text-xs text-gray-500 mt-1">${d.count || 0}건</div>
</div>`;
}).join('') + `
<div class="col-span-2 lg:col-span-4 bg-orange-50 rounded-xl p-3 text-center">
<span class="text-sm text-orange-700 font-semibold">${dateBasis === 'purchase' ? '구매' : '입고'} 월 합계: ${totalAmount.toLocaleString()}원</span>
</div>`;
}
function renderVendorSummary(data) {
const tbody = document.getElementById('paVendorSummary');
if (!data.length) {
tbody.innerHTML = '<tr><td colspan="5" class="px-4 py-8 text-center text-gray-400">해당 월 구매 내역이 없습니다.</td></tr>';
return;
}
tbody.innerHTML = data.map(v => {
const isCompleted = v.settlement_status === 'completed';
const statusBadge = isCompleted ? '<span class="badge badge-green">정산완료</span>' : '<span class="badge badge-gray">미정산</span>';
const vendorName = v.vendor_name || '(업체 미지정)';
const vendorId = v.vendor_id || 0;
let actionBtn = '';
if (vendorId > 0) {
actionBtn = isCompleted
? `<button onclick="cancelSettlement(${vendorId})" class="px-3 py-1 border border-gray-300 rounded text-xs text-gray-600 hover:bg-gray-50">정산 취소</button>`
: `<button onclick="completeSettlement(${vendorId})" class="px-3 py-1 bg-green-500 text-white rounded text-xs hover:bg-green-600">정산완료</button>`;
}
return `<tr class="hover:bg-gray-50">
<td class="px-4 py-3 font-medium text-gray-800">${escapeHtml(vendorName)}</td>
<td class="px-4 py-3 text-right">${v.count}건</td>
<td class="px-4 py-3 text-right font-medium">${Number(v.total_amount || 0).toLocaleString()}원</td>
<td class="px-4 py-3 text-center">${statusBadge}</td>
<td class="px-4 py-3 text-center">${actionBtn}</td>
</tr>`;
}).join('');
}
function renderPurchaseList(data) {
const tbody = document.getElementById('paPurchaseList');
if (!data.length) {
tbody.innerHTML = '<tr><td colspan="8" class="px-4 py-8 text-center text-gray-400">해당 월 구매 내역이 없습니다.</td></tr>';
return;
}
tbody.innerHTML = data.map(p => {
const catLabel = getCatLabel(p.category);
const catColor = getCatBgClass(p.category);
const subtotal = (p.quantity || 0) * (p.unit_price || 0);
const basePrice = Number(p.base_price || 0);
const unitPrice = Number(p.unit_price || 0);
const hasPriceDiff = basePrice > 0 && unitPrice > 0 && basePrice !== unitPrice;
const priceDiffClass = hasPriceDiff ? (unitPrice > basePrice ? 'text-red-600 font-semibold' : 'text-blue-600 font-semibold') : '';
return `<tr class="hover:bg-gray-50 ${hasPriceDiff ? 'bg-yellow-50' : ''}">
<td class="px-4 py-3">
<div class="font-medium text-gray-800">${escapeHtml(p.item_name)}${p.spec ? ' <span class="text-gray-400">[' + escapeHtml(p.spec) + ']</span>' : ''}</div>
<div class="text-xs text-gray-500">${escapeHtml(p.maker || '')}</div>
</td>
<td class="px-4 py-3"><span class="px-1.5 py-0.5 rounded text-xs ${catColor}">${catLabel}</span></td>
<td class="px-4 py-3 text-right">${p.quantity}</td>
<td class="px-4 py-3 text-right ${priceDiffClass}">${unitPrice.toLocaleString()}${hasPriceDiff ? `<div class="text-xs text-gray-400">(기준: ${basePrice.toLocaleString()})</div>` : ''}</td>
<td class="px-4 py-3 text-right font-medium">${subtotal.toLocaleString()}원</td>
<td class="px-4 py-3 text-gray-600">${escapeHtml(p.vendor_name || '-')}</td>
<td class="px-4 py-3 text-gray-600">${formatDate(p.purchase_date)}</td>
<td class="px-4 py-3 text-gray-500 text-xs">${escapeHtml(p.notes || '')}</td>
</tr>`;
}).join('');
}
function renderPriceChanges(data) {
const el = document.getElementById('paPriceChanges');
if (!data.length) {
el.innerHTML = '<p class="text-gray-400 text-center py-4 text-sm">가격 변동 항목이 없습니다.</p>';
return;
}
el.innerHTML = `<table class="w-full text-sm">
<thead class="bg-gray-50 text-gray-600 text-xs uppercase">
<tr>
<th class="px-4 py-3 text-left">품목</th>
<th class="px-4 py-3 text-right">기준가</th>
<th class="px-4 py-3 text-right">실구매가</th>
<th class="px-4 py-3 text-right">차이</th>
<th class="px-4 py-3 text-left">업체</th>
<th class="px-4 py-3 text-left">구매일</th>
</tr>
</thead>
<tbody class="divide-y">${data.map(p => {
const diff = Number(p.unit_price) - Number(p.base_price);
const arrow = diff > 0 ? '&#9650;' : '&#9660;';
const color = diff > 0 ? 'text-red-600' : 'text-blue-600';
return `<tr class="hover:bg-gray-50">
<td class="px-4 py-3">${escapeHtml(p.item_name)}${p.spec ? ' [' + escapeHtml(p.spec) + ']' : ''} ${p.maker ? '(' + escapeHtml(p.maker) + ')' : ''}</td>
<td class="px-4 py-3 text-right">${Number(p.base_price).toLocaleString()}원</td>
<td class="px-4 py-3 text-right font-medium ${color}">${Number(p.unit_price).toLocaleString()}원</td>
<td class="px-4 py-3 text-right ${color}">${arrow} ${Math.abs(diff).toLocaleString()}원</td>
<td class="px-4 py-3 text-gray-600">${escapeHtml(p.vendor_name || '-')}</td>
<td class="px-4 py-3 text-gray-600">${formatDate(p.purchase_date)}</td>
</tr>`;
}).join('')}</tbody>
</table>`;
}
function renderReceivedList(data) {
const tbody = document.getElementById('paReceivedList');
if (!data.length) {
tbody.innerHTML = '<tr><td colspan="8" class="px-4 py-8 text-center text-gray-400">해당 월 입고 내역이 없습니다.</td></tr>';
return;
}
tbody.innerHTML = data.map(r => {
const catLabel = getCatLabel(r.category);
const catColor = getCatBgClass(r.category);
const statusLabel = STATUS_LABELS[r.status] || r.status;
const statusColor = STATUS_COLORS[r.status] || 'badge-gray';
return `<tr class="hover:bg-gray-50 ${r.status === 'returned' ? 'bg-red-50' : ''}">
<td class="px-4 py-3">
<div class="font-medium text-gray-800">${escapeHtml(r.item_name || '-')}${r.spec ? ' <span class="text-gray-400">[' + escapeHtml(r.spec) + ']</span>' : ''}</div>
<div class="text-xs text-gray-500">${escapeHtml(r.maker || '')} · ${escapeHtml(r.requester_name || '')}</div>
</td>
<td class="px-4 py-3"><span class="px-1.5 py-0.5 rounded text-xs ${catColor}">${catLabel}</span></td>
<td class="px-4 py-3 text-right">${r.quantity}</td>
<td class="px-4 py-3 text-right">${r.unit_price ? Number(r.unit_price).toLocaleString() + '원' : '-'}</td>
<td class="px-4 py-3 text-gray-600">${escapeHtml(r.vendor_name || '-')}</td>
<td class="px-4 py-3 text-gray-600">${formatDateTime(r.received_at)}</td>
<td class="px-4 py-3 text-gray-600 text-xs">${escapeHtml(r.received_location || '-')}</td>
<td class="px-4 py-3 text-center"><span class="badge ${statusColor}">${statusLabel}</span></td>
</tr>`;
}).join('');
}
/* ===== 정산 처리 ===== */
async function completeSettlement(vendorId) {
if (!confirm('이 업체의 정산을 완료 처리하시겠습니까?')) return;
try {
await api('/settlements/complete', {
method: 'POST', body: JSON.stringify({ year_month: currentYearMonth, vendor_id: vendorId })
});
showToast('정산 완료 처리되었습니다.');
await loadAnalysis();
} catch (e) { showToast(e.message, 'error'); }
}
async function cancelSettlement(vendorId) {
if (!confirm('정산 완료를 취소하시겠습니까?')) return;
try {
await api('/settlements/cancel', {
method: 'POST', body: JSON.stringify({ year_month: currentYearMonth, vendor_id: vendorId })
});
showToast('정산이 취소되었습니다.');
await loadAnalysis();
} catch (e) { showToast(e.message, 'error'); }
}
/* ===== Init ===== */
(async function() {
if (!await initAuth()) return;
await loadCategories();
const now = new Date();
document.getElementById('paMonth').value = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
})();

View File

@@ -0,0 +1,491 @@
/* ===== 소모품 신청 모바일 (장바구니 방식) ===== */
const TKUSER_BASE_URL = location.hostname.includes('technicalkorea.net')
? 'https://tkuser.technicalkorea.net'
: location.protocol + '//' + location.hostname + ':30180';
// 카테고리 — API 동적 로드
let _categories = null;
async function loadCategories() {
if (_categories) return _categories;
try { const r = await api('/consumable-categories'); _categories = r.data || []; } catch(e) { _categories = []; }
return _categories;
}
function getCatLabel(code) { return (_categories || []).find(c => c.category_code === code)?.category_name || code || ''; }
const STATUS_LABELS = { pending: '대기', grouped: '구매진행중', purchased: '구매완료', received: '입고완료', cancelled: '취소', returned: '반품', hold: '보류' };
const STATUS_COLORS = { pending: 'badge-amber', grouped: 'badge-blue', purchased: 'badge-green', received: 'badge-teal', cancelled: 'badge-red', returned: 'badge-red', hold: 'badge-gray' };
const MATCH_LABELS = { exact: '정확', name: '이름', alias: '별칭', spec: '규격', chosung: '초성', chosung_alias: '초성' };
let currentPage = 1;
let currentStatus = '';
let totalPages = 1;
let isLoadingMore = false;
let requestsList = [];
let photoBase64 = null;
let searchTimer = null;
let lastSearchResults = [];
let cartItems = []; // [{item_id, item_name, spec, maker, category, quantity, notes, is_new, ...}]
/* ===== 상태 탭 필터 ===== */
function filterByStatus(btn) {
document.querySelectorAll('.pm-tab').forEach(t => t.classList.remove('active'));
btn.classList.add('active');
currentStatus = btn.dataset.status;
currentPage = 1;
requestsList = [];
loadRequests();
}
/* ===== 신청 목록 로드 ===== */
async function loadRequests(append = false) {
try {
if (!append) {
document.getElementById('requestCards').innerHTML = '<div class="pm-loading">불러오는 중...</div>';
}
const params = new URLSearchParams({ page: currentPage, limit: 20 });
if (currentStatus) params.set('status', currentStatus);
const res = await api('/purchase-requests/my-requests?' + params.toString());
const items = res.data || [];
totalPages = res.pagination?.totalPages || 1;
if (append) { requestsList = requestsList.concat(items); } else { requestsList = items; }
renderCards();
} catch (e) {
document.getElementById('requestCards').innerHTML = `<div class="pm-empty"><i class="fas fa-exclamation-circle"></i>${escapeHtml(e.message)}</div>`;
}
}
function renderCards() {
const container = document.getElementById('requestCards');
if (!requestsList.length) {
container.innerHTML = '<div class="pm-empty"><i class="fas fa-box-open"></i>신청 내역이 없습니다.</div>';
return;
}
container.innerHTML = requestsList.map(r => {
const itemName = r.item_name || r.custom_item_name || '-';
const category = r.category || r.custom_category;
const catLabel = getCatLabel(category);
const statusLabel = STATUS_LABELS[r.status] || r.status;
const statusColor = STATUS_COLORS[r.status] || 'badge-gray';
const isCustom = !r.item_id && r.custom_item_name;
return `<div class="pm-card" onclick="openDetail(${r.request_id})">
<div class="pm-card-header">
<div>
<div class="pm-card-name">${escapeHtml(itemName)}${isCustom ? '<span class="pm-card-custom">(직접입력)</span>' : ''}</div>
${catLabel ? `<span class="badge ${STATUS_COLORS[category] || 'badge-gray'} mt-1" style="font-size:11px">${catLabel}</span>` : ''}
</div>
<span class="badge ${statusColor}">${statusLabel}</span>
</div>
<div class="pm-card-meta">
<span>수량: <span class="pm-card-qty">${r.quantity}</span></span>
<span>${formatDate(r.request_date)}</span>
${r.batch_name ? `<span><i class="fas fa-layer-group"></i> ${escapeHtml(r.batch_name)}</span>` : ''}
</div>
</div>`;
}).join('');
}
/* ===== 무한 스크롤 ===== */
window.addEventListener('scroll', () => {
if (isLoadingMore || currentPage >= totalPages) return;
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 200) {
isLoadingMore = true;
currentPage++;
document.getElementById('loadingMore').classList.remove('hidden');
loadRequests(true).finally(() => {
isLoadingMore = false;
document.getElementById('loadingMore').classList.add('hidden');
});
}
});
/* ===== 상세 바텀시트 ===== */
function openDetail(requestId) {
const r = requestsList.find(x => x.request_id === requestId);
if (!r) return;
const itemName = r.item_name || r.custom_item_name || '-';
const category = r.category || r.custom_category;
const catLabel = getCatLabel(category);
const statusLabel = STATUS_LABELS[r.status] || r.status;
const statusColor = STATUS_COLORS[r.status] || 'badge-gray';
let html = `
<div class="text-center mb-4">
<div class="text-lg font-bold">${escapeHtml(itemName)}</div>
<span class="badge ${statusColor} mt-2">${statusLabel}</span>
</div>
<div class="pm-detail-row"><span class="pm-detail-label">분류</span><span class="pm-detail-value">${catLabel}</span></div>
<div class="pm-detail-row"><span class="pm-detail-label">수량</span><span class="pm-detail-value">${r.quantity}</span></div>
<div class="pm-detail-row"><span class="pm-detail-label">신청일</span><span class="pm-detail-value">${formatDate(r.request_date)}</span></div>`;
if (r.notes) html += `<div class="pm-detail-row"><span class="pm-detail-label">메모</span><span class="pm-detail-value">${escapeHtml(r.notes)}</span></div>`;
if (r.batch_name) html += `<div class="pm-detail-row"><span class="pm-detail-label">구매 그룹</span><span class="pm-detail-value">${escapeHtml(r.batch_name)}</span></div>`;
if (r.hold_reason) html += `<div class="pm-detail-row"><span class="pm-detail-label">보류 사유</span><span class="pm-detail-value text-red-600">${escapeHtml(r.hold_reason)}</span></div>`;
if (r.status === 'received') {
html += `<div class="mt-4 p-3 bg-teal-50 rounded-lg"><div class="text-sm font-semibold text-teal-700 mb-2"><i class="fas fa-box-open mr-1"></i>입고 완료</div>`;
if (r.received_location) html += `<div class="text-sm text-gray-700"><i class="fas fa-map-marker-alt mr-1 text-teal-500"></i>보관위치: ${escapeHtml(r.received_location)}</div>`;
if (r.received_at) html += `<div class="text-xs text-gray-500 mt-1">${formatDateTime(r.received_at)}${r.received_by_name ? ' · ' + escapeHtml(r.received_by_name) : ''}</div>`;
if (r.received_photo_path) html += `<img src="${r.received_photo_path}" class="pm-received-photo" onerror="this.style.display='none'">`;
html += `</div>`;
}
if (r.pr_photo_path) html += `<div class="mt-3"><div class="text-xs text-gray-500 mb-1">첨부 사진</div><img src="${r.pr_photo_path}" class="pm-received-photo" onerror="this.style.display='none'"></div>`;
document.getElementById('detailContent').innerHTML = html;
document.getElementById('detailOverlay').classList.add('open');
document.getElementById('detailSheet').classList.add('open');
}
function closeDetailSheet() {
document.getElementById('detailOverlay').classList.remove('open');
document.getElementById('detailSheet').classList.remove('open');
}
/* ===== 신청 바텀시트 ===== */
function openRequestSheet() {
document.getElementById('requestOverlay').classList.add('open');
document.getElementById('requestSheet').classList.add('open');
document.getElementById('searchInput').focus();
}
function closeRequestSheet() {
document.getElementById('requestOverlay').classList.remove('open');
document.getElementById('requestSheet').classList.remove('open');
resetRequestForm();
}
function resetRequestForm() {
document.getElementById('searchInput').value = '';
document.getElementById('searchResults').classList.remove('open');
cartItems = [];
renderCart();
document.getElementById('reqPhotoInput').value = '';
document.getElementById('reqPhotoPreview').classList.add('hidden');
document.getElementById('photoLabel').textContent = '사진 촬영/선택';
photoBase64 = null;
updateSubmitBtn();
}
/* ===== 서버 스마트 검색 ===== */
document.addEventListener('DOMContentLoaded', () => {
const input = document.getElementById('searchInput');
input.addEventListener('input', () => {
clearTimeout(searchTimer);
const q = input.value.trim();
if (q.length === 0) {
document.getElementById('searchResults').classList.remove('open');
document.getElementById('searchSpinner').classList.remove('show');
return;
}
document.getElementById('searchSpinner').classList.add('show');
searchTimer = setTimeout(async () => {
try {
const res = await api('/purchase-requests/search?q=' + encodeURIComponent(q));
renderSearchResults(res.data || [], q);
} catch (e) { console.error('검색 오류:', e); }
finally { document.getElementById('searchSpinner').classList.remove('show'); }
}, 300);
});
});
function renderSearchResults(items, query) {
lastSearchResults = items;
const container = document.getElementById('searchResults');
let html = '';
items.forEach(item => {
const catLabel = getCatLabel(item.category);
const matchLabel = MATCH_LABELS[item._matchType] || '';
const spec = item.spec ? ' [' + escapeHtml(item.spec) + ']' : '';
const maker = item.maker ? ' (' + escapeHtml(item.maker) + ')' : '';
const photoUrl = item.photo_path ? (item.photo_path.startsWith('http') ? item.photo_path : TKUSER_BASE_URL + item.photo_path) : '';
html += `<div class="pm-search-item" onclick="addToCart(${item.item_id})">
${photoUrl ? `<img src="${photoUrl}" class="pm-search-thumb" onerror="this.style.display='none'">` : '<div class="pm-search-thumb-empty"><i class="fas fa-box"></i></div>'}
<div class="flex-1">
<div class="text-sm font-medium">${escapeHtml(item.item_name)}${spec}${maker}</div>
${catLabel ? `<div class="text-xs text-gray-400 mt-0.5">${catLabel}</div>` : ''}
</div>
${matchLabel ? `<span class="match-type">${matchLabel}</span>` : ''}
</div>`;
});
html += `<div class="pm-search-register" onclick="addNewToCart()">
<i class="fas fa-plus-circle"></i>
<span>"${escapeHtml(query)}" 새 품목으로 추가</span>
</div>`;
container.innerHTML = html;
container.classList.add('open');
}
/* ===== 장바구니 ===== */
function addToCart(itemId) {
const item = lastSearchResults.find(i => i.item_id === itemId);
if (!item) return;
// 동일 품목이면 수량 +1
const existing = cartItems.find(c => c.item_id === item.item_id && !c.is_new);
if (existing) {
existing.quantity++;
showToast(`${item.item_name} 수량이 ${existing.quantity}개로 추가되었습니다.`);
} else {
cartItems.push({
item_id: item.item_id,
item_name: item.item_name,
spec: item.spec,
maker: item.maker,
category: item.category,
photo_path: item.photo_path,
quantity: 1,
notes: '',
is_new: false
});
}
document.getElementById('searchInput').value = '';
document.getElementById('searchResults').classList.remove('open');
renderCart();
updateSubmitBtn();
}
function addNewToCart() {
const query = document.getElementById('searchInput').value.trim();
if (!query) return;
cartItems.push({
item_id: null,
item_name: query,
spec: '',
maker: '',
category: '',
photo_path: null,
item_photo: null, // base64 — 마스터 사진으로 저장될 사진
quantity: 1,
notes: '',
is_new: true
});
document.getElementById('searchInput').value = '';
document.getElementById('searchResults').classList.remove('open');
renderCart();
updateSubmitBtn();
}
function removeFromCart(idx) {
cartItems.splice(idx, 1);
renderCart();
updateSubmitBtn();
}
function updateCartQty(idx, val) {
const qty = parseInt(val) || 1;
cartItems[idx].quantity = Math.max(1, qty);
}
function updateCartNotes(idx, val) {
cartItems[idx].notes = val;
}
function updateCartNewField(idx, field, val) {
cartItems[idx][field] = val;
}
function renderCart() {
const wrap = document.getElementById('cartWrap');
const list = document.getElementById('cartList');
const count = document.getElementById('cartCount');
if (cartItems.length === 0) {
wrap.classList.add('hidden');
return;
}
wrap.classList.remove('hidden');
count.textContent = cartItems.length + '건';
list.innerHTML = cartItems.map((c, idx) => {
const spec = c.spec ? ' [' + escapeHtml(c.spec) + ']' : '';
const maker = c.maker ? ' (' + escapeHtml(c.maker) + ')' : '';
const catLabel = getCatLabel(c.category);
// 사진 썸네일
let thumbHtml = '';
if (c.item_photo) {
thumbHtml = `<img src="${c.item_photo}" class="pm-cart-thumb">`;
} else if (c.photo_path) {
const url = c.photo_path.startsWith('http') ? c.photo_path : TKUSER_BASE_URL + c.photo_path;
thumbHtml = `<img src="${url}" class="pm-cart-thumb" onerror="this.style.display='none'">`;
}
let extraFields = '';
if (c.is_new) {
extraFields = `<div class="pm-cart-new-fields">
<input type="text" placeholder="규격" value="${escapeHtml(c.spec || '')}" oninput="updateCartNewField(${idx},'spec',this.value)">
<input type="text" placeholder="제조사" value="${escapeHtml(c.maker || '')}" oninput="updateCartNewField(${idx},'maker',this.value)">
<select onchange="updateCartNewField(${idx},'category',this.value)">
<option value="">분류</option>
<option value="consumable" ${c.category==='consumable'?'selected':''}>소모품</option>
<option value="safety" ${c.category==='safety'?'selected':''}>안전용품</option>
<option value="repair" ${c.category==='repair'?'selected':''}>수선비</option>
<option value="equipment" ${c.category==='equipment'?'selected':''}>설비</option>
</select>
</div>
<div class="pm-cart-new-fields" style="margin-top:4px">
<label class="pm-cart-photo-btn">
<i class="fas fa-camera"></i> ${c.item_photo ? '사진 변경' : '품목 사진'}
<input type="file" accept="image/*,.heic,.heif" capture="environment" class="hidden" onchange="onItemPhotoSelected(${idx},this)">
</label>
</div>`;
} else if (!c.photo_path) {
// 기존 품목이지만 사진 없음 → 사진 등록 가능
extraFields = `<div class="pm-cart-new-fields" style="margin-top:4px">
<label class="pm-cart-photo-btn">
<i class="fas fa-camera"></i> 품목 사진 등록
<input type="file" accept="image/*,.heic,.heif" capture="environment" class="hidden" onchange="uploadExistingItemPhoto(${idx},this)">
</label>
</div>`;
}
return `<div class="pm-cart-item">
${thumbHtml}
<div class="pm-cart-item-info">
<div class="pm-cart-item-name">${escapeHtml(c.item_name)}${spec}${maker}</div>
<div class="pm-cart-item-meta">${catLabel}${c.is_new ? ' <span class="pm-cart-item-new">(신규등록)</span>' : ''}</div>
${extraFields}
</div>
<input type="number" class="pm-cart-qty" value="${c.quantity}" min="1" inputmode="numeric" onchange="updateCartQty(${idx},this.value)">
<input type="text" class="pm-cart-memo" placeholder="메모" value="${escapeHtml(c.notes || '')}" oninput="updateCartNotes(${idx},this.value)">
<button class="pm-cart-remove" onclick="removeFromCart(${idx})">×</button>
</div>`;
}).join('');
}
function updateSubmitBtn() {
const btn = document.getElementById('submitBtn');
if (cartItems.length > 0) {
btn.disabled = false;
btn.textContent = cartItems.length + '건 신청하기';
} else {
btn.disabled = true;
btn.textContent = '품목을 추가해주세요';
}
}
/* ===== 품목 사진 (장바구니 내 신규/기존 품목) ===== */
async function onItemPhotoSelected(idx, inputEl) {
const file = inputEl.files[0];
if (!file) return;
let processFile = file;
const isHeic = file.type === 'image/heic' || file.type === 'image/heif' ||
file.name.toLowerCase().endsWith('.heic') || file.name.toLowerCase().endsWith('.heif');
if (isHeic && typeof heic2any !== 'undefined') {
try {
const blob = await heic2any({ blob: file, toType: 'image/jpeg', quality: 0.85 });
processFile = new File([blob], file.name.replace(/\.hei[cf]$/i, '.jpg'), { type: 'image/jpeg' });
} catch (e) { console.warn('HEIC 변환 실패:', e); }
}
if (processFile.size > 10 * 1024 * 1024) { showToast('10MB 이하만 가능합니다.', 'error'); return; }
const reader = new FileReader();
reader.onload = (e) => {
cartItems[idx].item_photo = e.target.result;
renderCart();
};
reader.readAsDataURL(processFile);
}
// 기존 품목(사진 없음)에 사진 업로드 → 마스터에 저장
async function uploadExistingItemPhoto(idx, inputEl) {
const file = inputEl.files[0];
if (!file) return;
let processFile = file;
const isHeic = file.type === 'image/heic' || file.type === 'image/heif' ||
file.name.toLowerCase().endsWith('.heic') || file.name.toLowerCase().endsWith('.heif');
if (isHeic && typeof heic2any !== 'undefined') {
try {
const blob = await heic2any({ blob: file, toType: 'image/jpeg', quality: 0.85 });
processFile = new File([blob], file.name.replace(/\.hei[cf]$/i, '.jpg'), { type: 'image/jpeg' });
} catch (e) { console.warn('HEIC 변환 실패:', e); }
}
if (processFile.size > 10 * 1024 * 1024) { showToast('10MB 이하만 가능합니다.', 'error'); return; }
const reader = new FileReader();
reader.onload = async (e) => {
const base64 = e.target.result;
try {
const res = await api(`/purchase-requests/consumable-items/${cartItems[idx].item_id}/photo`, {
method: 'PUT', body: JSON.stringify({ photo: base64 })
});
if (res.data?.photo_path) {
cartItems[idx].photo_path = res.data.photo_path;
cartItems[idx].item_photo = null;
}
showToast('품목 사진이 등록되었습니다.');
renderCart();
} catch (err) { showToast(err.message, 'error'); }
};
reader.readAsDataURL(processFile);
}
/* ===== 참고 사진 (신청 공통) ===== */
async function onMobilePhotoSelected(inputEl) {
const file = inputEl.files[0];
if (!file) return;
let processFile = file;
const isHeic = file.type === 'image/heic' || file.type === 'image/heif' ||
file.name.toLowerCase().endsWith('.heic') || file.name.toLowerCase().endsWith('.heif');
if (isHeic && typeof heic2any !== 'undefined') {
document.getElementById('photoLabel').textContent = '변환 중...';
try {
const blob = await heic2any({ blob: file, toType: 'image/jpeg', quality: 0.85 });
processFile = new File([blob], file.name.replace(/\.hei[cf]$/i, '.jpg'), { type: 'image/jpeg' });
} catch (e) { console.warn('HEIC 변환 실패, 원본 사용:', e); }
}
if (processFile.size > 10 * 1024 * 1024) {
showToast('파일 크기는 10MB 이하만 가능합니다.', 'error');
document.getElementById('photoLabel').textContent = '사진 촬영/선택';
return;
}
const reader = new FileReader();
reader.onload = (e) => {
photoBase64 = e.target.result;
document.getElementById('reqPhotoPreview').src = photoBase64;
document.getElementById('reqPhotoPreview').classList.remove('hidden');
document.getElementById('photoLabel').textContent = '사진 변경';
};
reader.readAsDataURL(processFile);
}
/* ===== 일괄 신청 제출 ===== */
async function submitRequest() {
if (cartItems.length === 0) { showToast('품목을 추가해주세요.', 'error'); return; }
const btn = document.getElementById('submitBtn');
btn.disabled = true;
btn.textContent = '처리 중...';
try {
const items = cartItems.map(c => {
if (c.is_new) {
return { item_name: c.item_name, spec: c.spec || null, maker: c.maker || null, category: c.category || null, quantity: c.quantity, notes: c.notes || null, is_new: true, item_photo: c.item_photo || null };
}
return { item_id: c.item_id, quantity: c.quantity, notes: c.notes || null };
});
const body = { items };
if (photoBase64) body.photo = photoBase64;
await api('/purchase-requests/bulk', { method: 'POST', body: JSON.stringify(body) });
showToast(`${cartItems.length}건 소모품 신청이 등록되었습니다.`);
closeRequestSheet();
currentPage = 1;
requestsList = [];
await loadRequests();
} catch (e) {
showToast(e.message, 'error');
} finally {
btn.disabled = false;
updateSubmitBtn();
}
}
/* ===== URL 파라미터로 상세 열기 ===== */
function checkViewParam() {
const urlParams = new URLSearchParams(location.search);
const viewId = urlParams.get('view');
if (viewId) setTimeout(() => openDetail(parseInt(viewId)), 500);
}
/* ===== Init ===== */
(async function() {
if (!await initAuth()) return;
await loadCategories();
await loadRequests();
checkViewParam();
})();

View File

@@ -0,0 +1,786 @@
/* ===== 소모품 신청 페이지 ===== */
const TKUSER_BASE_URL = location.hostname.includes('technicalkorea.net')
? 'https://tkuser.technicalkorea.net'
: location.protocol + '//' + location.hostname + ':30180';
// 카테고리 — API에서 동적 로드
let _categories = null;
async function loadCategories() {
if (_categories) return _categories;
try { const r = await api('/consumable-categories'); _categories = r.data || []; } catch(e) { _categories = []; }
return _categories;
}
function getCatLabel(code) { return (_categories || []).find(c => c.category_code === code)?.category_name || code || '-'; }
function getCatBg(code) { return (_categories || []).find(c => c.category_code === code)?.color_bg || '#f3f4f6'; }
function getCatFg(code) { return (_categories || []).find(c => c.category_code === code)?.color_fg || '#374151'; }
const STATUS_LABELS = { pending: '대기', grouped: '구매진행중', purchased: '구매완료', received: '입고완료', cancelled: '취소', returned: '반품', hold: '보류' };
const STATUS_COLORS = { pending: 'badge-amber', grouped: 'badge-blue', purchased: 'badge-green', received: 'badge-teal', cancelled: 'badge-red', returned: 'badge-red', hold: 'badge-gray' };
function _fmtSpec(spec) { return spec ? ' [' + spec + ']' : ''; }
let consumableItems = [];
let vendorsList = [];
let requestsList = [];
let currentRequestForPurchase = null;
let currentRequestForHold = null;
let isAdmin = false;
let photoBase64 = null;
let searchDebounceTimer = null;
let dropdownActiveIndex = -1;
let selectedRequestIds = new Set();
let batchesVisible = false;
async function loadInitialData() {
try {
const [itemsRes, vendorsRes] = await Promise.all([
api('/purchase-requests/consumable-items'),
api('/purchase-requests/vendors')
]);
consumableItems = itemsRes.data || [];
vendorsList = vendorsRes.data || [];
populateVendorSelect();
} catch (e) {
console.error('초기 데이터 로드 실패:', e);
}
}
function populateVendorSelect() {
const sel = document.getElementById('pmVendor');
sel.innerHTML = '<option value="">업체 선택 (선택사항)</option>' +
vendorsList.map(v => `<option value="${v.vendor_id}">${escapeHtml(v.vendor_name)}</option>`).join('');
}
/* ===== 검색형 품목 선택 ===== */
function initItemSearch() {
const input = document.getElementById('prItemSearch');
const dropdown = document.getElementById('prItemDropdown');
input.addEventListener('input', () => {
clearTimeout(searchDebounceTimer);
// 검색어 변경 시 이전 선택 자동 해제
if (document.getElementById('prItemId').value) {
document.getElementById('prItemId').value = '';
document.getElementById('prCustomItemName').value = '';
document.getElementById('prItemPreview').classList.add('hidden');
document.getElementById('prCustomCategoryWrap').classList.add('hidden');
}
searchDebounceTimer = setTimeout(() => {
const query = input.value.trim();
if (query.length === 0) {
// 빈 입력: 전체 목록 보여주기
showDropdown(consumableItems.slice(0, 30), '');
} else {
const lower = query.toLowerCase();
const filtered = consumableItems.filter(item =>
item.item_name.toLowerCase().includes(lower) ||
(item.maker && item.maker.toLowerCase().includes(lower)) ||
(item.spec && item.spec.toLowerCase().includes(lower))
);
showDropdown(filtered, query);
}
}, 200);
});
input.addEventListener('focus', () => {
const query = input.value.trim();
if (query.length === 0) {
showDropdown(consumableItems.slice(0, 30), '');
} else {
const lower = query.toLowerCase();
const filtered = consumableItems.filter(item =>
item.item_name.toLowerCase().includes(lower) ||
(item.maker && item.maker.toLowerCase().includes(lower)) ||
(item.spec && item.spec.toLowerCase().includes(lower))
);
showDropdown(filtered, query);
}
});
input.addEventListener('keydown', (e) => {
const items = dropdown.querySelectorAll('.item-dropdown-item, .item-dropdown-custom');
if (e.key === 'ArrowDown') {
e.preventDefault();
dropdownActiveIndex = Math.min(dropdownActiveIndex + 1, items.length - 1);
updateDropdownActive(items);
} else if (e.key === 'ArrowUp') {
e.preventDefault();
dropdownActiveIndex = Math.max(dropdownActiveIndex - 1, 0);
updateDropdownActive(items);
} else if (e.key === 'Enter') {
e.preventDefault();
if (dropdownActiveIndex >= 0 && dropdownActiveIndex < items.length) {
items[dropdownActiveIndex].click();
}
} else if (e.key === 'Escape') {
closeDropdown();
}
});
// 외부 클릭 시 드롭다운 닫기
document.addEventListener('click', (e) => {
if (!e.target.closest('#prItemSearch') && !e.target.closest('#prItemDropdown')) {
closeDropdown();
}
});
}
function showDropdown(items, query) {
const dropdown = document.getElementById('prItemDropdown');
dropdownActiveIndex = -1;
let html = '';
if (items.length > 0) {
items.forEach((item, idx) => {
const catLabel = getCatLabel(item.category);
const bg = getCatBg(item.category);
const fg = getCatFg(item.category);
const spec = _fmtSpec(item.spec ? escapeHtml(item.spec) : '');
const maker = item.maker ? ` (${escapeHtml(item.maker)})` : '';
const photoSrc = item.photo_path ? (item.photo_path.startsWith('http') ? item.photo_path : TKUSER_BASE_URL + item.photo_path) : '';
html += `<div class="item-dropdown-item" data-item-id="${item.item_id}" onclick="selectItem(${item.item_id})">
${photoSrc ? `<img src="${photoSrc}" style="width:28px;height:28px;border-radius:4px;object-fit:cover" onerror="this.style.display='none'">` : ''}
<span class="cat-tag" style="background:${bg};color:${fg}">${catLabel}</span>
<span>${escapeHtml(item.item_name)}${spec}${maker}</span>
</div>`;
});
}
// 직접 입력 옵션 (검색어가 있을 때만)
if (query.length > 0) {
html += `<div class="item-dropdown-custom" onclick="selectCustomItem()">
<i class="fas fa-plus-circle"></i>
<span>"${escapeHtml(query)}"(으)로 직접 신청</span>
</div>`;
}
if (html) {
dropdown.innerHTML = html;
dropdown.classList.add('open');
} else {
closeDropdown();
}
}
function updateDropdownActive(items) {
items.forEach((el, idx) => {
el.classList.toggle('active', idx === dropdownActiveIndex);
if (idx === dropdownActiveIndex) el.scrollIntoView({ block: 'nearest' });
});
}
function closeDropdown() {
document.getElementById('prItemDropdown').classList.remove('open');
dropdownActiveIndex = -1;
}
function selectItem(itemId) {
const item = consumableItems.find(i => i.item_id === itemId);
if (!item) return;
const input = document.getElementById('prItemSearch');
input.value = item.item_name + _fmtSpec(item.spec) + (item.maker ? ' (' + item.maker + ')' : '');
document.getElementById('prItemId').value = item.item_id;
document.getElementById('prCustomItemName').value = '';
closeDropdown();
// 미리보기
const preview = document.getElementById('prItemPreview');
preview.classList.remove('hidden');
const photoEl = document.getElementById('prItemPhoto');
if (item.photo_path) {
photoEl.src = TKUSER_BASE_URL + item.photo_path;
photoEl.classList.remove('hidden');
photoEl.onerror = () => photoEl.classList.add('hidden');
} else {
photoEl.classList.add('hidden');
}
document.getElementById('prItemInfo').textContent = `${item.item_name}${_fmtSpec(item.spec)} ${item.maker ? '(' + item.maker + ')' : ''}`;
const price = item.base_price ? Number(item.base_price).toLocaleString() + '원/' + (item.unit || 'EA') : '기준가 미설정';
document.getElementById('prItemPrice').textContent = price;
// 분류 선택 숨김
document.getElementById('prCustomCategoryWrap').classList.add('hidden');
}
function selectCustomItem() {
const input = document.getElementById('prItemSearch');
const customName = input.value.trim();
if (!customName) return;
document.getElementById('prItemId').value = '';
document.getElementById('prCustomItemName').value = customName;
closeDropdown();
// 미리보기 숨기고 분류 선택 표시
document.getElementById('prItemPreview').classList.add('hidden');
document.getElementById('prCustomCategoryWrap').classList.remove('hidden');
}
/* ===== 사진 첨부 ===== */
async function onPhotoSelected(inputEl) {
const file = inputEl.files[0];
if (!file) return;
const statusEl = document.getElementById('prPhotoStatus');
let processFile = file;
// HEIC/HEIF 변환
const isHeic = file.type === 'image/heic' || file.type === 'image/heif' ||
file.name.toLowerCase().endsWith('.heic') || file.name.toLowerCase().endsWith('.heif');
if (isHeic) {
if (typeof heic2any === 'undefined') {
showToast('HEIC 변환 라이브러리를 불러오지 못했습니다.', 'error');
return;
}
statusEl.textContent = 'HEIC 변환 중...';
try {
const blob = await heic2any({ blob: file, toType: 'image/jpeg', quality: 0.85 });
processFile = new File([blob], file.name.replace(/\.heic$/i, '.jpg').replace(/\.heif$/i, '.jpg'), { type: 'image/jpeg' });
} catch (e) {
console.error('HEIC 변환 실패:', e);
showToast('HEIC 이미지 변환에 실패했습니다.', 'error');
statusEl.textContent = '';
return;
}
}
// 파일 크기 확인 (10MB)
if (processFile.size > 10 * 1024 * 1024) {
showToast('파일 크기는 10MB 이하만 가능합니다.', 'error');
return;
}
statusEl.textContent = '처리 중...';
const reader = new FileReader();
reader.onload = (e) => {
photoBase64 = e.target.result;
document.getElementById('prPhotoPreviewImg').src = photoBase64;
document.getElementById('prPhotoPreview').classList.remove('hidden');
statusEl.textContent = '';
};
reader.readAsDataURL(processFile);
}
function removePhoto() {
photoBase64 = null;
document.getElementById('prPhotoPreview').classList.add('hidden');
document.getElementById('prPhotoInput').value = '';
document.getElementById('prPhotoStatus').textContent = '';
}
/* ===== 소모품 신청 제출 ===== */
async function submitPurchaseRequest() {
const itemId = document.getElementById('prItemId').value;
const customItemName = document.getElementById('prCustomItemName').value;
const quantity = parseInt(document.getElementById('prQuantity').value) || 0;
const notes = document.getElementById('prNotes').value.trim();
if (!itemId && !customItemName) { showToast('소모품을 선택하거나 품목명을 입력해주세요.', 'error'); return; }
if (quantity < 1) { showToast('수량은 1 이상이어야 합니다.', 'error'); return; }
const body = { quantity, notes };
if (itemId) {
body.item_id = parseInt(itemId);
} else {
body.custom_item_name = customItemName;
body.custom_category = document.getElementById('prCustomCategory').value;
}
if (photoBase64) {
body.photo = photoBase64;
}
try {
await api('/purchase-requests', {
method: 'POST',
body: JSON.stringify(body)
});
showToast('소모품 신청이 등록되었습니다.');
// 폼 초기화
document.getElementById('prItemSearch').value = '';
document.getElementById('prItemId').value = '';
document.getElementById('prCustomItemName').value = '';
document.getElementById('prQuantity').value = '1';
document.getElementById('prNotes').value = '';
document.getElementById('prItemPreview').classList.add('hidden');
document.getElementById('prCustomCategoryWrap').classList.add('hidden');
removePhoto();
await loadRequests();
} catch (e) { showToast(e.message, 'error'); }
}
/* ===== 신청 목록 ===== */
async function loadRequests() {
try {
const status = document.getElementById('prFilterStatus').value;
const category = document.getElementById('prFilterCategory').value;
const params = new URLSearchParams();
if (status) params.set('status', status);
if (category) params.set('category', category);
const res = await api('/purchase-requests?' + params.toString());
requestsList = res.data || [];
renderRequests();
} catch (e) {
document.getElementById('prRequestList').innerHTML = `<tr><td colspan="7" class="px-4 py-8 text-center text-red-500">${escapeHtml(e.message)}</td></tr>`;
}
}
function renderRequests() {
const tbody = document.getElementById('prRequestList');
selectedRequestIds.clear();
updateSelectedCount();
// admin이면 체크박스 열 보이기, 그룹 버튼 보이기
if (isAdmin) {
document.getElementById('thCheckbox').style.display = '';
document.getElementById('batchActions').classList.remove('hidden');
document.getElementById('batchViewBtn').classList.remove('hidden');
}
if (!requestsList.length) {
tbody.innerHTML = `<tr><td colspan="${isAdmin ? 8 : 7}" class="px-4 py-8 text-center text-gray-400">소모품 신청 내역이 없습니다.</td></tr>`;
return;
}
tbody.innerHTML = requestsList.map(r => {
// 등록 품목이면 ci 데이터, 미등록이면 custom 데이터 사용
const itemName = r.item_name || r.custom_item_name || '-';
const category = r.category || r.custom_category;
const catLabel = getCatLabel(category);
const catColor = 'badge-gray';
const statusLabel = STATUS_LABELS[r.status] || r.status;
const statusColor = STATUS_COLORS[r.status] || 'badge-gray';
const isCustom = !r.item_id && r.custom_item_name;
// 사진: 구매신청 첨부 사진 우선, 없으면 소모품 마스터 사진
let photoSrc = '';
if (r.pr_photo_path) {
photoSrc = r.pr_photo_path;
} else if (r.ci_photo_path) {
photoSrc = TKUSER_BASE_URL + r.ci_photo_path;
}
let actions = '';
if (isAdmin && r.status === 'pending') {
actions = `<button onclick="openPurchaseModal(${r.request_id})" class="px-2 py-1 bg-orange-500 text-white rounded text-xs hover:bg-orange-600 mr-1" title="구매 처리"><i class="fas fa-shopping-cart"></i></button>
<button onclick="openHoldModal(${r.request_id})" class="px-2 py-1 bg-gray-400 text-white rounded text-xs hover:bg-gray-500" title="보류"><i class="fas fa-pause"></i></button>`;
} else if (isAdmin && r.status === 'grouped') {
actions = `<button onclick="openPurchaseModal(${r.request_id})" class="px-2 py-1 bg-orange-500 text-white rounded text-xs hover:bg-orange-600 mr-1" title="구매 처리"><i class="fas fa-shopping-cart"></i></button>
<button onclick="openHoldModal(${r.request_id})" class="px-2 py-1 bg-gray-400 text-white rounded text-xs hover:bg-gray-500" title="보류"><i class="fas fa-pause"></i></button>`;
} else if (isAdmin && r.status === 'purchased') {
actions = `<button onclick="openReceiveModal(${r.request_id})" class="px-2 py-1 bg-teal-500 text-white rounded text-xs hover:bg-teal-600 mr-1" title="입고 처리"><i class="fas fa-box-open"></i></button>
<button onclick="cancelPurchase(${r.request_id})" class="px-2 py-1 bg-red-400 text-white rounded text-xs hover:bg-red-500" title="구매 취소"><i class="fas fa-times"></i></button>`;
} else if (isAdmin && r.status === 'received') {
actions = `<button onclick="returnItem(${r.request_id})" class="px-2 py-1 bg-red-500 text-white rounded text-xs hover:bg-red-600" title="반품"><i class="fas fa-undo-alt"></i></button>`;
} else if (isAdmin && r.status === 'cancelled') {
actions = `<button onclick="revertCancel(${r.request_id})" class="px-2 py-1 bg-blue-500 text-white rounded text-xs hover:bg-blue-600" title="대기로 되돌리기"><i class="fas fa-undo"></i></button>`;
} else if (isAdmin && r.status === 'hold') {
actions = `<button onclick="revertRequest(${r.request_id})" class="px-2 py-1 bg-blue-500 text-white rounded text-xs hover:bg-blue-600" title="대기로 되돌리기"><i class="fas fa-undo"></i></button>`;
}
if (r.status === 'pending' && (isAdmin || r.requester_id === currentUser.id)) {
actions += ` <button onclick="deleteRequest(${r.request_id})" class="px-2 py-1 bg-red-400 text-white rounded text-xs hover:bg-red-500" title="삭제"><i class="fas fa-trash"></i></button>`;
}
const cbCell = isAdmin && r.status === 'pending'
? `<td class="px-2 py-3 text-center" style="${isAdmin ? '' : 'display:none'}"><input type="checkbox" class="request-cb h-4 w-4" data-id="${r.request_id}" onchange="onRequestChecked()"></td>`
: `<td class="px-2 py-3" style="${isAdmin ? '' : 'display:none'}"></td>`;
return `<tr class="hover:bg-gray-50">
${cbCell}
<td class="px-4 py-3">
<div class="flex items-center gap-2">
${photoSrc ? `<img src="${photoSrc}" class="w-8 h-8 rounded object-cover" onerror="this.style.display='none'">` : ''}
<div>
<div class="font-medium text-gray-800">${escapeHtml(itemName)}${r.spec ? ' <span class="text-gray-400">[' + escapeHtml(r.spec) + ']</span>' : ''}${isCustom ? ' <span class="text-xs text-orange-500">(직접입력)</span>' : ''}</div>
<div class="text-xs text-gray-500">${escapeHtml(r.maker || '')}${r.batch_name ? ' <span class="text-blue-500"><i class="fas fa-layer-group"></i> ' + escapeHtml(r.batch_name) + '</span>' : ''}</div>
</div>
</div>
</td>
<td class="px-4 py-3"><span class="badge ${catColor}">${catLabel}</span></td>
<td class="px-4 py-3 text-right font-medium">${r.quantity}</td>
<td class="px-4 py-3 text-gray-600">${escapeHtml(r.requester_name || '')}</td>
<td class="px-4 py-3 text-gray-600">${formatDate(r.request_date)}</td>
<td class="px-4 py-3 text-center">
<span class="badge ${statusColor}">${statusLabel}</span>
${r.status === 'hold' && r.hold_reason ? `<div class="text-xs text-gray-400 mt-1">${escapeHtml(r.hold_reason)}</div>` : ''}
</td>
<td class="px-4 py-3 text-center">${actions}</td>
</tr>`;
}).join('');
}
/* ===== 구매 처리 모달 ===== */
function openPurchaseModal(requestId) {
const r = requestsList.find(x => x.request_id === requestId);
if (!r) return;
currentRequestForPurchase = r;
const itemName = r.item_name || r.custom_item_name || '-';
const category = r.category || r.custom_category;
const isCustom = !r.item_id && r.custom_item_name;
const basePrice = r.base_price ? Number(r.base_price).toLocaleString() + '원' : '-';
document.getElementById('purchaseModalInfo').innerHTML = `
<div class="font-medium">${escapeHtml(itemName)}${_fmtSpec(r.spec ? escapeHtml(r.spec) : '')} ${r.maker ? '(' + escapeHtml(r.maker) + ')' : ''}${isCustom ? ' <span class="text-orange-500 text-xs">(직접입력)</span>' : ''}</div>
<div class="text-xs text-gray-500 mt-1">분류: ${getCatLabel(category)} | 기준가: ${basePrice} | 신청수량: ${r.quantity}</div>
${r.pr_photo_path ? `<img src="${r.pr_photo_path}" class="mt-2 w-20 h-20 rounded object-cover" onerror="this.style.display='none'">` : ''}
`;
document.getElementById('pmUnitPrice').value = r.base_price || '';
document.getElementById('pmQuantity').value = r.quantity;
document.getElementById('pmDate').value = new Date().toISOString().substring(0, 10);
document.getElementById('pmNotes').value = '';
document.getElementById('pmPriceDiffArea').innerHTML = '';
// 마스터 등록 체크박스: 미등록 품목일 때만 표시
const masterWrap = document.getElementById('pmMasterRegisterWrap');
if (isCustom) {
masterWrap.classList.remove('hidden');
document.getElementById('pmRegisterToMaster').checked = true;
} else {
masterWrap.classList.add('hidden');
}
document.getElementById('purchaseModal').classList.remove('hidden');
showPriceDiff();
}
function closePurchaseModal() {
document.getElementById('purchaseModal').classList.add('hidden');
currentRequestForPurchase = null;
}
function showPriceDiff() {
if (!currentRequestForPurchase) return;
const basePrice = Number(currentRequestForPurchase.base_price) || 0;
const unitPrice = Number(document.getElementById('pmUnitPrice').value) || 0;
const area = document.getElementById('pmPriceDiffArea');
if (basePrice > 0 && unitPrice > 0 && basePrice !== unitPrice) {
const diff = unitPrice - basePrice;
const arrow = diff > 0 ? '&#9650;' : '&#9660;';
const color = diff > 0 ? 'text-red-600' : 'text-blue-600';
area.innerHTML = `
<div class="flex items-center gap-2 text-sm ${color}">
<span>기준가 ${basePrice.toLocaleString()}원 &rarr; 실구매가 ${unitPrice.toLocaleString()}${arrow}${Math.abs(diff).toLocaleString()}</span>
</div>
<label class="flex items-center gap-2 mt-1 cursor-pointer">
<input type="checkbox" id="pmUpdateBasePrice" class="h-4 w-4 rounded">
<span class="text-xs text-gray-600">기준가를 ${unitPrice.toLocaleString()}원으로 업데이트</span>
</label>`;
} else {
area.innerHTML = '';
}
}
async function submitPurchase() {
if (!currentRequestForPurchase) return;
const unit_price = Number(document.getElementById('pmUnitPrice').value);
const purchase_date = document.getElementById('pmDate').value;
if (!unit_price) { showToast('구매 단가를 입력해주세요.', 'error'); return; }
if (!purchase_date) { showToast('구매일을 입력해주세요.', 'error'); return; }
const updateCheckbox = document.getElementById('pmUpdateBasePrice');
const registerCheckbox = document.getElementById('pmRegisterToMaster');
const isCustom = !currentRequestForPurchase.item_id && currentRequestForPurchase.custom_item_name;
const body = {
request_id: currentRequestForPurchase.request_id,
item_id: currentRequestForPurchase.item_id || null,
vendor_id: parseInt(document.getElementById('pmVendor').value) || null,
quantity: parseInt(document.getElementById('pmQuantity').value) || currentRequestForPurchase.quantity,
unit_price,
purchase_date,
update_base_price: updateCheckbox ? updateCheckbox.checked : false,
register_to_master: isCustom ? (registerCheckbox ? registerCheckbox.checked : true) : undefined,
notes: document.getElementById('pmNotes').value.trim()
};
try {
const res = await api('/purchases', { method: 'POST', body: JSON.stringify(body) });
let msg = '구매 처리가 완료되었습니다.';
if (res.data?.equipment?.success) msg += ` 설비 ${res.data.equipment.equipment_code} 자동 등록됨.`;
else if (res.data?.equipment && !res.data.equipment.success) msg += ' (설비 자동 등록 실패 - 수동 등록 필요)';
showToast(msg);
closePurchaseModal();
await loadRequests();
} catch (e) { showToast(e.message, 'error'); }
}
/* ===== 보류 모달 ===== */
function openHoldModal(requestId) {
currentRequestForHold = requestId;
document.getElementById('holdReason').value = '';
document.getElementById('holdModal').classList.remove('hidden');
}
function closeHoldModal() {
document.getElementById('holdModal').classList.add('hidden');
currentRequestForHold = null;
}
async function submitHold() {
if (!currentRequestForHold) return;
const hold_reason = document.getElementById('holdReason').value.trim();
try {
await api(`/purchase-requests/${currentRequestForHold}/hold`, {
method: 'PUT',
body: JSON.stringify({ hold_reason })
});
showToast('보류 처리되었습니다.');
closeHoldModal();
await loadRequests();
} catch (e) { showToast(e.message, 'error'); }
}
/* ===== 기타 액션 ===== */
async function revertRequest(requestId) {
if (!confirm('이 신청을 대기 상태로 되돌리시겠습니까?')) return;
try {
await api(`/purchase-requests/${requestId}/revert`, { method: 'PUT' });
showToast('대기 상태로 되돌렸습니다.');
await loadRequests();
} catch (e) { showToast(e.message, 'error'); }
}
async function deleteRequest(requestId) {
if (!confirm('이 소모품 신청을 삭제하시겠습니까?')) return;
try {
await api(`/purchase-requests/${requestId}`, { method: 'DELETE' });
showToast('삭제되었습니다.');
await loadRequests();
} catch (e) { showToast(e.message, 'error'); }
}
/* ===== 그룹화 기능 ===== */
function onRequestChecked() {
selectedRequestIds.clear();
document.querySelectorAll('.request-cb:checked').forEach(cb => {
selectedRequestIds.add(parseInt(cb.dataset.id));
});
updateSelectedCount();
}
function updateSelectedCount() {
const el = document.getElementById('selectedCount');
if (el) el.textContent = selectedRequestIds.size + '건 선택';
}
function toggleSelectAll(masterCb) {
document.querySelectorAll('.request-cb').forEach(cb => {
cb.checked = masterCb.checked;
});
onRequestChecked();
}
function openBatchCreateModal() {
if (selectedRequestIds.size === 0) { showToast('그룹에 포함할 신청 건을 선택해주세요.', 'error'); return; }
document.getElementById('batchSelectedInfo').textContent = `${selectedRequestIds.size}건의 신청을 그룹으로 묶습니다.`;
document.getElementById('bcName').value = '';
document.getElementById('bcCategory').value = '';
document.getElementById('bcNotes').value = '';
// 업체 셀렉트 채우기
const sel = document.getElementById('bcVendor');
sel.innerHTML = '<option value="">업체 선택</option>' +
vendorsList.map(v => `<option value="${v.vendor_id}">${escapeHtml(v.vendor_name)}</option>`).join('');
document.getElementById('batchCreateModal').classList.remove('hidden');
}
function closeBatchCreateModal() {
document.getElementById('batchCreateModal').classList.add('hidden');
}
async function submitBatchCreate() {
const body = {
batch_name: document.getElementById('bcName').value.trim() || null,
category: document.getElementById('bcCategory').value || null,
vendor_id: parseInt(document.getElementById('bcVendor').value) || null,
notes: document.getElementById('bcNotes').value.trim() || null,
request_ids: Array.from(selectedRequestIds)
};
try {
await api('/purchase-batches', { method: 'POST', body: JSON.stringify(body) });
showToast('구매 그룹이 생성되었습니다.');
closeBatchCreateModal();
selectedRequestIds.clear();
await loadRequests();
if (batchesVisible) await loadBatches();
} catch (e) { showToast(e.message, 'error'); }
}
function toggleBatchView() {
batchesVisible = !batchesVisible;
document.getElementById('batchView').classList.toggle('hidden', !batchesVisible);
if (batchesVisible) loadBatches();
}
async function loadBatches() {
try {
const res = await api('/purchase-batches');
const batches = res.data || [];
const container = document.getElementById('batchList');
if (!batches.length) {
container.innerHTML = '<div class="text-gray-400 text-center py-4">생성된 그룹이 없습니다.</div>';
return;
}
const BATCH_STATUS = { pending: { label: '진행중', color: 'badge-blue' }, purchased: { label: '구매완료', color: 'badge-green' }, received: { label: '입고완료', color: 'badge-teal' } };
container.innerHTML = batches.map(b => {
const s = BATCH_STATUS[b.status] || { label: b.status, color: 'badge-gray' };
return `<div class="flex items-center justify-between p-3 border rounded-lg hover:bg-gray-50">
<div>
<span class="font-medium">${escapeHtml(b.batch_name || '그룹 #' + b.batch_id)}</span>
<span class="badge ${s.color} ml-2">${s.label}</span>
<span class="text-xs text-gray-400 ml-2">${b.request_count || 0}건</span>
${b.vendor_name ? `<span class="text-xs text-gray-400 ml-1">· ${escapeHtml(b.vendor_name)}</span>` : ''}
</div>
<div class="flex gap-1">
${b.status === 'pending' ? `<button onclick="batchPurchase(${b.batch_id})" class="px-2 py-1 bg-orange-500 text-white rounded text-xs hover:bg-orange-600" title="일괄 구매"><i class="fas fa-shopping-cart"></i></button>
<button onclick="batchDelete(${b.batch_id})" class="px-2 py-1 bg-red-400 text-white rounded text-xs hover:bg-red-500" title="삭제"><i class="fas fa-trash"></i></button>` : ''}
${b.status === 'purchased' ? `<button onclick="batchReceive(${b.batch_id})" class="px-2 py-1 bg-teal-500 text-white rounded text-xs hover:bg-teal-600" title="일괄 입고"><i class="fas fa-box-open"></i></button>` : ''}
</div>
</div>`;
}).join('');
} catch (e) { console.error('그룹 목록 로드 실패:', e); }
}
async function batchPurchase(batchId) {
if (!confirm('이 그룹의 모든 신청을 구매완료 처리하시겠습니까?')) return;
try {
await api(`/purchase-batches/${batchId}/purchase`, { method: 'POST' });
showToast('일괄 구매 처리 완료.');
await Promise.all([loadRequests(), loadBatches()]);
} catch (e) { showToast(e.message, 'error'); }
}
async function batchDelete(batchId) {
if (!confirm('이 그룹을 삭제하시겠습니까? 포함된 신청은 대기 상태로 복원됩니다.')) return;
try {
await api(`/purchase-batches/${batchId}`, { method: 'DELETE' });
showToast('그룹이 삭제되었습니다.');
await Promise.all([loadRequests(), loadBatches()]);
} catch (e) { showToast(e.message, 'error'); }
}
async function batchReceive(batchId) {
// 간단한 입고 — 위치만 입력
const location = prompt('보관 위치를 입력하세요 (선택):');
if (location === null) return; // 취소
try {
await api(`/purchase-batches/${batchId}/receive`, {
method: 'PUT',
body: JSON.stringify({ received_location: location || null })
});
showToast('일괄 입고 처리 완료.');
await Promise.all([loadRequests(), loadBatches()]);
} catch (e) { showToast(e.message, 'error'); }
}
/* ===== 구매 취소 / 반품 / 되돌리기 ===== */
async function cancelPurchase(requestId) {
const reason = prompt('취소 사유를 입력하세요 (선택):');
if (reason === null) return;
try {
await api(`/purchase-requests/${requestId}/cancel`, {
method: 'PUT', body: JSON.stringify({ cancel_reason: reason || null })
});
showToast('구매가 취소되었습니다.');
await loadRequests();
} catch (e) { showToast(e.message, 'error'); }
}
async function returnItem(requestId) {
const reason = prompt('반품 사유를 입력하세요:');
if (reason === null) return;
try {
await api(`/purchase-requests/${requestId}/return`, {
method: 'PUT', body: JSON.stringify({ cancel_reason: reason || null })
});
showToast('반품 처리되었습니다.');
await loadRequests();
} catch (e) { showToast(e.message, 'error'); }
}
async function revertCancel(requestId) {
if (!confirm('이 신청을 대기 상태로 되돌리시겠습니까?')) return;
try {
await api(`/purchase-requests/${requestId}/revert-cancel`, { method: 'PUT' });
showToast('대기 상태로 되돌렸습니다.');
await loadRequests();
} catch (e) { showToast(e.message, 'error'); }
}
/* ===== 입고 처리 모달 ===== */
let currentRequestForReceive = null;
let receivePhotoBase64 = null;
function openReceiveModal(requestId) {
const r = requestsList.find(x => x.request_id === requestId);
if (!r) return;
currentRequestForReceive = r;
const itemName = r.item_name || r.custom_item_name || '-';
document.getElementById('receiveModalInfo').innerHTML = `
<div class="font-medium">${escapeHtml(itemName)}</div>
<div class="text-xs text-gray-500 mt-1">수량: ${r.quantity} | 신청자: ${escapeHtml(r.requester_name || '')}</div>
`;
document.getElementById('rcLocation').value = '';
receivePhotoBase64 = null;
document.getElementById('rcPhotoPreview').classList.add('hidden');
document.getElementById('rcPhotoInput').value = '';
document.getElementById('receiveModal').classList.remove('hidden');
}
function closeReceiveModal() {
document.getElementById('receiveModal').classList.add('hidden');
currentRequestForReceive = null;
receivePhotoBase64 = null;
}
async function onReceivePhotoSelected(inputEl) {
const file = inputEl.files[0];
if (!file) return;
let processFile = file;
const isHeic = file.type === 'image/heic' || file.type === 'image/heif' ||
file.name.toLowerCase().endsWith('.heic') || file.name.toLowerCase().endsWith('.heif');
if (isHeic && typeof heic2any !== 'undefined') {
try {
const blob = await heic2any({ blob: file, toType: 'image/jpeg', quality: 0.85 });
processFile = new File([blob], file.name.replace(/\.hei[cf]$/i, '.jpg'), { type: 'image/jpeg' });
} catch (e) {
// 변환 실패 시 원본 시도
console.warn('HEIC 변환 실패, 원본 사용:', e);
}
}
if (processFile.size > 10 * 1024 * 1024) { showToast('파일 크기는 10MB 이하만 가능합니다.', 'error'); return; }
const reader = new FileReader();
reader.onload = (e) => {
receivePhotoBase64 = e.target.result;
document.getElementById('rcPhotoPreviewImg').src = receivePhotoBase64;
document.getElementById('rcPhotoPreview').classList.remove('hidden');
};
reader.readAsDataURL(processFile);
}
async function submitReceive() {
if (!currentRequestForReceive) return;
const received_location = document.getElementById('rcLocation').value.trim();
const body = { received_location };
if (receivePhotoBase64) body.photo = receivePhotoBase64;
try {
await api(`/purchase-requests/${currentRequestForReceive.request_id}/receive`, {
method: 'PUT',
body: JSON.stringify(body)
});
showToast('입고 처리가 완료되었습니다.');
closeReceiveModal();
await loadRequests();
} catch (e) { showToast(e.message, 'error'); }
}
/* ===== Init ===== */
(async function() {
if (!await initAuth()) return;
isAdmin = currentUser && ['admin', 'system', 'system admin'].includes(currentUser.role);
await loadCategories();
initItemSearch();
await loadInitialData();
await loadRequests();
})();

View File

@@ -0,0 +1,34 @@
/**
* shared-bottom-nav.js — 하단 네비게이션 공유 컴포넌트
* 각 페이지에서 <script src="/static/js/shared-bottom-nav.js"></script> 로드하면 자동 생성
*/
(function() {
var SVG_ATTR = 'viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"';
var NAV_ITEMS = [
{
href: '/pages/dashboard-new.html',
label: '홈',
icon: '<svg ' + SVG_ATTR + '><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>'
},
{
href: 'https://tkreport.technicalkorea.net/',
label: '신고',
icon: '<svg ' + SVG_ATTR + '><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>'
},
{
href: '/pages/purchase/request-mobile.html',
label: '소모품',
icon: '<svg ' + SVG_ATTR + '><path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6"/><path d="M16 10a4 4 0 0 1-8 0"/></svg>'
}
];
var currentPath = location.pathname;
var nav = document.createElement('nav');
nav.className = 'm-bottom-nav';
nav.innerHTML = NAV_ITEMS.map(function(item) {
var active = currentPath === item.href ? ' active' : '';
return '<a href="' + item.href + '" class="m-nav-item' + active + '">'
+ item.icon + '<span class="m-nav-label">' + item.label + '</span></a>';
}).join('');
document.body.appendChild(nav);
})();

View File

@@ -0,0 +1,336 @@
/* ===== 서비스 워커 등록 (Network-First 캐시) ===== */
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(function(reg) {
// 기존 SW가 있을 때만 업데이트 감지 (최초 설치 시 토스트 방지)
if (!navigator.serviceWorker.controller) return;
reg.addEventListener('updatefound', function() {
var newSW = reg.installing;
newSW.addEventListener('statechange', function() {
if (newSW.state === 'activated') {
showToast('새 버전이 적용되었습니다.', 'info');
setTimeout(function() { location.reload(); }, 1500);
}
});
});
});
}
/* ===== Config ===== */
const API_BASE = '/api';
const _tkuserBase = location.hostname.includes('technicalkorea.net')
? 'https://tkuser.technicalkorea.net'
: `http://${location.hostname}:30380`;
const _tksupportBase = location.hostname.includes('technicalkorea.net')
? 'https://tksupport.technicalkorea.net'
: `http://${location.hostname}:30680`;
const _tkqcBase = location.hostname.includes('technicalkorea.net')
? 'https://tkqc.technicalkorea.net'
: `http://${location.hostname}:30280`;
/* ===== Token ===== */
function _cookieGet(n) { const m = document.cookie.match(new RegExp('(?:^|; )' + n + '=([^;]*)')); return m ? decodeURIComponent(m[1]) : null; }
function _cookieRemove(n) { let c = n + '=; path=/; max-age=0'; if (location.hostname.includes('technicalkorea.net')) c += '; domain=.technicalkorea.net; secure; samesite=lax'; document.cookie = c; }
function getToken() { return _cookieGet('sso_token') || localStorage.getItem('sso_token'); }
function getLoginUrl() {
const h = location.hostname;
const t = Date.now();
if (h.includes('technicalkorea.net')) return location.protocol + '//tkfb.technicalkorea.net/dashboard?redirect=' + encodeURIComponent(location.href) + '&_t=' + t;
return location.protocol + '//' + h + ':30780/dashboard?redirect=' + encodeURIComponent(location.href) + '&_t=' + t;
}
function decodeToken(t) { try { const b = atob(t.split('.')[1].replace(/-/g,'+').replace(/_/g,'/')); return JSON.parse(new TextDecoder().decode(Uint8Array.from(b, c => c.charCodeAt(0)))); } catch { return null; } }
/* ===== 리다이렉트 루프 방지 ===== */
const _REDIRECT_KEY = '_sso_redirect_ts';
function _safeRedirect() {
const last = parseInt(sessionStorage.getItem(_REDIRECT_KEY) || '0', 10);
if (Date.now() - last < 5000) { console.warn('[tkfb] 리다이렉트 루프 감지'); return; }
sessionStorage.setItem(_REDIRECT_KEY, String(Date.now()));
location.href = getLoginUrl();
}
/* ===== API ===== */
async function api(path, opts = {}) {
const token = getToken();
const headers = { 'Authorization': token ? `Bearer ${token}` : '', ...(opts.headers||{}) };
if (!(opts.body instanceof FormData)) headers['Content-Type'] = 'application/json';
const res = await fetch(API_BASE + path, { ...opts, headers });
if (res.status === 401) { _safeRedirect(); throw new Error('인증 만료'); }
if (res.headers.get('content-type')?.includes('text/csv')) return res;
const data = await res.json();
if (!res.ok) throw new Error(data.error || data.message || '요청 실패');
return data;
}
/* ===== Toast ===== */
function showToast(msg, type = 'success') {
document.querySelector('.toast-message')?.remove();
const el = document.createElement('div');
el.className = `toast-message fixed bottom-4 right-4 px-4 py-3 rounded-lg text-white z-[10000] shadow-lg ${type==='success'?'bg-orange-500':'bg-red-500'}`;
el.innerHTML = `<i class="fas ${type==='success'?'fa-check-circle':'fa-exclamation-circle'} mr-2"></i>${escapeHtml(msg)}`;
document.body.appendChild(el);
setTimeout(() => { el.classList.add('opacity-0'); setTimeout(() => el.remove(), 300); }, 3000);
}
/* ===== Escape ===== */
function escapeHtml(str) { if (!str) return ''; const d = document.createElement('div'); d.textContent = str; return d.innerHTML; }
/* ===== Helpers ===== */
function formatDate(d) { if (!d) return ''; return String(d).substring(0, 10); }
function formatTime(d) { if (!d) return ''; return String(d).substring(11, 16); }
function formatDateTime(d) { if (!d) return ''; return String(d).substring(0, 16).replace('T', ' '); }
function debounce(fn, ms) { let t; return function(...args) { clearTimeout(t); t = setTimeout(() => fn.apply(this, args), ms); }; }
/* ===== Logout ===== */
function doLogout() {
if (!confirm('로그아웃?')) return;
_cookieRemove('sso_token'); _cookieRemove('sso_user'); _cookieRemove('sso_refresh_token');
['sso_token','sso_user','sso_refresh_token','token','user','access_token','currentUser','current_user','userInfo','userPageAccess'].forEach(k => localStorage.removeItem(k));
location.href = getLoginUrl() + '&logout=1';
}
/* ===== Page Access ===== */
const _PA_CACHE_KEY = 'userPageAccess';
const _PA_CACHE_DURATION = 5 * 60 * 1000; // 5분
let _paPromise = null;
async function _fetchPageAccess(userId) {
const cached = localStorage.getItem(_PA_CACHE_KEY);
if (cached) {
try {
const c = JSON.parse(cached);
if (Date.now() - c.timestamp < _PA_CACHE_DURATION) return c.keys;
} catch { localStorage.removeItem(_PA_CACHE_KEY); }
}
if (_paPromise) return _paPromise;
_paPromise = (async () => {
try {
const token = getToken();
const res = await fetch(`${API_BASE}/users/${userId}/page-access`, {
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }
});
if (!res.ok) return [];
const data = await res.json();
const pages = data.data?.pageAccess || [];
const keys = pages.filter(p => p.can_access == 1).map(p => p.page_key);
localStorage.setItem(_PA_CACHE_KEY, JSON.stringify({ keys, timestamp: Date.now() }));
return keys;
} catch (e) {
console.error('페이지 권한 조회 오류:', e);
return [];
} finally { _paPromise = null; }
})();
return _paPromise;
}
/* ===== Navbar ===== */
const NAV_MENU = [
{ cat: null, href: '/pages/dashboard-new.html', icon: 'fa-home', label: '대시보드', key: 'dashboard' },
{ cat: '작업 관리', items: [
{ href: '/pages/work/tbm-mobile.html', icon: 'fa-clipboard-list', label: 'TBM 관리', key: 'work.tbm', restricted: true },
{ href: '/pages/work/report-create-mobile.html', icon: 'fa-file-alt', label: '작업보고서 작성', key: 'work.report_create' },
{ href: '/pages/work/analysis.html', icon: 'fa-chart-bar', label: '작업 분석', key: 'work.analysis', admin: true },
{ href: `${_tkqcBase}/`, icon: 'fa-exclamation-triangle', label: '부적합 현황', key: 'work.nonconformity', external: true },
{ href: '/pages/work/schedule.html', icon: 'fa-calendar-alt', label: '공정표', key: 'work.schedule' },
{ href: '/pages/work/meetings.html', icon: 'fa-users', label: '생산회의록', key: 'work.meetings' },
{ href: '/pages/work/daily-status.html', icon: 'fa-chart-bar', label: '입력 현황', key: 'work.daily_status' },
{ href: '/pages/work/proxy-input.html', icon: 'fa-user-edit', label: '대리입력', key: 'work.proxy_input' },
]},
{ cat: '공장 관리', items: [
{ href: '/pages/admin/repair-management.html', icon: 'fa-tools', label: '시설설비 관리', key: 'factory.repair_management' },
{ href: '/pages/inspection/daily-patrol.html', icon: 'fa-route', label: '일일순회점검', key: 'inspection.daily_patrol' },
{ href: '/pages/attendance/checkin.html', icon: 'fa-user-check', label: '출근 체크', key: 'inspection.checkin' },
{ href: '/pages/attendance/work-status.html', icon: 'fa-briefcase', label: '근무 현황', key: 'inspection.work_status' },
]},
{ cat: '소모품 관리', items: [
{ href: '/pages/purchase/request-mobile.html', icon: 'fa-shopping-cart', label: '소모품 신청', key: 'purchase.request_mobile' },
{ href: '/pages/admin/purchase-analysis.html', icon: 'fa-chart-line', label: '소모품 분석', key: 'purchase.analysis', admin: true },
]},
{ cat: '근태 관리', items: [
{ href: '/pages/attendance/my-vacation-info.html', icon: 'fa-info-circle', label: '내 연차 정보', key: 'attendance.my_vacation_info' },
{ href: '/pages/attendance/monthly.html', icon: 'fa-calendar', label: '월간 근태', key: 'attendance.monthly' },
{ href: `${_tksupportBase}/`, icon: 'fa-paper-plane', label: '휴가 신청', key: 'attendance.vacation_request', external: true },
{ href: '/pages/attendance/vacation-management.html', icon: 'fa-cog', label: '휴가 관리', key: 'attendance.vacation_management', admin: true },
{ href: '/pages/attendance/vacation-allocation.html', icon: 'fa-plus-circle', label: '휴가 발생 입력', key: 'attendance.vacation_allocation', admin: true },
{ href: '/pages/attendance/annual-overview.html', icon: 'fa-chart-pie', label: '연간 휴가 현황', key: 'attendance.annual_overview', admin: true },
{ href: '/pages/attendance/monthly-comparison.html', icon: 'fa-scale-balanced', label: '월간 비교·확인', key: 'attendance.monthly_comparison' },
]},
{ cat: '시스템 관리', admin: true, items: [
{ href: `${_tkuserBase}/?tab=users`, icon: 'fa-users-cog', label: '사용자 관리', key: 'admin.user_management', external: true },
{ href: `${_tkuserBase}/?tab=projects`, icon: 'fa-project-diagram', label: '프로젝트 관리', key: 'admin.projects', external: true },
{ href: `${_tkuserBase}/?tab=tasks`, icon: 'fa-tasks', label: '작업 관리', key: 'admin.tasks', external: true },
{ href: `${_tkuserBase}/?tab=workplaces`, icon: 'fa-building', label: '작업장 관리', key: 'admin.workplaces', external: true },
{ href: `${_tkuserBase}/?tab=equipments`, icon: 'fa-cogs', label: '설비 관리', key: 'admin.equipments', external: true },
{ href: `${_tkuserBase}/?tab=departments`, icon: 'fa-sitemap', label: '부서 관리', key: 'admin.departments', external: true },
{ href: `${_tkuserBase}/?tab=notificationRecipients`, icon: 'fa-bell', label: '알림 관리', key: 'admin.notifications', external: true },
{ href: '/pages/admin/attendance-report.html', icon: 'fa-clipboard-check', label: '출퇴근-보고서 대조', key: 'admin.attendance_report' },
]},
];
// 하위 페이지 → 부모 페이지 키 매핑
const PAGE_KEY_ALIASES = {
'dashboard_new': 'dashboard',
'work.tbm_mobile': 'work.tbm',
'work.tbm_create': 'work.tbm',
'work.report_create_mobile': 'work.report_create',
'admin.equipment_detail': 'admin.equipments',
'admin.repair_management': 'factory.repair_management',
'attendance.checkin': 'inspection.checkin',
'attendance.work_status': 'inspection.work_status',
'work.meeting_detail': 'work.meetings',
'work.proxy_input': 'work.daily_status',
};
function _getCurrentPageKey() {
const path = location.pathname;
if (!path.startsWith('/pages/')) return 'dashboard';
const raw = path.substring(7).replace('.html', '').replace(/\//g, '.').replace(/-/g, '_');
return PAGE_KEY_ALIASES[raw] || raw;
}
function renderNavbar(accessibleKeys) {
const nav = document.getElementById('sideNav');
if (!nav) return;
const currentKey = _getCurrentPageKey();
const isAdmin = currentUser && ['admin', 'system', 'system admin'].includes(currentUser.role);
let html = '';
for (const entry of NAV_MENU) {
if (!entry.cat) {
// Top-level link (dashboard)
const active = currentKey === entry.key;
html += `<a href="${entry.href}" class="nav-link flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm transition-colors ${active ? 'active' : 'text-gray-600 hover:bg-gray-100'}">
<i class="fas ${entry.icon} w-5 text-center"></i><span>${entry.label}</span></a>`;
continue;
}
// Category
if (entry.admin && !isAdmin) continue;
const visibleItems = entry.items.filter(item => {
if (item.admin && !isAdmin) return false;
if (isAdmin) return true;
if (item.external) return true;
return accessibleKeys.includes(item.key);
});
if (visibleItems.length === 0) continue;
const hasActive = visibleItems.some(item => currentKey === item.key);
html += `<div class="nav-category${hasActive ? ' expanded' : ''}">
<button class="nav-category-header" onclick="this.parentElement.classList.toggle('expanded')">
<span>${entry.cat}</span><span class="nav-arrow">&#9662;</span>
</button>
<div class="nav-category-items">`;
for (const item of visibleItems) {
const active = currentKey === item.key;
const target = item.external ? ' target="_blank"' : '';
const arrow = item.external ? ' &#8599;' : '';
html += `<a href="${item.href}"${target} class="nav-link flex items-center gap-3 px-4 py-2 rounded-lg text-sm transition-colors ${active ? 'active' : 'text-gray-600 hover:bg-gray-100'}" data-page-key="${item.key}">
<i class="fas ${item.icon} w-5 text-center text-xs"></i><span>${item.label}${arrow}</span></a>`;
}
html += `</div></div>`;
}
nav.innerHTML = html;
}
/* ===== Mobile Menu ===== */
function toggleMobileMenu() {
const nav = document.getElementById('sideNav');
const overlay = document.getElementById('mobileOverlay');
if (!nav) return;
const isOpen = nav.classList.contains('mobile-open');
nav.classList.toggle('mobile-open');
if (overlay) overlay.classList.toggle('hidden', isOpen);
document.body.style.overflow = isOpen ? '' : 'hidden';
}
/* ===== State ===== */
let currentUser = null;
function getCurrentUser() { return currentUser; }
/* ===== Init ===== */
async function initAuth() {
// 쿠키 우선 검증
const cookieToken = _cookieGet('sso_token');
const localToken = localStorage.getItem('sso_token');
if (!cookieToken && localToken) {
['sso_token','sso_user','sso_refresh_token','token','user','access_token',
'currentUser','current_user','userInfo','userPageAccess'].forEach(k => localStorage.removeItem(k));
_safeRedirect();
return false;
}
const token = getToken();
if (!token) { _safeRedirect(); return false; }
const decoded = decodeToken(token);
if (!decoded) { _safeRedirect(); return false; }
sessionStorage.removeItem(_REDIRECT_KEY);
if (!localStorage.getItem('sso_token')) localStorage.setItem('sso_token', token);
currentUser = {
id: decoded.user_id || decoded.id,
username: decoded.username || decoded.sub,
name: decoded.name || decoded.full_name,
role: (decoded.role || decoded.access_level || '').toLowerCase()
};
const dn = currentUser.name || currentUser.username;
const nameEl = document.getElementById('headerUserName');
const avatarEl = document.getElementById('headerUserAvatar');
if (nameEl) nameEl.textContent = dn;
if (avatarEl) avatarEl.textContent = dn.charAt(0).toUpperCase();
// Page access 기반 네비게이션
const isAdmin = ['admin', 'system', 'system admin'].includes(currentUser.role);
let accessibleKeys = [];
if (!isAdmin) {
accessibleKeys = await _fetchPageAccess(currentUser.id);
if (accessibleKeys.length === 0) {
console.warn('[PageAccess] 접근 가능 페이지가 없거나 권한 조회 실패');
}
// 현재 페이지 접근 권한 확인 (dashboard, profile은 전체 공개)
const pageKey = _getCurrentPageKey();
if (pageKey && pageKey !== 'dashboard' && !pageKey.startsWith('profile.')) {
if (!accessibleKeys.includes(pageKey)) {
alert('이 페이지에 접근할 권한이 없습니다.');
location.href = '/pages/dashboard-new.html';
return false;
}
}
}
renderNavbar(accessibleKeys);
// Mobile menu overlay
const mobileBtn = document.getElementById('mobileMenuBtn');
if (mobileBtn) mobileBtn.addEventListener('click', toggleMobileMenu);
const overlay = document.getElementById('mobileOverlay');
if (overlay) overlay.addEventListener('click', toggleMobileMenu);
// 알림 벨 로드
_loadNotificationBell();
setTimeout(() => document.querySelectorAll('.fade-in').forEach(el => el.classList.add('visible')), 50);
return true;
}
/* ===== 알림 벨 ===== */
function _loadNotificationBell() {
const s = document.createElement('script');
s.src = (location.hostname.includes('technicalkorea.net') ? 'https://tkfb.technicalkorea.net' : location.protocol + '//' + location.hostname + ':30000') + '/shared/notification-bell.js?v=4';
document.head.appendChild(s);
}
/* ===== Modal ESC 닫기 ===== */
document.addEventListener('keydown', e => {
if (e.key === 'Escape') {
document.querySelectorAll('.modal-overlay:not(.hidden)')
.forEach(m => m.classList.add('hidden'));
}
});

View File

@@ -0,0 +1,117 @@
/* ===== Dashboard (대시보드) ===== */
const today = new Date().toISOString().substring(0, 10);
function updateDateTime() {
const now = new Date();
const days = ['일', '월', '화', '수', '목', '금', '토'];
const h = String(now.getHours()).padStart(2, '0');
const m = String(now.getMinutes()).padStart(2, '0');
const el = document.getElementById('dateTimeDisplay');
if (el) el.textContent = `${now.getFullYear()}${now.getMonth()+1}${now.getDate()}일 (${days[now.getDay()]}) ${h}:${m}`;
}
async function loadDashboard() {
updateDateTime();
const results = await Promise.allSettled([
api('/tbm/sessions/date/' + today).catch(() => ({ data: [] })),
api('/equipments/repair-requests?status=pending').catch(() => ({ data: [] })),
api('/attendance/daily-status?date=' + today).catch(() => ({ data: [] })),
]);
const tbmData = results[0].status === 'fulfilled' ? results[0].value : { data: [] };
const repairData = results[1].status === 'fulfilled' ? results[1].value : { data: [] };
const attendData = results[2].status === 'fulfilled' ? results[2].value : { data: [] };
const tbmSessions = tbmData.data || [];
const repairs = repairData.data || [];
const attendList = Array.isArray(attendData.data) ? attendData.data : [];
const checkedInCount = attendList.filter(d => d.status !== 'incomplete').length;
// Stats
document.getElementById('statTbm').textContent = tbmSessions.length;
document.getElementById('statWorkers').textContent = checkedInCount;
document.getElementById('statRepairs').textContent = repairs.length;
document.getElementById('statNotifications').textContent = '-';
// TBM list
renderTbmList(tbmSessions);
renderNotificationPanel();
renderRepairList(repairs);
}
function renderTbmList(sessions) {
const el = document.getElementById('tbmList');
if (!sessions.length) {
el.innerHTML = '<p class="text-gray-400 text-sm text-center py-4">금일 TBM이 없습니다</p>';
return;
}
el.innerHTML = sessions.slice(0, 5).map(s => {
const workers = s.team_member_count || 0;
return `<div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
<div>
<div class="text-sm font-medium text-gray-800">${escapeHtml(s.workplace_name || s.session_title || 'TBM')}</div>
<div class="text-xs text-gray-500">${escapeHtml(s.leader_name || '-')} · ${workers}명</div>
</div>
<span class="badge ${s.status === 'completed' ? 'badge-green' : 'badge-amber'}">${s.status === 'completed' ? '완료' : '진행중'}</span>
</div>`;
}).join('');
if (sessions.length > 5) {
el.innerHTML += `<a href="/pages/work/tbm.html" class="block text-center text-xs text-orange-600 hover:text-orange-700 mt-2">전체 보기 (${sessions.length}건)</a>`;
}
}
function renderNotificationPanel() {
const el = document.getElementById('notificationList');
el.innerHTML = `<div class="flex flex-col items-center gap-3 py-6">
<i class="fas fa-bell text-gray-300 text-3xl"></i>
<p class="text-gray-400 text-sm">알림은 사용자관리에서 확인하세요</p>
<a href="${_tkuserBase}/?tab=notificationRecipients" class="text-sm text-orange-600 hover:text-orange-700 font-medium">
<i class="fas fa-external-link-alt mr-1"></i>알림 관리 바로가기
</a>
</div>`;
}
function renderRepairList(repairs) {
const el = document.getElementById('repairList');
if (!repairs.length) {
el.innerHTML = '<p class="text-gray-400 text-sm text-center py-4">대기 중인 수리 요청이 없습니다</p>';
return;
}
el.innerHTML = repairs.slice(0, 5).map(r => {
return `<div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
<div>
<div class="text-sm font-medium text-gray-800">${escapeHtml(r.equipment_name || r.title || '수리 요청')}</div>
<div class="text-xs text-gray-500">${formatDate(r.created_at)}</div>
</div>
<span class="badge badge-red">대기</span>
</div>`;
}).join('');
if (repairs.length > 5) {
el.innerHTML += `<a href="/pages/admin/repair-management.html" class="block text-center text-xs text-orange-600 hover:text-orange-700 mt-2">전체 보기 (${repairs.length}건)</a>`;
}
}
function formatTimeAgo(dateStr) {
if (!dateStr) return '';
const d = new Date(dateStr);
const now = new Date();
const diff = now - d;
const mins = Math.floor(diff / 60000);
const hours = Math.floor(diff / 3600000);
const days = Math.floor(diff / 86400000);
if (mins < 1) return '방금 전';
if (mins < 60) return `${mins}분 전`;
if (hours < 24) return `${hours}시간 전`;
if (days < 7) return `${days}일 전`;
return formatDate(dateStr);
}
/* ===== Init ===== */
(async function() {
if (!await initAuth()) return;
updateDateTime();
setInterval(updateDateTime, 60000);
loadDashboard();
})();