Files
document-server/frontend/static/js/book-documents.js
Hyungi Ahn b5602cbf44 Debug: 서적 수정 버튼 디버깅 로그 추가
- openBookEditor() 함수에 상세 디버깅 로그 추가
- URL 파라미터 파싱 과정 로그 추가
- bookId 값과 타입 확인 로그 추가
- 버튼 클릭 이벤트 확인을 위한 로그 추가
2025-09-03 18:03:03 +09:00

295 lines
10 KiB
JavaScript

// 서적 문서 목록 애플리케이션 컴포넌트
window.bookDocumentsApp = () => ({
// 상태 관리
documents: [],
availablePDFs: [],
bookInfo: {},
loading: false,
error: '',
// 인증 상태
isAuthenticated: false,
currentUser: null,
// URL 파라미터
bookId: null,
// 초기화
async init() {
console.log('🚀 Book Documents App 초기화 시작');
// URL 파라미터 파싱
this.parseUrlParams();
// 인증 상태 확인
await this.checkAuthStatus();
if (this.isAuthenticated) {
await this.loadBookDocuments();
}
// 헤더 로드
await this.loadHeader();
},
// URL 파라미터 파싱
parseUrlParams() {
const urlParams = new URLSearchParams(window.location.search);
this.bookId = urlParams.get('book_id') || urlParams.get('bookId'); // 둘 다 지원
console.log('📖 서적 ID:', this.bookId);
console.log('🔍 전체 URL 파라미터:', window.location.search);
console.log('🔍 URLSearchParams 객체:', urlParams);
console.log('🔍 book_id 파라미터:', urlParams.get('book_id'));
console.log('🔍 bookId 파라미터:', urlParams.get('bookId'));
},
// 인증 상태 확인
async checkAuthStatus() {
try {
const user = await window.api.getCurrentUser();
this.isAuthenticated = true;
this.currentUser = user;
console.log('✅ 인증됨:', user.username);
} catch (error) {
console.log('❌ 인증되지 않음');
this.isAuthenticated = false;
this.currentUser = null;
// 로그인 페이지로 리다이렉트하거나 로그인 모달 표시
window.location.href = '/login.html';
}
},
// 헤더 로드
async loadHeader() {
try {
await window.headerLoader.loadHeader();
} catch (error) {
console.error('헤더 로드 실패:', error);
}
},
// 서적 문서 목록 로드
async loadBookDocuments() {
this.loading = true;
this.error = '';
try {
// 모든 문서 가져오기
const allDocuments = await window.api.getDocuments();
if (this.bookId === 'none') {
// 서적 미분류 HTML 문서들만 (폴더로 구분)
this.documents = allDocuments.filter(doc =>
!doc.book_id &&
doc.html_path &&
doc.html_path.includes('/documents/') // HTML은 documents 폴더에 저장됨
);
// 서적 미분류 PDF 문서들 (매칭용)
this.availablePDFs = allDocuments.filter(doc =>
!doc.book_id &&
doc.pdf_path &&
doc.pdf_path.includes('/pdfs/') // PDF는 pdfs 폴더에 저장됨
);
this.bookInfo = {
title: '서적 미분류',
description: '서적에 속하지 않은 문서들입니다.'
};
} else {
// 특정 서적의 HTML 문서들만 (폴더로 구분)
this.documents = allDocuments.filter(doc =>
doc.book_id === this.bookId &&
doc.html_path &&
doc.html_path.includes('/documents/') // HTML은 documents 폴더에 저장됨
);
// 특정 서적의 PDF 문서들 (매칭용)
this.availablePDFs = allDocuments.filter(doc =>
doc.book_id === this.bookId &&
doc.pdf_path &&
doc.pdf_path.includes('/pdfs/') // PDF는 pdfs 폴더에 저장됨
);
if (this.documents.length > 0) {
// 첫 번째 문서에서 서적 정보 추출
const firstDoc = this.documents[0];
this.bookInfo = {
id: firstDoc.book_id,
title: firstDoc.book_title,
author: firstDoc.book_author,
description: firstDoc.book_description || '서적 설명이 없습니다.'
};
} else {
// 서적 정보만 가져오기 (문서가 없는 경우)
try {
this.bookInfo = await window.api.getBook(this.bookId);
} catch (error) {
console.error('서적 정보 로드 실패:', error);
this.bookInfo = {
title: '알 수 없는 서적',
description: '서적 정보를 불러올 수 없습니다.'
};
}
}
}
console.log('📚 서적 문서 로드 완료:', this.documents.length, '개');
console.log('📕 사용 가능한 PDF:', this.availablePDFs.length, '개');
console.log('📎 PDF 목록:', this.availablePDFs.map(pdf => ({ title: pdf.title, book_id: pdf.book_id })));
console.log('🔍 현재 서적 ID:', this.bookId);
// 디버깅: 문서들의 original_filename 확인
console.log('🔍 문서들 확인:');
this.documents.slice(0, 5).forEach(doc => {
console.log(`- ${doc.title}: ${doc.original_filename}`);
});
console.log('🔍 PDF들 확인:');
this.availablePDFs.slice(0, 5).forEach(doc => {
console.log(`- ${doc.title}: ${doc.original_filename}`);
});
} catch (error) {
console.error('서적 문서 로드 실패:', error);
this.error = '문서를 불러오는데 실패했습니다: ' + error.message;
this.documents = [];
} finally {
this.loading = false;
}
},
// 문서 열기
openDocument(documentId) {
// 현재 페이지 정보를 세션 스토리지에 저장
sessionStorage.setItem('previousPage', 'book-documents.html');
// 뷰어로 이동 - 같은 창에서 이동
window.location.href = `/viewer.html?id=${documentId}&from=book`;
},
// 서적 편집 페이지 열기
openBookEditor() {
console.log('🔧 서적 편집 버튼 클릭됨');
console.log('📖 현재 bookId:', this.bookId);
console.log('🔍 bookId 타입:', typeof this.bookId);
if (this.bookId === 'none') {
alert('서적 미분류 문서들은 편집할 수 없습니다.');
return;
}
if (!this.bookId) {
alert('서적 ID가 없습니다. 페이지를 새로고침해주세요.');
return;
}
const targetUrl = `book-editor.html?bookId=${this.bookId}`;
console.log('🔗 이동할 URL:', targetUrl);
window.location.href = targetUrl;
},
// 문서 수정
editDocument(doc) {
// TODO: 문서 수정 모달 또는 페이지로 이동
console.log('문서 수정:', doc.title);
alert('문서 수정 기능은 준비 중입니다.');
},
// 문서 삭제
async deleteDocument(documentId) {
if (!confirm('이 문서를 삭제하시겠습니까?')) {
return;
}
try {
await window.api.deleteDocument(documentId);
await this.loadBookDocuments(); // 목록 새로고침
this.showNotification('문서가 삭제되었습니다', 'success');
} catch (error) {
console.error('문서 삭제 실패:', error);
this.showNotification('문서 삭제에 실패했습니다: ' + error.message, 'error');
}
},
// 뒤로가기
goBack() {
window.location.href = 'index.html';
},
// 날짜 포맷팅
formatDate(dateString) {
if (!dateString) return '';
const date = new Date(dateString);
return date.toLocaleDateString('ko-KR', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
},
// 알림 표시
showNotification(message, type = 'info') {
// TODO: 알림 시스템 구현
console.log(`${type.toUpperCase()}: ${message}`);
if (type === 'error') {
alert(message);
}
},
// PDF를 서적에 연결
async matchPDFToBook(pdfId) {
if (!this.bookId) {
this.showNotification('서적 ID가 없습니다', 'error');
return;
}
if (!confirm('이 PDF를 현재 서적에 연결하시겠습니까?')) {
return;
}
try {
console.log('🔗 PDF 매칭 시작:', { pdfId, bookId: this.bookId });
// PDF 문서를 서적에 연결
await window.api.updateDocument(pdfId, {
book_id: this.bookId
});
this.showNotification('PDF가 서적에 성공적으로 연결되었습니다');
// 데이터 새로고침
await this.loadBookData();
} catch (error) {
console.error('PDF 매칭 실패:', error);
this.showNotification('PDF 연결에 실패했습니다: ' + error.message, 'error');
}
},
// PDF 열기
openPDF(pdf) {
if (pdf.pdf_path) {
// PDF 뷰어로 이동
window.open(`/viewer.html?id=${pdf.id}`, '_blank');
} else {
this.showNotification('PDF 파일을 찾을 수 없습니다', 'error');
}
},
// 날짜 포맷팅
formatDate(dateString) {
if (!dateString) return '';
const date = new Date(dateString);
return date.toLocaleDateString('ko-KR', {
year: 'numeric',
month: 'short',
day: 'numeric'
});
}
});
// 페이지 로드 시 초기화
document.addEventListener('DOMContentLoaded', () => {
console.log('📄 Book Documents 페이지 로드됨');
});