/** * issue-view.js — 부적합 조회 페이지 스크립트 */ let currentUser = null; let issues = []; let projects = []; // 프로젝트 데이터 캐시 let currentRange = 'week'; // 기본값: 이번 주 // 애니메이션 함수들 function animateHeaderAppearance() { console.log('헤더 애니메이션 시작'); // 헤더 요소 찾기 (공통 헤더가 생성한 요소) const headerElement = document.querySelector('header') || document.querySelector('[class*="header"]') || document.querySelector('nav'); if (headerElement) { headerElement.classList.add('header-fade-in'); setTimeout(() => { headerElement.classList.add('visible'); // 헤더 애니메이션 완료 후 본문 애니메이션 setTimeout(() => { animateContentAppearance(); }, 200); }, 50); } else { // 헤더를 찾지 못했으면 바로 본문 애니메이션 animateContentAppearance(); } } // 본문 컨텐츠 애니메이션 function animateContentAppearance() { // 모든 content-fade-in 요소들을 순차적으로 애니메이션 const contentElements = document.querySelectorAll('.content-fade-in'); contentElements.forEach((element, index) => { setTimeout(() => { element.classList.add('visible'); }, index * 100); // 100ms씩 지연 }); } // API 로드 후 초기화 함수 async function initializeIssueView() { const token = TokenManager.getToken(); if (!token) { window.location.href = '/index.html'; return; } try { const user = await AuthAPI.getCurrentUser(); currentUser = user; localStorage.setItem('sso_user', JSON.stringify(user)); // 공통 헤더 초기화 await window.commonHeader.init(user, 'issues_view'); // 헤더 초기화 후 부드러운 애니메이션 시작 setTimeout(() => { animateHeaderAppearance(); }, 100); // 사용자 역할에 따른 페이지 제목 설정 updatePageTitle(user); // 페이지 접근 권한 체크 (부적합 조회 페이지) setTimeout(() => { if (!canAccessPage('issues_view')) { alert('부적합 조회 페이지에 접근할 권한이 없습니다.'); window.location.href = '/index.html'; return; } }, 500); } catch (error) { console.error('인증 실패:', error); TokenManager.removeToken(); TokenManager.removeUser(); window.location.href = '/index.html'; return; } // 프로젝트 로드 await loadProjects(); // 기본 날짜 설정 (이번 주) setDefaultDateRange(); // 기본값: 이번 주 데이터 로드 await loadIssues(); setDateRange('week'); } // showImageModal은 photo-modal.js에서 제공됨 // 기본 날짜 범위 설정 function setDefaultDateRange() { const today = new Date(); const weekStart = new Date(today); weekStart.setDate(today.getDate() - today.getDay()); // 이번 주 일요일 // 날짜 입력 필드에 기본값 설정 document.getElementById('startDateInput').value = formatDateForInput(weekStart); document.getElementById('endDateInput').value = formatDateForInput(today); } // 날짜를 input[type="date"] 형식으로 포맷 function formatDateForInput(date) { return date.toISOString().split('T')[0]; } // 날짜 필터 적용 function applyDateFilter() { const startDate = document.getElementById('startDateInput').value; const endDate = document.getElementById('endDateInput').value; if (!startDate || !endDate) { alert('시작날짜와 끝날짜를 모두 선택해주세요.'); return; } if (new Date(startDate) > new Date(endDate)) { alert('시작날짜는 끝날짜보다 이전이어야 합니다.'); return; } // 필터 적용 filterIssues(); } // 사용자 역할에 따른 페이지 제목 업데이트 function updatePageTitle(user) { const titleElement = document.getElementById('pageTitle'); const descriptionElement = document.getElementById('pageDescription'); if (user.role === 'admin') { titleElement.innerHTML = ` 전체 부적합 조회 `; descriptionElement.textContent = '모든 사용자가 등록한 부적합 사항을 관리할 수 있습니다'; } else { titleElement.innerHTML = ` 내 부적합 조회 `; descriptionElement.textContent = '내가 등록한 부적합 사항을 확인할 수 있습니다'; } } // 프로젝트 로드 (API 기반) async function loadProjects() { try { // 모든 프로젝트 로드 (활성/비활성 모두 - 기존 데이터 조회를 위해) projects = await ProjectsAPI.getAll(false); const projectFilter = document.getElementById('projectFilter'); // 기존 옵션 제거 (전체 프로젝트 옵션 제외) projectFilter.innerHTML = ''; // 모든 프로젝트 추가 projects.forEach(project => { const option = document.createElement('option'); option.value = project.id; option.textContent = `${project.job_no} / ${project.project_name}${!project.is_active ? ' (비활성)' : ''}`; projectFilter.appendChild(option); }); } catch (error) { console.error('프로젝트 로드 실패:', error); } } // 이슈 필터링 // 검토 상태 확인 함수 function isReviewCompleted(issue) { return issue.status === 'complete' && issue.work_hours && issue.work_hours > 0; } // 날짜 필터링 함수 function filterByDate(issues, dateFilter) { const now = new Date(); const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); switch (dateFilter) { case 'today': return issues.filter(issue => { const issueDate = new Date(issue.report_date); return issueDate >= today; }); case 'week': const weekStart = new Date(today); weekStart.setDate(today.getDate() - today.getDay()); return issues.filter(issue => { const issueDate = new Date(issue.report_date); return issueDate >= weekStart; }); case 'month': const monthStart = new Date(today.getFullYear(), today.getMonth(), 1); return issues.filter(issue => { const issueDate = new Date(issue.report_date); return issueDate >= monthStart; }); default: return issues; } } // 날짜 범위별 필터링 함수 function filterByDateRange(issues, range) { const now = new Date(); const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); switch (range) { case 'today': return issues.filter(issue => { const issueDate = new Date(issue.created_at); const issueDay = new Date(issueDate.getFullYear(), issueDate.getMonth(), issueDate.getDate()); return issueDay.getTime() === today.getTime(); }); case 'week': const weekStart = new Date(today); weekStart.setDate(today.getDate() - today.getDay()); const weekEnd = new Date(weekStart); weekEnd.setDate(weekStart.getDate() + 6); weekEnd.setHours(23, 59, 59, 999); return issues.filter(issue => { const issueDate = new Date(issue.created_at); return issueDate >= weekStart && issueDate <= weekEnd; }); case 'month': const monthStart = new Date(today.getFullYear(), today.getMonth(), 1); const monthEnd = new Date(today.getFullYear(), today.getMonth() + 1, 0); monthEnd.setHours(23, 59, 59, 999); return issues.filter(issue => { const issueDate = new Date(issue.created_at); return issueDate >= monthStart && issueDate <= monthEnd; }); default: return issues; } } function filterIssues() { // 필터 값 가져오기 const selectedProjectId = document.getElementById('projectFilter').value; const reviewStatusFilter = document.getElementById('reviewStatusFilter').value; let filteredIssues = [...issues]; // 프로젝트 필터 적용 if (selectedProjectId) { filteredIssues = filteredIssues.filter(issue => { const issueProjectId = issue.project_id || issue.projectId; return issueProjectId && (issueProjectId == selectedProjectId || issueProjectId.toString() === selectedProjectId.toString()); }); } // 워크플로우 상태 필터 적용 if (reviewStatusFilter) { filteredIssues = filteredIssues.filter(issue => { // 새로운 워크플로우 시스템 사용 if (issue.review_status) { return issue.review_status === reviewStatusFilter; } // 기존 데이터 호환성을 위한 폴백 else { const isCompleted = isReviewCompleted(issue); if (reviewStatusFilter === 'pending_review') return !isCompleted; if (reviewStatusFilter === 'completed') return isCompleted; return false; } }); } // 날짜 범위 필터 적용 (입력 필드에서 선택된 범위) const startDateInput = document.getElementById('startDateInput').value; const endDateInput = document.getElementById('endDateInput').value; if (startDateInput && endDateInput) { filteredIssues = filteredIssues.filter(issue => { const issueDate = new Date(issue.report_date); const startOfDay = new Date(startDateInput); startOfDay.setHours(0, 0, 0, 0); const endOfDay = new Date(endDateInput); endOfDay.setHours(23, 59, 59, 999); return issueDate >= startOfDay && issueDate <= endOfDay; }); } // 전역 변수에 필터링된 결과 저장 window.filteredIssues = filteredIssues; displayResults(); } // 프로젝트 정보 표시용 함수 function getProjectInfo(projectId) { if (!projectId) { return '프로젝트 미지정'; } // 전역 projects 배열에서 찾기 const project = projects.find(p => p.id == projectId); if (project) { return `${project.job_no} / ${project.project_name}`; } return `프로젝트 ID: ${projectId} (정보 없음)`; } // 날짜 범위 설정 및 자동 조회 function setDateRange(range) { currentRange = range; const today = new Date(); let startDate, endDate; switch (range) { case 'today': startDate = new Date(today); endDate = new Date(today); break; case 'week': startDate = new Date(today); startDate.setDate(today.getDate() - today.getDay()); // 이번 주 일요일 endDate = new Date(today); break; case 'month': startDate = new Date(today.getFullYear(), today.getMonth(), 1); // 이번 달 1일 endDate = new Date(today); break; case 'all': startDate = new Date(2020, 0, 1); // 충분히 과거 날짜 endDate = new Date(today); break; default: return; } // 날짜 입력 필드 업데이트 document.getElementById('startDateInput').value = formatDateForInput(startDate); document.getElementById('endDateInput').value = formatDateForInput(endDate); // 필터 적용 filterIssues(); } // 부적합 사항 로드 (자신이 올린 내용만) async function loadIssues() { const container = document.getElementById('issueResults'); container.innerHTML = `
데이터를 불러오는 중...
데이터를 불러오는데 실패했습니다.
${emptyMessage}
${currentUser.role !== 'admin' ? ` ` : ''}${issue.description}
${issue.location_info ? `
이 부적합 사항을 삭제하시겠습니까?
삭제된 데이터는 로그로 보관되지만 복구할 수 없습니다.