Files
M-Project/frontend/admin.html
Hyungi Ahn 236e1ca493 feat: 사용자 관리에 부서 정보 추가 및 편집 기능 구현
🏢 Department Management System:
- 5개 부서 지원: 생산, 품질, 구매, 설계, 영업
- 사용자 생성/수정 시 부서 선택 가능
- 부서별 사용자 분류 및 표시

📊 Database Schema Updates:
- department_type ENUM 추가 (production, quality, purchasing, design, sales)
- users 테이블에 department 컬럼 추가
- idx_users_department 인덱스 생성 (성능 최적화)
- 014_add_user_department.sql 마이그레이션 실행

🔧 Backend Enhancements:
- DepartmentType ENUM 클래스 추가 (models.py, schemas.py)
- User 모델에 department 필드 추가
- UserBase, UserUpdate 스키마에 department 필드 포함
- 기존 API 엔드포인트 자동 호환

🎨 Frontend UI Improvements:
- 사용자 추가 폼에 부서 선택 드롭다운 추가
- 사용자 목록에 부서 정보 배지 표시 (녹색 배경)
- 사용자 편집 모달 새로 구현
- 부서명 한글 변환 함수 (AuthAPI.getDepartmentLabel)

 User Management Features:
- 편집 버튼으로 사용자 정보 수정 가능
- 부서, 이름, 권한 실시간 변경
- 사용자 ID는 수정 불가 (읽기 전용)
- 모달 기반 직관적 UI

🔍 Visual Enhancements:
- 부서 정보 아이콘 (fas fa-building)
- 색상 코딩: 부서(녹색), 권한(빨강/파랑)
- 반응형 레이아웃 (flex-1, gap-3)
- 호버 효과 및 트랜지션

🚀 API Integration:
- AuthAPI.getDepartments() - 부서 목록 반환
- AuthAPI.getDepartmentLabel() - 부서명 변환
- AuthAPI.updateUser() - 부서 정보 포함 업데이트
- 기존 createUser API 확장 지원

Expected Result:
 사용자 생성 시 부서 선택 가능
 사용자 목록에 부서 정보 표시
 편집 버튼으로 부서 변경 가능
 5개 부서 분류 시스템 완성
 직관적인 사용자 관리 UI
2025-10-25 13:29:47 +09:00

