/* ===== 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 ? `${p}` : ''; } 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 = ''; 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 = `

${err.message}

`; } } function renderSidebar() { const c = document.getElementById('wpSidebarContent'); if (!c) return; let html = ''; if (wpNavLevel === 'categories') { // 공장 목록 레벨 html += '
공장 선택
'; html += ``; if (!workplaceCategories.length) { html += '

등록된 공장이 없습니다.

'; } else { html += '
'; workplaceCategories.forEach(cat => { const count = workplaces.filter(w => w.category_id == cat.category_id).length; html += `
${cat.category_name}
${count}
`; }); // 미분류 작업장 const uncategorized = workplaces.filter(w => !w.category_id); if (uncategorized.length) { html += `
미분류
${uncategorized.length}
`; } html += '
'; } } else { // 작업장 목록 레벨 (특정 공장 내) html += ``; html += `
${wpNavCategoryName}
`; html += ``; const filtered = wpNavCategoryId === 0 ? workplaces.filter(w => !w.category_id) : workplaces.filter(w => w.category_id == wpNavCategoryId); if (!filtered.length) { html += '

등록된 작업장이 없습니다.

'; } else { html += '
'; filtered.forEach(w => { html += `
${w.workplace_name}
${purposeBadge(w.workplace_purpose)} ${w.is_active === 0 || w.is_active === false ? '비활성' : ''}
${w.is_active !== 0 && w.is_active !== false ? `` : ''}
`; }); html += '
'; } } 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 = `${catName} - 구역지도`; selectedMapCategoryId = categoryId; if (categoryId === 0) { document.getElementById('layoutPreviewArea').classList.remove('hidden'); document.getElementById('layoutPreviewCanvas').classList.add('hidden'); document.getElementById('layoutPreviewArea').innerHTML = '

미분류 작업장에는 구역지도가 없습니다.

'; 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 `${labels[status] || status || ''}`; } 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 = `

${e.message}

`; } } 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 = '

설비가 없습니다.

'; return; } c.innerHTML = filtered.map(e => `
${e.equipment_code || ''}${e.equipment_name} ${e.is_temporarily_moved ? '' : ''}
${e.equipment_type ? `${e.equipment_type}` : ''} ${e.manufacturer ? `${e.manufacturer}` : ''} ${eqStatusBadge(e.status)}
`).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 = ''; 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 = `
유형: ${fmt(eq.equipment_type)}
상태: ${eqStatusBadge(eq.status)}
제조사: ${fmt(eq.manufacturer)}
모델: ${fmt(eq.model_name)}
공급업체: ${fmt(eq.supplier)}
구매가격: ${fmtPrice(eq.purchase_price)}
설치일: ${fmtDate(eq.installation_date)}
시리얼: ${fmt(eq.serial_number)}
사양: ${fmt(eq.specifications)}
비고: ${fmt(eq.notes)}
`; 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 = '

사진 없음

'; return; } c.innerHTML = photos.map(p => { const fname = (p.photo_path||'').replace(/^\/uploads\//, ''); return `
`; }).join(''); } catch(e) { c.innerHTML = '

로드 실패

'; } } 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'); } }