Files
tk-factory-services/user-management/web/static/js/tkuser-workplaces.js
Hyungi Ahn bf4000c4ae refactor: 코드 분리 + 성능 최적화 + 모바일 개선
tkqc 5개 페이지 인라인 JS/CSS를 외부 파일로 추출 (HTML 82% 감소)
tkuser index.html을 CSS 1개 + JS 10개 모듈로 분리 (3283→1155줄)

- 공통 유틸 추출: issue-helpers, photo-modal, toast
- 공통 CSS 확장: tkqc-common.css (모바일 반응형 포함)
- 모바일 하단 네비게이션 추가 (mobile-bottom-nav.js)
- nginx: JS/CSS 1시간 캐싱 + gzip 압축 활성화
- Tailwind CDN preload, 캐시버스터 통일 (?v=20260213)
- 카메라 capture="environment" 추가
- tkuser Dockerfile에 static/ 디렉토리 복사 추가

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 12:11:51 +09:00

515 lines
30 KiB
JavaScript

/* ===== Workplaces CRUD ===== */
let workplaces = [], workplacesLoaded = false, workplaceCategories = [];
let selectedWorkplaceId = null, selectedWorkplaceName = '';
let equipments = [], equipmentTypes = [];
let wpNavLevel = 'categories'; // 'categories' | 'workplaces'
let wpNavCategoryId = null;
let wpNavCategoryName = '';
let previewMapRegions = [];
function purposeBadge(p) {
const colors = { '작업구역': 'bg-blue-50 text-blue-600', '창고': 'bg-amber-50 text-amber-600', '설비': 'bg-purple-50 text-purple-600', '휴게시설': 'bg-green-50 text-green-600' };
return p ? `<span class="px-1.5 py-0.5 rounded text-xs ${colors[p] || 'bg-gray-50 text-gray-500'}">${p}</span>` : '';
}
async function loadWorkplaceCategories() {
try {
const r = await api('/workplaces/categories'); workplaceCategories = r.data || r;
populateCategorySelects();
renderSidebar();
} catch(e) { console.warn('카테고리 로드 실패:', e); }
}
function populateCategorySelects() {
['newWorkplaceCategory','editWorkplaceCategory'].forEach(id => {
const sel = document.getElementById(id); if (!sel) return;
const val = sel.value;
sel.innerHTML = '<option value="">선택</option>';
workplaceCategories.forEach(c => { const o = document.createElement('option'); o.value = c.category_id; o.textContent = c.category_name; sel.appendChild(o); });
sel.value = val;
});
}
async function loadWorkplaces() {
await loadWorkplaceCategories();
try {
const r = await api('/workplaces'); workplaces = r.data || r;
workplacesLoaded = true;
renderSidebar();
} catch (err) {
document.getElementById('wpSidebarContent').innerHTML = `<div class="text-red-500 text-center py-6"><i class="fas fa-exclamation-triangle text-xl"></i><p class="text-sm mt-2">${err.message}</p></div>`;
}
}
function renderSidebar() {
const c = document.getElementById('wpSidebarContent');
if (!c) return;
let html = '';
if (wpNavLevel === 'categories') {
// 공장 목록 레벨
html += '<div class="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-2">공장 선택</div>';
html += `<button onclick="openAddWorkplaceModal()" class="w-full px-3 py-2 mb-3 bg-slate-700 text-white rounded-lg hover:bg-slate-800 text-sm font-medium flex items-center justify-center gap-1.5"><i class="fas fa-plus text-xs"></i>작업장 추가</button>`;
if (!workplaceCategories.length) {
html += '<p class="text-gray-400 text-center py-4 text-sm">등록된 공장이 없습니다.</p>';
} else {
html += '<div class="space-y-1.5 flex-1 overflow-y-auto">';
workplaceCategories.forEach(cat => {
const count = workplaces.filter(w => w.category_id == cat.category_id).length;
html += `<div onclick="drillIntoCategory(${cat.category_id},'${(cat.category_name||'').replace(/'/g,"\\'")}')" class="flex items-center justify-between p-2.5 rounded-lg hover:bg-blue-50 transition-colors cursor-pointer bg-gray-50">
<div class="flex items-center gap-2 min-w-0">
<i class="fas fa-industry text-gray-400 text-sm"></i>
<span class="text-sm font-medium text-gray-800 truncate">${cat.category_name}</span>
</div>
<div class="flex items-center gap-1.5 flex-shrink-0">
<span class="text-xs text-gray-400">${count}</span>
<i class="fas fa-chevron-right text-gray-300 text-xs"></i>
</div>
</div>`;
});
// 미분류 작업장
const uncategorized = workplaces.filter(w => !w.category_id);
if (uncategorized.length) {
html += `<div onclick="drillIntoCategory(0,'미분류')" class="flex items-center justify-between p-2.5 rounded-lg hover:bg-blue-50 transition-colors cursor-pointer bg-gray-50">
<div class="flex items-center gap-2 min-w-0">
<i class="fas fa-folder-open text-gray-300 text-sm"></i>
<span class="text-sm font-medium text-gray-500 truncate">미분류</span>
</div>
<div class="flex items-center gap-1.5 flex-shrink-0">
<span class="text-xs text-gray-400">${uncategorized.length}</span>
<i class="fas fa-chevron-right text-gray-300 text-xs"></i>
</div>
</div>`;
}
html += '</div>';
}
} else {
// 작업장 목록 레벨 (특정 공장 내)
html += `<button onclick="backToCategories()" class="flex items-center gap-1.5 text-sm text-slate-600 hover:text-slate-800 mb-2 px-1 py-1 rounded hover:bg-gray-100 transition-colors"><i class="fas fa-arrow-left text-xs"></i>전체 공장</button>`;
html += `<div class="text-sm font-semibold text-gray-800 mb-2 px-1"><i class="fas fa-industry text-gray-400 mr-1.5"></i>${wpNavCategoryName}</div>`;
html += `<button onclick="openAddWorkplaceModal()" class="w-full px-3 py-2 mb-3 bg-slate-700 text-white rounded-lg hover:bg-slate-800 text-sm font-medium flex items-center justify-center gap-1.5"><i class="fas fa-plus text-xs"></i>작업장 추가</button>`;
const filtered = wpNavCategoryId === 0
? workplaces.filter(w => !w.category_id)
: workplaces.filter(w => w.category_id == wpNavCategoryId);
if (!filtered.length) {
html += '<p class="text-gray-400 text-center py-4 text-sm">등록된 작업장이 없습니다.</p>';
} else {
html += '<div class="space-y-1.5 flex-1 overflow-y-auto">';
filtered.forEach(w => {
html += `<div class="flex items-center justify-between p-2.5 rounded-lg hover:bg-blue-50 transition-colors cursor-pointer ${selectedWorkplaceId === w.workplace_id ? 'bg-blue-50 ring-1 ring-blue-200' : 'bg-gray-50'}" onclick="selectWorkplaceForEquipments(${w.workplace_id},'${(w.workplace_name||'').replace(/'/g,"\\'")}')">
<div class="flex-1 min-w-0">
<div class="text-sm font-medium text-gray-800 truncate"><i class="fas fa-building mr-1.5 text-gray-400 text-xs"></i>${w.workplace_name}</div>
<div class="text-xs text-gray-500 flex items-center gap-1.5 mt-0.5 flex-wrap">
${purposeBadge(w.workplace_purpose)}
${w.is_active === 0 || w.is_active === false ? '<span class="px-1.5 py-0.5 rounded bg-gray-100 text-gray-400">비활성</span>' : ''}
</div>
</div>
<div class="flex gap-1 ml-2 flex-shrink-0">
<button onclick="event.stopPropagation(); editWorkplace(${w.workplace_id})" class="p-1.5 text-slate-500 hover:text-slate-700 hover:bg-slate-200 rounded" title="편집"><i class="fas fa-pen-to-square text-xs"></i></button>
${w.is_active !== 0 && w.is_active !== false ? `<button onclick="event.stopPropagation(); deactivateWorkplace(${w.workplace_id},'${(w.workplace_name||'').replace(/'/g,"\\'")}')" class="p-1.5 text-red-400 hover:text-red-600 hover:bg-red-100 rounded" title="비활성화"><i class="fas fa-ban text-xs"></i></button>` : ''}
</div>
</div>`;
});
html += '</div>';
}
}
c.innerHTML = html;
}
function drillIntoCategory(categoryId, categoryName) {
wpNavLevel = 'workplaces';
wpNavCategoryId = categoryId;
wpNavCategoryName = categoryName;
selectedWorkplaceId = null;
renderSidebar();
showZoneMapForCategory(categoryId);
}
function backToCategories() {
wpNavLevel = 'categories';
wpNavCategoryId = null;
wpNavCategoryName = '';
selectedWorkplaceId = null;
renderSidebar();
showEmptyState();
}
function showEmptyState() {
document.getElementById('workplaceEmptyState')?.classList.remove('hidden');
document.getElementById('equipmentSection')?.classList.add('hidden');
document.getElementById('zoneMapSection')?.classList.add('hidden');
}
function showZoneMapForCategory(categoryId) {
document.getElementById('workplaceEmptyState')?.classList.add('hidden');
document.getElementById('equipmentSection')?.classList.add('hidden');
document.getElementById('zoneMapSection')?.classList.remove('hidden');
const catName = categoryId === 0 ? '미분류' : (workplaceCategories.find(c => c.category_id == categoryId)?.category_name || '');
document.getElementById('zoneMapTitle').innerHTML = `<i class="fas fa-map text-slate-400 mr-2"></i>${catName} - 구역지도`;
selectedMapCategoryId = categoryId;
if (categoryId === 0) {
document.getElementById('layoutPreviewArea').classList.remove('hidden');
document.getElementById('layoutPreviewCanvas').classList.add('hidden');
document.getElementById('layoutPreviewArea').innerHTML = '<i class="fas fa-info-circle text-2xl mb-2"></i><p>미분류 작업장에는 구역지도가 없습니다.</p>';
return;
}
loadLayoutPreview(categoryId);
}
function backToCategory() {
if (!wpNavCategoryId && wpNavCategoryId !== 0) { backToCategories(); return; }
selectedWorkplaceId = null;
renderSidebar();
showZoneMapForCategory(wpNavCategoryId);
}
function openAddWorkplaceModal() {
populateCategorySelects();
document.getElementById('addWorkplaceForm').reset();
// 공장 드릴다운 상태이면 카테고리 자동 선택
if (wpNavLevel === 'workplaces' && wpNavCategoryId && wpNavCategoryId !== 0) {
document.getElementById('newWorkplaceCategory').value = wpNavCategoryId;
}
document.getElementById('addWorkplaceModal').classList.remove('hidden');
}
function closeAddWorkplaceModal() { document.getElementById('addWorkplaceModal').classList.add('hidden'); }
document.getElementById('addWorkplaceForm').addEventListener('submit', async e => {
e.preventDefault();
try {
await api('/workplaces', { method: 'POST', body: JSON.stringify({
workplace_name: document.getElementById('newWorkplaceName').value.trim(),
category_id: document.getElementById('newWorkplaceCategory').value ? parseInt(document.getElementById('newWorkplaceCategory').value) : null,
workplace_purpose: document.getElementById('newWorkplacePurpose').value || null,
description: document.getElementById('newWorkplaceDesc').value.trim() || null,
display_priority: parseInt(document.getElementById('newWorkplacePriority').value) || 0
})});
showToast('작업장이 추가되었습니다.'); document.getElementById('addWorkplaceForm').reset(); closeAddWorkplaceModal(); await loadWorkplaces();
} catch(e) { showToast(e.message, 'error'); }
});
function editWorkplace(id) {
const w = workplaces.find(x => x.workplace_id === id); if (!w) return;
document.getElementById('editWorkplaceId').value = w.workplace_id;
document.getElementById('editWorkplaceName').value = w.workplace_name;
document.getElementById('editWorkplaceDesc').value = w.description || '';
document.getElementById('editWorkplacePriority').value = w.display_priority || 0;
document.getElementById('editWorkplaceActive').value = (w.is_active === 0 || w.is_active === false) ? '0' : '1';
document.getElementById('editWorkplacePurpose').value = w.workplace_purpose || '';
populateCategorySelects();
document.getElementById('editWorkplaceCategory').value = w.category_id || '';
document.getElementById('editWorkplaceModal').classList.remove('hidden');
}
function closeWorkplaceModal() { document.getElementById('editWorkplaceModal').classList.add('hidden'); }
document.getElementById('editWorkplaceForm').addEventListener('submit', async e => {
e.preventDefault();
try {
await api(`/workplaces/${document.getElementById('editWorkplaceId').value}`, { method: 'PUT', body: JSON.stringify({
workplace_name: document.getElementById('editWorkplaceName').value.trim(),
category_id: document.getElementById('editWorkplaceCategory').value ? parseInt(document.getElementById('editWorkplaceCategory').value) : null,
workplace_purpose: document.getElementById('editWorkplacePurpose').value || null,
description: document.getElementById('editWorkplaceDesc').value.trim() || null,
display_priority: parseInt(document.getElementById('editWorkplacePriority').value) || 0,
is_active: document.getElementById('editWorkplaceActive').value === '1'
})});
showToast('수정되었습니다.'); closeWorkplaceModal(); await loadWorkplaces();
} catch(e) { showToast(e.message, 'error'); }
});
async function deactivateWorkplace(id, name) {
if (!confirm(`"${name}" 작업장을 비활성화?`)) return;
try { await api(`/workplaces/${id}`, { method: 'DELETE' }); showToast('작업장 비활성화 완료'); await loadWorkplaces(); } catch(e) { showToast(e.message, 'error'); }
}
/* ===== Equipment CRUD ===== */
let eqMapImg = null, eqMapCanvas = null, eqMapCtx = null, eqDetailEqId = null;
function eqStatusBadge(status) {
const map = { active:'bg-emerald-50 text-emerald-600', maintenance:'bg-amber-50 text-amber-600', inactive:'bg-gray-100 text-gray-500', external:'bg-blue-50 text-blue-600', repair_external:'bg-blue-50 text-blue-600', repair_needed:'bg-red-50 text-red-600' };
const labels = { active:'가동중', maintenance:'점검중', inactive:'비활성', external:'외부반출', repair_external:'수리외주', repair_needed:'수리필요' };
return `<span class="px-1.5 py-0.5 rounded text-xs ${map[status] || 'bg-gray-100 text-gray-500'}">${labels[status] || status || ''}</span>`;
}
function selectWorkplaceForEquipments(id, name) {
selectedWorkplaceId = id;
selectedWorkplaceName = name;
// 카테고리 레벨에서 직접 호출된 경우, 해당 카테고리로 드릴인
if (wpNavLevel === 'categories') {
const wp = workplaces.find(w => w.workplace_id === id);
if (wp && wp.category_id) {
wpNavLevel = 'workplaces';
wpNavCategoryId = wp.category_id;
wpNavCategoryName = wp.category_name || '';
}
}
renderSidebar();
document.getElementById('workplaceEmptyState')?.classList.add('hidden');
document.getElementById('zoneMapSection')?.classList.add('hidden');
document.getElementById('equipmentSection').classList.remove('hidden');
document.getElementById('eqWorkplaceName').textContent = name;
// 뒤로가기 버튼 표시 (공장 구역지도로 돌아가기)
const backBtn = document.getElementById('eqBackToCategory');
if (backBtn && wpNavCategoryId !== null) {
document.getElementById('eqBackLabel').textContent = `${wpNavCategoryName} 구역지도`;
backBtn.classList.remove('hidden');
} else if (backBtn) {
backBtn.classList.add('hidden');
}
loadEquipments();
loadEquipmentTypes();
loadEqMap();
}
async function loadEquipments() {
try {
const r = await api(`/equipments/workplace/${selectedWorkplaceId}`);
equipments = r.data || [];
displayEquipments();
drawEqMapEquipments();
} catch(e) {
document.getElementById('equipmentList').innerHTML = `<div class="text-red-500 text-center py-4"><p class="text-sm">${e.message}</p></div>`;
}
}
function displayEquipments() {
const statusFilter = document.getElementById('eqStatusFilter').value;
const typeFilter = document.getElementById('eqTypeFilter').value;
let filtered = equipments;
if (statusFilter) filtered = filtered.filter(e => e.status === statusFilter);
if (typeFilter) filtered = filtered.filter(e => e.equipment_type === typeFilter);
const c = document.getElementById('equipmentList');
if (!filtered.length) { c.innerHTML = '<p class="text-gray-400 text-center py-4 text-sm">설비가 없습니다.</p>'; return; }
c.innerHTML = filtered.map(e => `
<div class="flex items-center justify-between p-2.5 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors cursor-pointer" onclick="openEqDetailModal(${e.equipment_id})">
<div class="flex-1 min-w-0">
<div class="text-sm font-medium text-gray-800 truncate">
<span class="text-xs text-gray-400 font-mono mr-1.5">${e.equipment_code || ''}</span>${e.equipment_name}
${e.is_temporarily_moved ? '<i class="fas fa-arrows-alt text-blue-400 ml-1" title="임시이동중"></i>' : ''}
</div>
<div class="text-xs text-gray-500 flex items-center gap-1.5 mt-0.5 flex-wrap">
${e.equipment_type ? `<span class="px-1.5 py-0.5 rounded bg-slate-50 text-slate-600">${e.equipment_type}</span>` : ''}
${e.manufacturer ? `<span class="text-gray-400">${e.manufacturer}</span>` : ''}
${eqStatusBadge(e.status)}
</div>
</div>
<div class="flex gap-1 ml-2 flex-shrink-0">
<button onclick="event.stopPropagation(); editEquipment(${e.equipment_id})" class="p-1.5 text-slate-500 hover:text-slate-700 hover:bg-slate-200 rounded" title="편집"><i class="fas fa-pen-to-square text-xs"></i></button>
<button onclick="event.stopPropagation(); deleteEquipment(${e.equipment_id},'${(e.equipment_name||'').replace(/'/g,"\\'")}')" class="p-1.5 text-red-400 hover:text-red-600 hover:bg-red-100 rounded" title="삭제"><i class="fas fa-trash-alt text-xs"></i></button>
</div>
</div>`).join('');
}
function filterEquipments() { displayEquipments(); }
async function loadEquipmentTypes() {
try {
const r = await api('/equipments/types'); equipmentTypes = r.data || [];
const sel = document.getElementById('eqTypeFilter'); const val = sel.value;
sel.innerHTML = '<option value="">전체 유형</option>';
equipmentTypes.forEach(t => { const o = document.createElement('option'); o.value = t; o.textContent = t; sel.appendChild(o); });
sel.value = val;
const dl = document.getElementById('eqTypeDatalist');
if (dl) { dl.innerHTML = ''; equipmentTypes.forEach(t => { const o = document.createElement('option'); o.value = t; dl.appendChild(o); }); }
} catch(e) { console.warn('설비 유형 로드 실패:', e); }
}
async function openEquipmentModal(editId) {
document.getElementById('eqEditId').value = '';
document.getElementById('equipmentForm').reset();
if (editId) {
document.getElementById('eqModalTitle').textContent = '설비 수정';
const eq = equipments.find(e => e.equipment_id === editId);
if (!eq) return;
document.getElementById('eqEditId').value = eq.equipment_id;
document.getElementById('eqCode').value = eq.equipment_code || '';
document.getElementById('eqName').value = eq.equipment_name || '';
document.getElementById('eqType').value = eq.equipment_type || '';
document.getElementById('eqStatus').value = eq.status || 'active';
document.getElementById('eqManufacturer').value = eq.manufacturer || '';
document.getElementById('eqModel').value = eq.model_name || '';
document.getElementById('eqSupplier').value = eq.supplier || '';
document.getElementById('eqPrice').value = eq.purchase_price || '';
document.getElementById('eqInstallDate').value = eq.installation_date ? eq.installation_date.substring(0, 10) : '';
document.getElementById('eqSerial').value = eq.serial_number || '';
document.getElementById('eqSpecs').value = eq.specifications || '';
document.getElementById('eqNotes').value = eq.notes || '';
} else {
document.getElementById('eqModalTitle').textContent = '설비 추가';
generateEquipmentCode();
}
document.getElementById('equipmentModal').classList.remove('hidden');
}
function closeEquipmentModal() { document.getElementById('equipmentModal').classList.add('hidden'); }
async function generateEquipmentCode() { try { const r = await api('/equipments/next-code?prefix=TKP'); document.getElementById('eqCode').value = r.data || ''; } catch(e) {} }
function editEquipment(id) { openEquipmentModal(id); }
async function deleteEquipment(id, name) {
if (!confirm(`"${name}" 설비를 삭제하시겠습니까?`)) return;
try { await api(`/equipments/${id}`, { method: 'DELETE' }); showToast('설비가 삭제되었습니다.'); await loadEquipments(); } catch(e) { showToast(e.message, 'error'); }
}
document.getElementById('equipmentForm').addEventListener('submit', async e => {
e.preventDefault();
const editId = document.getElementById('eqEditId').value;
const body = {
equipment_code: document.getElementById('eqCode').value.trim(),
equipment_name: document.getElementById('eqName').value.trim(),
equipment_type: document.getElementById('eqType').value.trim() || null,
status: document.getElementById('eqStatus').value,
manufacturer: document.getElementById('eqManufacturer').value.trim() || null,
model_name: document.getElementById('eqModel').value.trim() || null,
supplier: document.getElementById('eqSupplier').value.trim() || null,
purchase_price: document.getElementById('eqPrice').value ? parseFloat(document.getElementById('eqPrice').value) : null,
installation_date: document.getElementById('eqInstallDate').value || null,
serial_number: document.getElementById('eqSerial').value.trim() || null,
specifications: document.getElementById('eqSpecs').value.trim() || null,
notes: document.getElementById('eqNotes').value.trim() || null,
workplace_id: selectedWorkplaceId
};
try {
if (editId) { await api(`/equipments/${editId}`, { method: 'PUT', body: JSON.stringify(body) }); showToast('설비가 수정되었습니다.'); }
else { await api('/equipments', { method: 'POST', body: JSON.stringify(body) }); showToast('설비가 추가되었습니다.'); }
closeEquipmentModal(); await loadEquipments(); loadEquipmentTypes();
} catch(e) { showToast(e.message, 'error'); }
});
/* ===== Equipment Map (설비 배치도) ===== */
function loadEqMap() {
const wp = workplaces.find(w => w.workplace_id === selectedWorkplaceId);
if (!wp || !wp.layout_image) {
document.getElementById('eqMapArea').classList.remove('hidden');
document.getElementById('eqMapCanvasWrap').classList.add('hidden');
return;
}
document.getElementById('eqMapArea').classList.add('hidden');
document.getElementById('eqMapCanvasWrap').classList.remove('hidden');
eqMapCanvas = document.getElementById('eqMapCanvas');
eqMapCtx = eqMapCanvas.getContext('2d');
const imgUrl = wp.layout_image.startsWith('/') ? '/uploads/' + wp.layout_image.replace(/^\/uploads\//, '') : wp.layout_image;
const img = new Image();
img.onload = function() {
const maxW = 780; const scale = img.width > maxW ? maxW / img.width : 1;
eqMapCanvas.width = img.width * scale; eqMapCanvas.height = img.height * scale;
eqMapCtx.drawImage(img, 0, 0, eqMapCanvas.width, eqMapCanvas.height);
eqMapImg = img;
drawEqMapEquipments();
eqMapCanvas.onclick = onEqMapClick;
};
img.src = imgUrl;
}
function drawEqMapEquipments() {
if (!eqMapCanvas || !eqMapCtx || !eqMapImg) return;
eqMapCtx.clearRect(0, 0, eqMapCanvas.width, eqMapCanvas.height);
eqMapCtx.drawImage(eqMapImg, 0, 0, eqMapCanvas.width, eqMapCanvas.height);
equipments.forEach(eq => {
if (eq.map_x_percent == null || eq.map_y_percent == null) return;
const x = (eq.map_x_percent / 100) * eqMapCanvas.width;
const y = (eq.map_y_percent / 100) * eqMapCanvas.height;
const w = ((eq.map_width_percent || 3) / 100) * eqMapCanvas.width;
const h = ((eq.map_height_percent || 3) / 100) * eqMapCanvas.height;
const colors = { active:'#10b981', maintenance:'#f59e0b', inactive:'#94a3b8', external:'#3b82f6', repair_external:'#3b82f6', repair_needed:'#ef4444' };
const color = colors[eq.status] || '#64748b';
eqMapCtx.fillStyle = color + '33'; eqMapCtx.fillRect(x - w/2, y - h/2, w, h);
eqMapCtx.strokeStyle = color; eqMapCtx.lineWidth = 2; eqMapCtx.strokeRect(x - w/2, y - h/2, w, h);
eqMapCtx.fillStyle = color; eqMapCtx.font = 'bold 10px sans-serif'; eqMapCtx.textAlign = 'center';
eqMapCtx.fillText(eq.equipment_code || eq.equipment_name, x, y - h/2 - 3);
eqMapCtx.textAlign = 'start';
});
}
let eqMapPlacingId = null;
function onEqMapClick(e) {
if (!eqMapPlacingId) return;
const r = eqMapCanvas.getBoundingClientRect();
const scaleX = eqMapCanvas.width / r.width; const scaleY = eqMapCanvas.height / r.height;
const px = (e.clientX - r.left) * scaleX; const py = (e.clientY - r.top) * scaleY;
const xPct = (px / eqMapCanvas.width * 100).toFixed(2); const yPct = (py / eqMapCanvas.height * 100).toFixed(2);
saveEqMapPosition(eqMapPlacingId, xPct, yPct);
eqMapPlacingId = null; eqMapCanvas.style.cursor = 'default';
}
async function saveEqMapPosition(eqId, x, y) {
try {
await api(`/equipments/${eqId}/map-position`, { method: 'PATCH', body: JSON.stringify({ map_x_percent: parseFloat(x), map_y_percent: parseFloat(y), map_width_percent: 3, map_height_percent: 3 }) });
showToast('설비 위치가 저장되었습니다.'); await loadEquipments();
} catch(e) { showToast(e.message, 'error'); }
}
function startPlaceEquipment(eqId) {
eqMapPlacingId = eqId; if(eqMapCanvas) eqMapCanvas.style.cursor = 'crosshair';
showToast('배치도에서 위치를 클릭하세요');
}
async function uploadWorkplaceLayoutImage() {
const file = document.getElementById('wpLayoutImageFile').files[0];
if (!file) return;
try {
const fd = new FormData(); fd.append('image', file); const token = getToken();
const res = await fetch(`${API_BASE}/workplaces/${selectedWorkplaceId}/layout-image`, { method: 'POST', headers: { 'Authorization': token ? `Bearer ${token}` : '' }, body: fd });
const result = await res.json(); if (!res.ok) throw new Error(result.error || '업로드 실패');
showToast('배치도 이미지가 업로드되었습니다.');
const wp = workplaces.find(w => w.workplace_id === selectedWorkplaceId);
if (wp) wp.layout_image = result.data.image_path;
loadEqMap();
} catch(e) { showToast(e.message || '업로드 실패', 'error'); }
}
/* ===== Equipment Detail Modal ===== */
async function openEqDetailModal(eqId) {
eqDetailEqId = eqId;
const eq = equipments.find(e => e.equipment_id === eqId);
if (!eq) return;
document.getElementById('eqDetailTitle').textContent = `${eq.equipment_code} - ${eq.equipment_name}`;
document.getElementById('eqReturnBtn').classList.toggle('hidden', !eq.is_temporarily_moved);
const fmt = v => v || '-';
const fmtDate = v => v ? v.substring(0, 10) : '-';
const fmtPrice = v => v ? Number(v).toLocaleString() + '원' : '-';
document.getElementById('eqDetailContent').innerHTML = `
<div class="grid grid-cols-2 gap-x-4 gap-y-2 text-sm">
<div><span class="text-gray-400">유형:</span> ${fmt(eq.equipment_type)}</div>
<div><span class="text-gray-400">상태:</span> ${eqStatusBadge(eq.status)}</div>
<div><span class="text-gray-400">제조사:</span> ${fmt(eq.manufacturer)}</div>
<div><span class="text-gray-400">모델:</span> ${fmt(eq.model_name)}</div>
<div><span class="text-gray-400">공급업체:</span> ${fmt(eq.supplier)}</div>
<div><span class="text-gray-400">구매가격:</span> ${fmtPrice(eq.purchase_price)}</div>
<div><span class="text-gray-400">설치일:</span> ${fmtDate(eq.installation_date)}</div>
<div><span class="text-gray-400">시리얼:</span> ${fmt(eq.serial_number)}</div>
<div class="col-span-2"><span class="text-gray-400">사양:</span> ${fmt(eq.specifications)}</div>
<div class="col-span-2"><span class="text-gray-400">비고:</span> ${fmt(eq.notes)}</div>
</div>
<div class="mt-2"><button onclick="startPlaceEquipment(${eq.equipment_id}); closeEqDetailModal();" class="text-xs text-blue-600 hover:underline"><i class="fas fa-map-pin mr-1"></i>배치도에 위치 지정</button></div>`;
loadEqPhotos(eqId);
document.getElementById('eqDetailModal').classList.remove('hidden');
}
function closeEqDetailModal() { document.getElementById('eqDetailModal').classList.add('hidden'); }
async function loadEqPhotos(eqId) {
const c = document.getElementById('eqPhotoGrid');
try {
const r = await api(`/equipments/${eqId}/photos`); const photos = r.data || [];
if (!photos.length) { c.innerHTML = '<p class="text-gray-400 text-xs col-span-4 text-center py-2">사진 없음</p>'; return; }
c.innerHTML = photos.map(p => {
const fname = (p.photo_path||'').replace(/^\/uploads\//, '');
return `
<div class="relative group cursor-pointer" onclick="document.getElementById('photoViewImage').src='/uploads/${fname}'; document.getElementById('photoViewModal').classList.remove('hidden');">
<img src="/uploads/${fname}" class="w-full h-20 object-cover rounded">
<button onclick="event.stopPropagation(); deleteEqPhoto(${p.photo_id})" class="absolute top-0.5 right-0.5 bg-red-500 text-white rounded-full w-4 h-4 text-[10px] leading-4 text-center opacity-0 group-hover:opacity-100">&times;</button>
</div>`; }).join('');
} catch(e) { c.innerHTML = '<p class="text-red-400 text-xs col-span-4">로드 실패</p>'; }
}
async function uploadEqPhoto() {
const file = document.getElementById('eqPhotoFile').files[0]; if (!file || !eqDetailEqId) return;
try {
const fd = new FormData(); fd.append('photo', file); const token = getToken();
const res = await fetch(`${API_BASE}/equipments/${eqDetailEqId}/photos`, { method: 'POST', headers: { 'Authorization': token ? `Bearer ${token}` : '' }, body: fd });
const result = await res.json(); if (!res.ok) throw new Error(result.error || '업로드 실패');
showToast('사진이 추가되었습니다.'); loadEqPhotos(eqDetailEqId);
} catch(e) { showToast(e.message, 'error'); }
document.getElementById('eqPhotoFile').value = '';
}
async function deleteEqPhoto(photoId) {
if (!confirm('사진을 삭제하시겠습니까?')) return;
try { await api(`/equipments/photos/${photoId}`, { method: 'DELETE' }); showToast('삭제됨'); loadEqPhotos(eqDetailEqId); } catch(e) { showToast(e.message, 'error'); }
}