914 lines
40 KiB
HTML

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>관리자 페이지 - 작업보고서</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<!-- Custom Styles -->
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 50%, #f0f9ff 100%);
min-height: 100vh;
}
.glass-effect {
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(10px);
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}
.nav-link {
padding: 0.5rem 1rem;
border-radius: 0.5rem;
color: #4b5563;
transition: all 0.2s;
white-space: nowrap;
}
.nav-link:hover {
background-color: #f3f4f6;
color: #1f2937;
}
.nav-link.active {
background-color: #3b82f6;
color: white;
}
.input-field {
background: white;
border: 1px solid #e5e7eb;
transition: all 0.2s;
}
.input-field:focus {
outline: none;
border-color: #60a5fa;
box-shadow: 0 0 0 3px rgba(96, 165, 250, 0.1);
}
/* 부드러운 페이드인 애니메이션 */
.fade-in {
opacity: 0;
transform: translateY(20px);
transition: opacity 0.6s ease-out, transform 0.6s ease-out;
}
.fade-in.visible {
opacity: 1;
transform: translateY(0);
}
/* 헤더 전용 빠른 페이드인 */
.header-fade-in {
opacity: 0;
transform: translateY(-10px);
transition: opacity 0.4s ease-out, transform 0.4s ease-out;
}
.header-fade-in.visible {
opacity: 1;
transform: translateY(0);
}
/* 본문 컨텐츠 지연 페이드인 */
.content-fade-in {
opacity: 0;
transform: translateY(30px);
transition: opacity 0.8s ease-out, transform 0.8s ease-out;
transition-delay: 0.2s;
}
.content-fade-in.visible {
opacity: 1;
transform: translateY(0);
}
</style>
</head>
<body>
<!-- 공통 헤더가 여기에 자동으로 삽입됩니다 -->
<!-- Main Content -->
<main class="container mx-auto px-4 py-8 max-w-6xl content-fade-in" style="padding-top: 80px;">
<div class="grid md:grid-cols-2 gap-6">
<!-- 사용자 추가 섹션 -->
<div class="bg-white rounded-xl shadow-sm p-6">
<h2 class="text-lg font-semibold text-gray-800 mb-4">
<i class="fas fa-user-plus text-blue-500 mr-2"></i>사용자 추가
</h2>
<form id="addUserForm" class="space-y-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">사용자 ID</label>
<input
type="text"
id="newUsername"
class="input-field w-full px-3 py-2 rounded-lg"
placeholder="한글 가능 (예: 홍길동)"
required
>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">이름</label>
<input
type="text"
id="newFullName"
class="input-field w-full px-3 py-2 rounded-lg"
placeholder="실명 입력"
required
>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">비밀번호</label>
<input
type="password"
id="newPassword"
class="input-field w-full px-3 py-2 rounded-lg"
placeholder="초기 비밀번호"
required
>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">부서</label>
<select id="newDepartment" class="input-field w-full px-3 py-2 rounded-lg">
<option value="">부서 선택 (선택사항)</option>
<option value="production">생산</option>
<option value="quality">품질</option>
<option value="purchasing">구매</option>
<option value="design">설계</option>
<option value="sales">영업</option>
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">권한</label>
<select id="newRole" class="input-field w-full px-3 py-2 rounded-lg">
<option value="user">일반 사용자</option>
<option value="admin">관리자</option>
</select>
</div>
<button
type="submit"
class="w-full px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
>
<i class="fas fa-plus mr-2"></i>사용자 추가
</button>
</form>
</div>
<!-- 사용자 목록 섹션 -->
<div class="bg-white rounded-xl shadow-sm p-6">
<h2 class="text-lg font-semibold text-gray-800 mb-4">
<i class="fas fa-users text-green-500 mr-2"></i>사용자 목록
</h2>
<div id="userList" class="space-y-3">
<!-- 사용자 목록이 여기에 표시됩니다 -->
<div class="text-gray-500 text-center py-8">
<i class="fas fa-spinner fa-spin text-3xl"></i>
<p>로딩 중...</p>
</div>
</div>
</div>
</div>
<!-- 페이지 권한 관리 섹션 (관리자용) -->
<div id="pagePermissionSection" class="mt-6">
<div class="bg-white rounded-xl shadow-sm p-6">
<h2 class="text-lg font-semibold text-gray-800 mb-4">
<i class="fas fa-shield-alt text-purple-500 mr-2"></i>페이지 접근 권한 관리
</h2>
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 mb-2">사용자 선택</label>
<select id="permissionUserSelect" class="input-field w-full max-w-xs px-3 py-2 rounded-lg">
<option value="">사용자를 선택하세요</option>
</select>
</div>
<div id="pagePermissionGrid" class="hidden">
<h3 class="text-md font-medium text-gray-700 mb-3">페이지별 접근 권한</h3>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<!-- 페이지 권한 체크박스들이 여기에 동적으로 생성됩니다 -->
</div>
<div class="mt-4 pt-4 border-t">
<button
id="savePermissionsBtn"
class="px-4 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors"
>
<i class="fas fa-save mr-2"></i>권한 저장
</button>
<span id="permissionSaveStatus" class="ml-3 text-sm"></span>
</div>
</div>
</div>
</div>
<!-- 비밀번호 변경 섹션 (사용자용) -->
<div id="passwordChangeSection" class="hidden mt-6">
<div class="bg-white rounded-xl shadow-sm p-6 max-w-md mx-auto">
<h2 class="text-lg font-semibold text-gray-800 mb-4">
<i class="fas fa-key text-yellow-500 mr-2"></i>비밀번호 변경
</h2>
<form id="changePasswordForm" class="space-y-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">현재 비밀번호</label>
<input
type="password"
id="currentPassword"
class="input-field w-full px-3 py-2 rounded-lg"
required
>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">새 비밀번호</label>
<input
type="password"
id="newPasswordChange"
class="input-field w-full px-3 py-2 rounded-lg"
required
>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">새 비밀번호 확인</label>
<input
type="password"
id="confirmPassword"
class="input-field w-full px-3 py-2 rounded-lg"
required
>
</div>
<button
type="submit"
class="w-full px-4 py-2 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600 transition-colors"
>
<i class="fas fa-save mr-2"></i>비밀번호 변경
</button>
</form>
</div>
</div>
</main>
<!-- 사용자 편집 모달 -->
<div id="editUserModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
<div class="flex items-center justify-center min-h-screen p-4">
<div class="bg-white rounded-xl max-w-md w-full p-6">
<div class="flex items-center justify-between mb-4">
<h3 class="text-lg font-semibold text-gray-900">사용자 정보 수정</h3>
<button onclick="closeEditModal()" class="text-gray-400 hover:text-gray-600">
<i class="fas fa-times text-xl"></i>
</button>
</div>
<form id="editUserForm" class="space-y-4">
<input type="hidden" id="editUserId">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">사용자 ID</label>
<input
type="text"
id="editUsername"
class="input-field w-full px-3 py-2 rounded-lg bg-gray-100"
readonly
>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">이름</label>
<input
type="text"
id="editFullName"
class="input-field w-full px-3 py-2 rounded-lg"
placeholder="실명 입력"
>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">부서</label>
<select id="editDepartment" class="input-field w-full px-3 py-2 rounded-lg">
<option value="">부서 선택 (선택사항)</option>
<option value="production">생산</option>
<option value="quality">품질</option>
<option value="purchasing">구매</option>
<option value="design">설계</option>
<option value="sales">영업</option>
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">권한</label>
<select id="editRole" class="input-field w-full px-3 py-2 rounded-lg">
<option value="user">일반 사용자</option>
<option value="admin">관리자</option>
</select>
</div>
<div class="flex gap-3 pt-4">
<button
type="button"
onclick="closeEditModal()"
class="flex-1 px-4 py-2 bg-gray-300 text-gray-700 rounded-lg hover:bg-gray-400 transition-colors"
>
취소
</button>
<button
type="submit"
class="flex-1 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
>
<i class="fas fa-save mr-2"></i>저장
</button>
</div>
</form>
</div>
</div>
</div>
<!-- Scripts -->
<script src="/static/js/date-utils.js?v=20250917"></script>
<script src="/static/js/core/permissions.js?v=20251025"></script>
<script src="/static/js/components/common-header.js?v=20251025"></script>
<script src="/static/js/core/page-manager.js?v=20251025"></script>
<script>
let currentUser = null;
let users = [];
// 애니메이션 함수들
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');
console.log('✨ 헤더 페이드인 완료');
// 헤더 애니메이션 완료 후 본문 애니메이션
setTimeout(() => {
animateContentAppearance();
}, 200);
}, 50);
} else {
// 헤더를 찾지 못했으면 바로 본문 애니메이션
console.log('⚠️ 헤더 요소를 찾지 못함 - 본문 애니메이션 시작');
animateContentAppearance();
}
}
// 본문 컨텐츠 애니메이션
function animateContentAppearance() {
console.log('🎨 본문 컨텐츠 애니메이션 시작');
// 모든 content-fade-in 요소들을 순차적으로 애니메이션
const contentElements = document.querySelectorAll('.content-fade-in');
contentElements.forEach((element, index) => {
setTimeout(() => {
element.classList.add('visible');
console.log(`✨ 컨텐츠 ${index + 1} 페이드인 완료`);
}, index * 100); // 100ms씩 지연
});
}
// API 로드 후 초기화 함수
async function initializeAdmin() {
const token = localStorage.getItem('access_token');
if (!token) {
window.location.href = '/index.html';
return;
}
try {
const user = await AuthAPI.getCurrentUser();
currentUser = user;
localStorage.setItem('currentUser', JSON.stringify(user));
// 공통 헤더 초기화
await window.commonHeader.init(user, 'users_manage');
// 헤더 초기화 후 부드러운 애니메이션 시작
setTimeout(() => {
animateHeaderAppearance();
}, 100);
// 페이지 접근 권한 체크
setTimeout(() => {
if (!canAccessPage('users_manage')) {
alert('사용자 관리 페이지에 접근할 권한이 없습니다.');
window.location.href = '/index.html';
return;
}
}, 500);
} catch (error) {
console.error('인증 실패:', error);
localStorage.removeItem('access_token');
localStorage.removeItem('currentUser');
window.location.href = '/index.html';
return;
}
// 관리자가 아니면 비밀번호 변경만 표시
if (currentUser.role !== 'admin') {
document.querySelector('.grid').style.display = 'none';
document.getElementById('passwordChangeSection').classList.remove('hidden');
} else {
// 관리자면 사용자 목록 로드
await loadUsers();
}
}
// 사용자 추가
document.getElementById('addUserForm').addEventListener('submit', async (e) => {
e.preventDefault();
const userData = {
username: document.getElementById('newUsername').value.trim(),
full_name: document.getElementById('newFullName').value.trim(),
password: document.getElementById('newPassword').value,
department: document.getElementById('newDepartment').value || null,
role: document.getElementById('newRole').value
};
try {
await AuthAPI.createUser(userData);
// 성공
alert('사용자가 추가되었습니다.');
// 폼 초기화
document.getElementById('addUserForm').reset();
// 목록 새로고침
await loadUsers();
} catch (error) {
alert(error.message || '사용자 추가에 실패했습니다.');
}
});
// 비밀번호 변경
document.getElementById('changePasswordForm').addEventListener('submit', async (e) => {
e.preventDefault();
const currentPassword = document.getElementById('currentPassword').value;
const newPassword = document.getElementById('newPasswordChange').value;
const confirmPassword = document.getElementById('confirmPassword').value;
if (newPassword !== confirmPassword) {
alert('새 비밀번호가 일치하지 않습니다.');
return;
}
try {
await AuthAPI.changePassword(currentPassword, newPassword);
alert('비밀번호가 변경되었습니다. 다시 로그인해주세요.');
AuthAPI.logout();
} catch (error) {
alert(error.message || '비밀번호 변경에 실패했습니다.');
}
});
// 사용자 목록 로드
async function loadUsers() {
try {
// 백엔드 API에서 사용자 목록 로드
users = await AuthAPI.getUsers();
displayUsers();
} catch (error) {
console.error('사용자 목록 로드 실패:', error);
// API 실패 시 빈 배열로 초기화
users = [];
displayUsers();
}
}
// 사용자 목록 표시
function displayUsers() {
const container = document.getElementById('userList');
if (users.length === 0) {
container.innerHTML = '<p class="text-gray-500 text-center">등록된 사용자가 없습니다.</p>';
return;
}
container.innerHTML = users.map(user => `
<div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
<div class="flex-1">
<div class="font-medium text-gray-800">
<i class="fas fa-user mr-2 text-gray-500"></i>
${user.full_name || user.username}
</div>
<div class="text-sm text-gray-600 flex items-center gap-3">
<span>ID: ${user.username}</span>
${user.department ? `
<span class="px-2 py-0.5 rounded text-xs bg-green-100 text-green-700">
<i class="fas fa-building mr-1"></i>${AuthAPI.getDepartmentLabel(user.department)}
</span>
` : ''}
<span class="px-2 py-0.5 rounded text-xs ${
user.role === 'admin'
? 'bg-red-100 text-red-700'
: 'bg-blue-100 text-blue-700'
}">
${user.role === 'admin' ? '관리자' : '사용자'}
</span>
</div>
</div>
<div class="flex gap-2">
<button
onclick="editUser(${user.id})"
class="px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors text-sm"
>
<i class="fas fa-edit mr-1"></i>편집
</button>
<button
onclick="resetPassword('${user.username}')"
class="px-3 py-1 bg-yellow-500 text-white rounded hover:bg-yellow-600 transition-colors text-sm"
>
<i class="fas fa-key mr-1"></i>비밀번호 초기화
</button>
${user.username !== 'hyungi' ? `
<button
onclick="deleteUser('${user.username}')"
class="px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600 transition-colors text-sm"
>
<i class="fas fa-trash mr-1"></i>삭제
</button>
` : ''}
</div>
</div>
`).join('');
}
// 비밀번호 초기화
async function resetPassword(username) {
if (!confirm(`${username} 사용자의 비밀번호를 "000000"으로 초기화하시겠습니까?`)) {
return;
}
try {
// 사용자 ID 찾기
const user = users.find(u => u.username === username);
if (!user) {
alert('사용자를 찾을 수 없습니다.');
return;
}
// 백엔드 API로 비밀번호 초기화
await AuthAPI.resetPassword(user.id, '000000');
alert(`${username} 사용자의 비밀번호가 "000000"으로 초기화되었습니다.`);
// 목록 새로고침
await loadUsers();
} catch (error) {
alert('비밀번호 초기화에 실패했습니다: ' + error.message);
}
}
// 사용자 삭제
async function deleteUser(username) {
if (!confirm(`정말 ${username} 사용자를 삭제하시겠습니까?`)) {
return;
}
try {
await AuthAPI.deleteUser(username);
alert('사용자가 삭제되었습니다.');
await loadUsers();
} catch (error) {
alert(error.message || '삭제에 실패했습니다.');
}
}
// 사용자 편집 모달 열기
function editUser(userId) {
const user = users.find(u => u.id === userId);
if (!user) {
alert('사용자를 찾을 수 없습니다.');
return;
}
// 모달 필드에 현재 값 설정
document.getElementById('editUserId').value = user.id;
document.getElementById('editUsername').value = user.username;
document.getElementById('editFullName').value = user.full_name || '';
document.getElementById('editDepartment').value = user.department || '';
document.getElementById('editRole').value = user.role;
// 모달 표시
document.getElementById('editUserModal').classList.remove('hidden');
}
// 사용자 편집 모달 닫기
function closeEditModal() {
document.getElementById('editUserModal').classList.add('hidden');
}
// 사용자 편집 폼 제출
document.getElementById('editUserForm').addEventListener('submit', async (e) => {
e.preventDefault();
const userId = document.getElementById('editUserId').value;
const userData = {
full_name: document.getElementById('editFullName').value.trim() || null,
department: document.getElementById('editDepartment').value || null,
role: document.getElementById('editRole').value
};
try {
await AuthAPI.updateUser(userId, userData);
alert('사용자 정보가 수정되었습니다.');
closeEditModal();
await loadUsers(); // 목록 새로고침
} catch (error) {
alert(error.message || '사용자 정보 수정에 실패했습니다.');
}
});
// 페이지 권한 관리 기능
let selectedUserId = null;
let currentPermissions = {};
// AuthAPI를 사용하여 사용자 목록 로드
async function loadUsers() {
try {
users = await AuthAPI.getUsers();
displayUsers();
updatePermissionUserSelect(); // 권한 관리 드롭다운 업데이트
} catch (error) {
console.error('사용자 로드 실패:', error);
document.getElementById('userList').innerHTML = `
<div class="text-red-500 text-center py-8">
<i class="fas fa-exclamation-triangle text-3xl"></i>
<p>사용자 목록을 불러올 수 없습니다.</p>
<p class="text-sm mt-2">오류: ${error.message}</p>
</div>
`;
}
}
// 권한 관리 사용자 선택 드롭다운 업데이트
function updatePermissionUserSelect() {
const select = document.getElementById('permissionUserSelect');
select.innerHTML = '<option value="">사용자를 선택하세요</option>';
// 일반 사용자만 표시 (admin 제외)
const regularUsers = users.filter(user => user.role === 'user');
regularUsers.forEach(user => {
const option = document.createElement('option');
option.value = user.id;
option.textContent = `${user.full_name || user.username} (${user.username})`;
select.appendChild(option);
});
}
// 사용자 선택 시 페이지 권한 그리드 표시
document.getElementById('permissionUserSelect').addEventListener('change', async (e) => {
selectedUserId = e.target.value;
if (selectedUserId) {
await loadUserPagePermissions(selectedUserId);
showPagePermissionGrid();
} else {
hidePagePermissionGrid();
}
});
// 사용자의 페이지 권한 로드
async function loadUserPagePermissions(userId) {
try {
// 기본 페이지 목록 가져오기
const defaultPages = {
'issues_create': { title: '부적합 등록', defaultAccess: true },
'issues_view': { title: '부적합 조회', defaultAccess: true },
'issues_manage': { title: '부적합 관리', defaultAccess: true },
'issues_inbox': { title: '수신함', defaultAccess: true },
'issues_management': { title: '관리함', defaultAccess: false },
'issues_archive': { title: '폐기함', defaultAccess: false },
'projects_manage': { title: '프로젝트 관리', defaultAccess: false },
'daily_work': { title: '일일 공수', defaultAccess: false },
'reports': { title: '보고서', defaultAccess: false }
};
// 기본값으로 초기화
currentPermissions = {};
Object.keys(defaultPages).forEach(pageName => {
currentPermissions[pageName] = defaultPages[pageName].defaultAccess;
});
// 실제 API 호출로 사용자별 설정된 권한 가져오기
try {
const response = await fetch(`/api/users/${userId}/page-permissions`, {
headers: {
'Authorization': `Bearer ${localStorage.getItem('access_token')}`
}
});
if (response.ok) {
const permissions = await response.json();
permissions.forEach(perm => {
currentPermissions[perm.page_name] = perm.can_access;
});
console.log('사용자 권한 로드 완료:', currentPermissions);
} else {
console.warn('사용자 권한 로드 실패, 기본값 사용');
}
} catch (apiError) {
console.warn('API 호출 실패, 기본값 사용:', apiError);
}
} catch (error) {
console.error('페이지 권한 로드 실패:', error);
}
}
// 페이지 권한 그리드 표시
function showPagePermissionGrid() {
const grid = document.getElementById('pagePermissionGrid');
const gridContainer = grid.querySelector('.grid');
// 페이지 권한 체크박스 생성 (카테고리별로 그룹화)
const pageCategories = {
'부적합 관리': {
'issues_create': { title: '부적합 등록', icon: 'fas fa-plus-circle', color: 'text-green-600' },
'issues_view': { title: '부적합 조회', icon: 'fas fa-search', color: 'text-purple-600' },
'issues_manage': { title: '목록 관리 (통합)', icon: 'fas fa-tasks', color: 'text-orange-600' }
},
'목록 관리 세부': {
'issues_inbox': { title: '📥 수신함', icon: 'fas fa-inbox', color: 'text-blue-600' },
'issues_management': { title: '⚙️ 관리함', icon: 'fas fa-cog', color: 'text-green-600' },
'issues_archive': { title: '🗃️ 폐기함', icon: 'fas fa-archive', color: 'text-gray-600' }
},
'시스템 관리': {
'projects_manage': { title: '프로젝트 관리', icon: 'fas fa-folder-open', color: 'text-indigo-600' },
'daily_work': { title: '일일 공수', icon: 'fas fa-calendar-check', color: 'text-blue-600' },
'reports': { title: '보고서', icon: 'fas fa-chart-bar', color: 'text-red-600' },
'users_manage': { title: '사용자 관리', icon: 'fas fa-users-cog', color: 'text-purple-600' }
}
};
let html = '';
// 카테고리별로 그룹화하여 표시
Object.entries(pageCategories).forEach(([categoryName, pages]) => {
html += `
<div class="col-span-full">
<h4 class="text-sm font-semibold text-gray-800 mb-3 pb-2 border-b border-gray-200">
${categoryName}
</h4>
</div>
`;
Object.entries(pages).forEach(([pageName, pageInfo]) => {
const isChecked = currentPermissions[pageName] || false;
const isDefault = currentPermissions[pageName] === undefined ?
(pageInfo.title.includes('등록') || pageInfo.title.includes('조회') || pageInfo.title.includes('수신함')) : false;
html += `
<div class="flex items-center p-3 border rounded-lg hover:bg-gray-50 transition-colors ${isChecked ? 'border-blue-300 bg-blue-50' : 'border-gray-200'}">
<input
type="checkbox"
id="perm_${pageName}"
${isChecked ? 'checked' : ''}
class="mr-3 h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
onchange="this.parentElement.classList.toggle('border-blue-300', this.checked); this.parentElement.classList.toggle('bg-blue-50', this.checked);"
>
<label for="perm_${pageName}" class="flex-1 cursor-pointer">
<div class="flex items-center">
<i class="${pageInfo.icon} ${pageInfo.color} mr-2"></i>
<span class="text-sm font-medium text-gray-700">${pageInfo.title}</span>
${isDefault ? '<span class="ml-2 text-xs bg-green-100 text-green-800 px-2 py-1 rounded-full">기본</span>' : ''}
</div>
</label>
</div>
`;
});
});
gridContainer.innerHTML = html;
grid.classList.remove('hidden');
}
// 페이지 권한 그리드 숨기기
function hidePagePermissionGrid() {
document.getElementById('pagePermissionGrid').classList.add('hidden');
}
// 권한 저장
document.getElementById('savePermissionsBtn').addEventListener('click', async () => {
if (!selectedUserId) return;
const saveBtn = document.getElementById('savePermissionsBtn');
const statusSpan = document.getElementById('permissionSaveStatus');
saveBtn.disabled = true;
saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>저장 중...';
statusSpan.textContent = '';
try {
// 체크박스 상태 수집 (모든 페이지 포함)
const allPages = [
'issues_create', 'issues_view', 'issues_manage',
'issues_inbox', 'issues_management', 'issues_archive',
'projects_manage', 'daily_work', 'reports', 'users_manage'
];
const permissions = {};
allPages.forEach(pageName => {
const checkbox = document.getElementById(`perm_${pageName}`);
if (checkbox) {
permissions[pageName] = checkbox.checked;
}
});
// 실제 API 호출로 권한 저장
const permissionArray = Object.entries(permissions).map(([pageName, canAccess]) => ({
page_name: pageName,
can_access: canAccess
}));
const response = await fetch('/api/page-permissions/bulk-grant', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('access_token')}`
},
body: JSON.stringify({
user_id: parseInt(selectedUserId),
permissions: permissionArray
})
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.detail || '권한 저장에 실패했습니다.');
}
const result = await response.json();
console.log('권한 저장 완료:', result);
statusSpan.textContent = '✅ 권한이 저장되었습니다.';
statusSpan.className = 'ml-3 text-sm text-green-600';
setTimeout(() => {
statusSpan.textContent = '';
}, 3000);
} catch (error) {
console.error('권한 저장 실패:', error);
statusSpan.textContent = '❌ 권한 저장에 실패했습니다.';
statusSpan.className = 'ml-3 text-sm text-red-600';
} finally {
saveBtn.disabled = false;
saveBtn.innerHTML = '<i class="fas fa-save mr-2"></i>권한 저장';
}
});
// API 스크립트 동적 로딩
const cacheBuster = Date.now() + Math.random() + Math.floor(Math.random() * 1000000);
const script = document.createElement('script');
script.src = `/static/js/api.js?v=20251025-2&cb=${cacheBuster}&t=${Date.now()}&r=${Math.random()}`;
script.setAttribute('cache-control', 'no-cache');
script.setAttribute('pragma', 'no-cache');
script.onload = function() {
console.log('✅ API 스크립트 로드 완료 (admin.html)');
// API 로드 후 초기화 시작
initializeAdmin();
};
script.onerror = function() {
console.error('❌ API 스크립트 로드 실패');
};
document.head.appendChild(script);
</script>
</body>
</html>