diff --git a/src/app/admin/courses/CourseRegistrationModal.tsx b/src/app/admin/courses/CourseRegistrationModal.tsx
index 2ba2dde..46c8416 100644
--- a/src/app/admin/courses/CourseRegistrationModal.tsx
+++ b/src/app/admin/courses/CourseRegistrationModal.tsx
@@ -411,7 +411,8 @@ export default function CourseRegistrationModal({ open, onClose, onSave, onDelet
};
// 삭제 버튼 클릭 핸들러
- const handleDeleteClick = () => {
+ const handleDeleteClick = (e: React.MouseEvent) => {
+ e.stopPropagation();
setIsDeleteConfirmOpen(true);
};
@@ -559,24 +560,27 @@ export default function CourseRegistrationModal({ open, onClose, onSave, onDelet
});
};
- if (!open) return null;
+ if (!open && !isDeleteConfirmOpen) return null;
return (
-
-
-
-
+ <>
+ {/* 메인 모달 */}
+ {open && (
+
+
+
+
{/* Header */}
@@ -837,7 +841,9 @@ export default function CourseRegistrationModal({ open, onClose, onSave, onDelet
-
+
+
+ )}
{/* 삭제 확인 모달 */}
{isDeleteConfirmOpen && (
@@ -847,41 +853,48 @@ export default function CourseRegistrationModal({ open, onClose, onSave, onDelet
onClick={handleDeleteCancel}
aria-hidden="true"
/>
-
+
-
- 교육과정을 삭제하시겠습니까?
-
-
- 삭제된 교육과정은 복구할 수 없습니다.
-
- 정말 삭제하시겠습니까?
-
+
+
+
+
삭제 버튼을 누르면 강좌 정보가 삭제됩니다.
+
정말 삭제하시겠습니까?
+
+
{errors.submit && (
{errors.submit}
)}
-
+
)}
-
+ >
);
}
diff --git a/src/app/admin/lessons/[id]/edit/page.tsx b/src/app/admin/lessons/[id]/edit/page.tsx
index 479d726..73b27b2 100644
--- a/src/app/admin/lessons/[id]/edit/page.tsx
+++ b/src/app/admin/lessons/[id]/edit/page.tsx
@@ -26,13 +26,16 @@ export default function LessonEditPage() {
const [courseVideoCount, setCourseVideoCount] = useState(0);
const [courseVideoFiles, setCourseVideoFiles] = useState
([]);
const [courseVideoFileObjects, setCourseVideoFileObjects] = useState([]);
+ const [courseVideoFileKeys, setCourseVideoFileKeys] = useState([]);
const [existingVideoFiles, setExistingVideoFiles] = useState>([]);
const [vrContentCount, setVrContentCount] = useState(0);
const [vrContentFiles, setVrContentFiles] = useState([]);
const [vrContentFileObjects, setVrContentFileObjects] = useState([]);
+ const [vrContentFileKeys, setVrContentFileKeys] = useState([]);
const [existingVrFiles, setExistingVrFiles] = useState>([]);
const [questionFileCount, setQuestionFileCount] = useState(0);
const [questionFileObject, setQuestionFileObject] = useState(null);
+ const [questionFileKey, setQuestionFileKey] = useState(null);
const [existingQuestionFile, setExistingQuestionFile] = useState<{fileName: string, fileKey?: string} | null>(null);
// 원본 데이터 저장 (변경사항 비교용)
@@ -271,61 +274,41 @@ export default function LessonEditPage() {
return;
}
- // 새로 업로드된 파일들 처리
+ // 이미 업로드된 fileKey 배열 사용
let videoUrl: string | undefined;
let webglUrl: string | undefined;
let csvUrl: string | undefined;
- // 강좌 영상 업로드 (새 파일이 있는 경우)
- if (courseVideoFileObjects.length > 0) {
- try {
- const uploadResponse = await apiService.uploadFiles(courseVideoFileObjects);
- // 다중 파일 업로드 응답 처리 (실제 API 응답 구조에 맞게 조정 필요)
- if (uploadResponse.data && uploadResponse.data.length > 0) {
- videoUrl = uploadResponse.data[0].url || uploadResponse.data[0].fileKey;
- }
- } catch (error) {
- console.error('강좌 영상 업로드 실패:', error);
- throw new Error('강좌 영상 업로드에 실패했습니다.');
- }
+ // 강좌 영상 fileKey (새로 업로드된 파일이 있는 경우)
+ if (courseVideoFileKeys.length > 0) {
+ videoUrl = courseVideoFileKeys[0]; // 첫 번째 fileKey 사용
+ // TODO: API가 배열을 받는 경우 courseVideoFileKeys 배열 전체를 저장해야 함
} else if (existingVideoFiles.length > 0 && existingVideoFiles[0].url) {
// 기존 파일 URL 유지
videoUrl = existingVideoFiles[0].url;
+ } else if (existingVideoFiles.length > 0 && existingVideoFiles[0].fileKey) {
+ // 기존 파일 fileKey 사용
+ videoUrl = existingVideoFiles[0].fileKey;
}
- // VR 콘텐츠 업로드 (새 파일이 있는 경우)
- if (vrContentFileObjects.length > 0) {
- try {
- const uploadResponse = await apiService.uploadFiles(vrContentFileObjects);
- if (uploadResponse.data && uploadResponse.data.length > 0) {
- webglUrl = uploadResponse.data[0].url || uploadResponse.data[0].fileKey;
- }
- } catch (error) {
- console.error('VR 콘텐츠 업로드 실패:', error);
- throw new Error('VR 콘텐츠 업로드에 실패했습니다.');
- }
+ // VR 콘텐츠 fileKey (새로 업로드된 파일이 있는 경우)
+ if (vrContentFileKeys.length > 0) {
+ webglUrl = vrContentFileKeys[0]; // 첫 번째 fileKey 사용
+ // TODO: API가 배열을 받는 경우 vrContentFileKeys 배열 전체를 저장해야 함
} else if (existingVrFiles.length > 0 && existingVrFiles[0].url) {
// 기존 파일 URL 유지
webglUrl = existingVrFiles[0].url;
+ } else if (existingVrFiles.length > 0 && existingVrFiles[0].fileKey) {
+ // 기존 파일 fileKey 사용
+ webglUrl = existingVrFiles[0].fileKey;
}
- // 학습 평가 문제 업로드 (새 파일이 있는 경우)
- if (questionFileObject) {
- try {
- const uploadResponse = await apiService.uploadFile(questionFileObject);
- const fileKey = uploadResponse.data?.key || uploadResponse.data?.fileKey || uploadResponse.data?.csvKey;
- if (fileKey) {
- csvUrl = `csv/${fileKey}`;
- } else if (uploadResponse.data?.url) {
- csvUrl = uploadResponse.data.url;
- }
- } catch (error) {
- console.error('학습 평가 문제 업로드 실패:', error);
- throw new Error('학습 평가 문제 업로드에 실패했습니다.');
- }
+ // 학습 평가 문제 fileKey (새로 업로드된 파일이 있는 경우)
+ if (questionFileKey) {
+ csvUrl = questionFileKey;
} else if (existingQuestionFile?.fileKey) {
- // 기존 파일 URL 유지
- csvUrl = `csv/${existingQuestionFile.fileKey}`;
+ // 기존 파일 fileKey 사용
+ csvUrl = existingQuestionFile.fileKey;
} else if (originalData.csvUrl) {
// 원본 데이터의 csvUrl 유지
csvUrl = originalData.csvUrl;
@@ -634,36 +617,74 @@ export default function LessonEditPage() {
if (!files) return;
const MAX_SIZE = 30 * 1024 * 1024; // 30MB
+ const MAX_COUNT = 10; // 최대 10개
const validFiles: File[] = [];
const oversizedFiles: string[] = [];
+ const invalidTypeFiles: string[] = [];
Array.from(files).forEach((file) => {
+ // mp4 파일인지 확인
if (!file.name.toLowerCase().endsWith('.mp4')) {
+ invalidTypeFiles.push(file.name);
return;
}
- if (file.size < MAX_SIZE) {
+ // 각 파일이 30MB 이하인지 검사
+ if (file.size <= MAX_SIZE) {
validFiles.push(file);
} else {
oversizedFiles.push(file.name);
}
});
- if (oversizedFiles.length > 0) {
- alert(`다음 파일은 30MB 미만이어야 합니다:\n${oversizedFiles.join('\n')}`);
+ // 파일 타입 오류
+ if (invalidTypeFiles.length > 0) {
+ alert(`다음 파일은 MP4 형식만 가능합니다:\n${invalidTypeFiles.join('\n')}`);
}
- if (existingVideoFiles.length + courseVideoFiles.length + validFiles.length > 10) {
- alert('강좌 영상은 최대 10개까지 첨부할 수 있습니다.');
+ // 30MB 초과 파일이 있으면 알림
+ if (oversizedFiles.length > 0) {
+ alert(`다음 파일은 30MB 이하여야 합니다:\n${oversizedFiles.join('\n')}`);
+ }
+
+ // 파일 개수 제한 확인
+ const totalCount = existingVideoFiles.length + courseVideoFiles.length + validFiles.length;
+ if (totalCount > MAX_COUNT) {
+ const currentCount = existingVideoFiles.length + courseVideoFiles.length;
+ const availableCount = MAX_COUNT - currentCount;
+ alert(`강좌 영상은 최대 ${MAX_COUNT}개까지 첨부할 수 있습니다. (현재 ${currentCount}개, 추가 가능 ${availableCount > 0 ? availableCount : 0}개)`);
+ e.target.value = '';
+ return;
+ }
+
+ // 30MB 초과 파일이나 잘못된 타입 파일만 있는 경우 중단
+ if (validFiles.length === 0 && (oversizedFiles.length > 0 || invalidTypeFiles.length > 0)) {
e.target.value = '';
return;
}
if (validFiles.length > 0) {
try {
- await apiService.uploadFiles(validFiles);
- setCourseVideoFiles(prev => [...prev, ...validFiles.map(f => f.name)]);
- setCourseVideoFileObjects(prev => [...prev, ...validFiles]);
- setCourseVideoCount(prev => prev + validFiles.length);
+ // 다중 파일 업로드
+ const uploadResponse = await apiService.uploadFiles(validFiles);
+
+ // 응답에서 fileKey 배열 추출
+ const fileKeys: string[] = [];
+ if (uploadResponse.data?.results && Array.isArray(uploadResponse.data.results)) {
+ uploadResponse.data.results.forEach((result: any) => {
+ if (result.ok && result.fileKey) {
+ fileKeys.push(result.fileKey);
+ }
+ });
+ }
+
+ if (fileKeys.length > 0) {
+ setCourseVideoFiles(prev => [...prev, ...validFiles.map(f => f.name)]);
+ setCourseVideoFileObjects(prev => [...prev, ...validFiles]);
+ setCourseVideoFileKeys(prev => [...prev, ...fileKeys]);
+ setCourseVideoCount(prev => prev + validFiles.length);
+ } else {
+ throw new Error('파일 업로드는 완료되었지만 fileKey를 받지 못했습니다.');
+ }
} catch (error) {
console.error('강좌 영상 업로드 실패:', error);
alert('파일 업로드에 실패했습니다. 다시 시도해주세요.');
@@ -717,6 +738,7 @@ export default function LessonEditPage() {
onClick={() => {
setCourseVideoFiles(prev => prev.filter((_, i) => i !== index));
setCourseVideoFileObjects(prev => prev.filter((_, i) => i !== index));
+ setCourseVideoFileKeys(prev => prev.filter((_, i) => i !== index));
setCourseVideoCount(prev => prev - 1);
}}
className="size-[16px] flex items-center justify-center cursor-pointer hover:opacity-70 transition-opacity shrink-0"
@@ -754,36 +776,74 @@ export default function LessonEditPage() {
if (!files) return;
const MAX_SIZE = 30 * 1024 * 1024; // 30MB
+ const MAX_COUNT = 10; // 최대 10개
const validFiles: File[] = [];
const oversizedFiles: string[] = [];
+ const invalidTypeFiles: string[] = [];
Array.from(files).forEach((file) => {
+ // zip 파일인지 확인
if (!file.name.toLowerCase().endsWith('.zip')) {
+ invalidTypeFiles.push(file.name);
return;
}
- if (file.size < MAX_SIZE) {
+ // 각 파일이 30MB 이하인지 검사
+ if (file.size <= MAX_SIZE) {
validFiles.push(file);
} else {
oversizedFiles.push(file.name);
}
});
- if (oversizedFiles.length > 0) {
- alert(`다음 파일은 30MB 미만이어야 합니다:\n${oversizedFiles.join('\n')}`);
+ // 파일 타입 오류
+ if (invalidTypeFiles.length > 0) {
+ alert(`다음 파일은 ZIP 형식만 가능합니다:\n${invalidTypeFiles.join('\n')}`);
}
- if (existingVrFiles.length + vrContentFiles.length + validFiles.length > 10) {
- alert('VR 콘텐츠는 최대 10개까지 첨부할 수 있습니다.');
+ // 30MB 초과 파일이 있으면 알림
+ if (oversizedFiles.length > 0) {
+ alert(`다음 파일은 30MB 이하여야 합니다:\n${oversizedFiles.join('\n')}`);
+ }
+
+ // 파일 개수 제한 확인
+ const totalCount = existingVrFiles.length + vrContentFiles.length + validFiles.length;
+ if (totalCount > MAX_COUNT) {
+ const currentCount = existingVrFiles.length + vrContentFiles.length;
+ const availableCount = MAX_COUNT - currentCount;
+ alert(`VR 콘텐츠는 최대 ${MAX_COUNT}개까지 첨부할 수 있습니다. (현재 ${currentCount}개, 추가 가능 ${availableCount > 0 ? availableCount : 0}개)`);
+ e.target.value = '';
+ return;
+ }
+
+ // 30MB 초과 파일이나 잘못된 타입 파일만 있는 경우 중단
+ if (validFiles.length === 0 && (oversizedFiles.length > 0 || invalidTypeFiles.length > 0)) {
e.target.value = '';
return;
}
if (validFiles.length > 0) {
try {
- await apiService.uploadFiles(validFiles);
- setVrContentFiles(prev => [...prev, ...validFiles.map(f => f.name)]);
- setVrContentFileObjects(prev => [...prev, ...validFiles]);
- setVrContentCount(prev => prev + validFiles.length);
+ // 다중 파일 업로드
+ const uploadResponse = await apiService.uploadFiles(validFiles);
+
+ // 응답에서 fileKey 배열 추출
+ const fileKeys: string[] = [];
+ if (uploadResponse.data?.results && Array.isArray(uploadResponse.data.results)) {
+ uploadResponse.data.results.forEach((result: any) => {
+ if (result.ok && result.fileKey) {
+ fileKeys.push(result.fileKey);
+ }
+ });
+ }
+
+ if (fileKeys.length > 0) {
+ setVrContentFiles(prev => [...prev, ...validFiles.map(f => f.name)]);
+ setVrContentFileObjects(prev => [...prev, ...validFiles]);
+ setVrContentFileKeys(prev => [...prev, ...fileKeys]);
+ setVrContentCount(prev => prev + validFiles.length);
+ } else {
+ throw new Error('파일 업로드는 완료되었지만 fileKey를 받지 못했습니다.');
+ }
} catch (error) {
console.error('VR 콘텐츠 업로드 실패:', error);
alert('파일 업로드에 실패했습니다. 다시 시도해주세요.');
@@ -837,6 +897,7 @@ export default function LessonEditPage() {
onClick={() => {
setVrContentFiles(prev => prev.filter((_, i) => i !== index));
setVrContentFileObjects(prev => prev.filter((_, i) => i !== index));
+ setVrContentFileKeys(prev => prev.filter((_, i) => i !== index));
setVrContentCount(prev => prev - 1);
}}
className="size-[16px] flex items-center justify-center cursor-pointer hover:opacity-70 transition-opacity shrink-0"
@@ -876,10 +937,30 @@ export default function LessonEditPage() {
const file = files[0];
if (file.name.toLowerCase().endsWith('.csv')) {
try {
- await apiService.uploadFile(file);
- setQuestionFileObject(file);
- setQuestionFileCount(1);
- setExistingQuestionFile(null);
+ // 단일 파일 업로드
+ const uploadResponse = await apiService.uploadFile(file);
+
+ // 응답에서 fileKey 추출
+ let fileKey: string | null = null;
+ if (uploadResponse.data?.fileKey) {
+ fileKey = uploadResponse.data.fileKey;
+ } else if (uploadResponse.data?.key) {
+ fileKey = uploadResponse.data.key;
+ } else if (uploadResponse.data?.results && Array.isArray(uploadResponse.data.results) && uploadResponse.data.results.length > 0) {
+ const result = uploadResponse.data.results[0];
+ if (result.ok && result.fileKey) {
+ fileKey = result.fileKey;
+ }
+ }
+
+ if (fileKey) {
+ setQuestionFileObject(file);
+ setQuestionFileKey(fileKey);
+ setQuestionFileCount(1);
+ setExistingQuestionFile(null);
+ } else {
+ throw new Error('파일 업로드는 완료되었지만 fileKey를 받지 못했습니다.');
+ }
} catch (error) {
console.error('학습 평가 문제 업로드 실패:', error);
alert('파일 업로드에 실패했습니다. 다시 시도해주세요.');
@@ -900,6 +981,7 @@ export default function LessonEditPage() {
type="button"
onClick={() => {
setQuestionFileObject(null);
+ setQuestionFileKey(null);
setExistingQuestionFile(null);
setQuestionFileCount(0);
}}
diff --git a/src/app/admin/lessons/[id]/page.tsx b/src/app/admin/lessons/[id]/page.tsx
index 1e2d008..6273581 100644
--- a/src/app/admin/lessons/[id]/page.tsx
+++ b/src/app/admin/lessons/[id]/page.tsx
@@ -6,6 +6,7 @@ import AdminSidebar from '@/app/components/AdminSidebar';
import BackArrowSvg from '@/app/svgs/backarrow';
import DownloadIcon from '@/app/svgs/downloadicon';
import apiService from '@/app/lib/apiService';
+import { getCourses } from '@/app/admin/courses/mockData';
type VideoFile = {
id: string;
@@ -49,6 +50,9 @@ export default function AdminCourseDetailPage() {
const [course, setCourse] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
+ const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
+ const [isDeleting, setIsDeleting] = useState(false);
+ const [showToast, setShowToast] = useState(false);
useEffect(() => {
const fetchCourse = async () => {
@@ -90,20 +94,8 @@ export default function AdminCourseDetailPage() {
throw new Error('강좌를 찾을 수 없습니다.');
}
- // 첨부파일 정보 구성
- const attachmentParts: string[] = [];
- if (data.videoUrl) {
- attachmentParts.push('강좌영상 1개');
- }
- if (data.webglUrl) {
- attachmentParts.push('VR콘텐츠 1개');
- }
- if (data.csvKey) {
- attachmentParts.push('평가문제 1개');
- }
- const attachments = attachmentParts.length > 0
- ? attachmentParts.join(', ')
- : '없음';
+ // 첨부파일 정보 구성 (나중에 videoFiles와 vrFiles 길이로 업데이트됨)
+ // 이 부분은 videoFiles와 vrFiles가 구성된 후에 업데이트됩니다
// 썸네일 이미지 가져오기
let thumbnail = '/imgs/talk.png';
@@ -118,53 +110,178 @@ export default function AdminCourseDetailPage() {
}
}
- // 교육 과정명 가져오기
+ // 교육 과정명 가져오기 - AdminLessonsPage와 동일한 방식
let courseName = '';
- if (data.subjectId || data.subject_id) {
+ const subjectId = data.subjectId || data.subject_id;
+ if (subjectId) {
try {
- const subjectsResponse = await apiService.getSubjects();
- const subjects = Array.isArray(subjectsResponse.data)
- ? subjectsResponse.data
- : subjectsResponse.data?.items || subjectsResponse.data?.subjects || [];
- const subject = subjects.find((s: any) =>
- String(s.id || s.subjectId) === String(data.subjectId || data.subject_id)
- );
- courseName = subject?.courseName || subject?.name || subject?.subjectName || '';
+ const courses = await getCourses();
+ const foundCourse = courses.find(course => course.id === String(subjectId));
+ courseName = foundCourse?.courseName || '';
+
+ // 교육과정명을 찾지 못한 경우 fallback
+ if (!courseName) {
+ courseName = data.subjectName || data.courseName || '';
+ }
} catch (err) {
console.error('교육 과정명 조회 실패:', err);
+ // 에러 발생 시 fallback
+ courseName = data.subjectName || data.courseName || '';
}
}
// 학습 목표를 여러 줄로 분리
const goalLines = (data.objective || data.goal || '').split('\n').filter((line: string) => line.trim());
- // 비디오 파일 목록 구성
+ // 비디오 파일 목록 구성 - fileKey 배열에서 파일 조회
const videoFiles: VideoFile[] = [];
- if (data.videoUrl) {
- videoFiles.push({
- id: '1',
- fileName: data.videoFileName || '강좌영상.mp4',
- fileSize: '796.35 KB',
- fileKey: data.videoKey,
- url: data.videoUrl,
+
+ // fileKey 배열 수집
+ const videoFileKeys: string[] = [];
+
+ // videoUrl이 배열인 경우 처리
+ if (data.videoUrl && Array.isArray(data.videoUrl)) {
+ // videoUrl 배열의 각 항목을 fileKey로 사용
+ videoFileKeys.push(...data.videoUrl);
+ } else if (data.videoKeys && Array.isArray(data.videoKeys)) {
+ videoFileKeys.push(...data.videoKeys);
+ } else if (data.videoFileKeys && Array.isArray(data.videoFileKeys)) {
+ videoFileKeys.push(...data.videoFileKeys);
+ } else if (data.videoFiles && Array.isArray(data.videoFiles)) {
+ // videoFiles 배열에서 fileKey 추출
+ data.videoFiles.forEach((vf: any) => {
+ if (vf.fileKey || vf.key) {
+ videoFileKeys.push(vf.fileKey || vf.key);
+ }
});
+ } else if (data.videoKey) {
+ // 단일 fileKey
+ videoFileKeys.push(data.videoKey);
+ } else if (data.videoUrl && typeof data.videoUrl === 'string') {
+ // 단일 videoUrl을 fileKey로 사용 (하위 호환성)
+ videoFileKeys.push(data.videoUrl);
}
- // 여러 비디오 파일이 있는 경우 처리
- if (data.videoFiles && Array.isArray(data.videoFiles)) {
- data.videoFiles.forEach((vf: any, index: number) => {
- videoFiles.push({
- id: String(index + 1),
- fileName: vf.fileName || vf.name || `강좌영상_${index + 1}.mp4`,
- fileSize: vf.fileSize || '796.35 KB',
- fileKey: vf.fileKey || vf.key,
- url: vf.url || vf.videoUrl,
- });
+
+ // fileKey 배열이 있으면 각각에 대해 파일 조회 API 호출
+ if (videoFileKeys.length > 0) {
+ const videoFilePromises = videoFileKeys.map(async (fileKey, index) => {
+ try {
+ const fileUrl = await apiService.getFile(fileKey);
+ return {
+ id: String(index + 1),
+ fileName: data.videoFiles?.[index]?.fileName || data.videoFiles?.[index]?.name || `강좌영상_${index + 1}.mp4`,
+ fileSize: data.videoFiles?.[index]?.fileSize || '796.35 KB',
+ fileKey: fileKey,
+ url: fileUrl || undefined,
+ };
+ } catch (err) {
+ console.error(`비디오 파일 ${index + 1} 조회 실패:`, err);
+ // 조회 실패해도 fileKey는 저장
+ return {
+ id: String(index + 1),
+ fileName: data.videoFiles?.[index]?.fileName || data.videoFiles?.[index]?.name || `강좌영상_${index + 1}.mp4`,
+ fileSize: data.videoFiles?.[index]?.fileSize || '796.35 KB',
+ fileKey: fileKey,
+ url: undefined,
+ };
+ }
});
+
+ const resolvedVideoFiles = await Promise.all(videoFilePromises);
+ videoFiles.push(...resolvedVideoFiles);
+ } else {
+ // fileKey 배열이 없으면 기존 방식대로 처리
+ if (data.videoUrl) {
+ videoFiles.push({
+ id: '1',
+ fileName: data.videoFileName || '강좌영상.mp4',
+ fileSize: '796.35 KB',
+ fileKey: data.videoKey,
+ url: data.videoUrl,
+ });
+ }
+ // 여러 비디오 파일이 있는 경우 처리 (기존 로직 유지)
+ if (data.videoFiles && Array.isArray(data.videoFiles)) {
+ data.videoFiles.forEach((vf: any, index: number) => {
+ videoFiles.push({
+ id: String(index + 1),
+ fileName: vf.fileName || vf.name || `강좌영상_${index + 1}.mp4`,
+ fileSize: vf.fileSize || '796.35 KB',
+ fileKey: vf.fileKey || vf.key,
+ url: vf.url || vf.videoUrl,
+ });
+ });
+ }
}
- // VR 파일 목록 구성
+ // VR 파일 목록 구성 - fileKey 배열에서 파일 조회
const vrFiles: VrFile[] = [];
- if (data.webglUrl || data.vrUrl) {
+
+ // fileKey 배열 수집
+ const vrFileKeys: string[] = [];
+
+ // webglUrl이 배열인 경우 처리
+ if (data.webglUrl && Array.isArray(data.webglUrl)) {
+ // webglUrl 배열의 각 항목을 fileKey로 사용
+ vrFileKeys.push(...data.webglUrl);
+ } else if (data.vrUrl && Array.isArray(data.vrUrl)) {
+ // vrUrl 배열의 각 항목을 fileKey로 사용
+ vrFileKeys.push(...data.vrUrl);
+ } else if (data.webglKeys && Array.isArray(data.webglKeys)) {
+ vrFileKeys.push(...data.webglKeys);
+ } else if (data.vrKeys && Array.isArray(data.vrKeys)) {
+ vrFileKeys.push(...data.vrKeys);
+ } else if (data.webglFileKeys && Array.isArray(data.webglFileKeys)) {
+ vrFileKeys.push(...data.webglFileKeys);
+ } else if (data.vrFileKeys && Array.isArray(data.vrFileKeys)) {
+ vrFileKeys.push(...data.vrFileKeys);
+ } else if (data.webglFiles && Array.isArray(data.webglFiles)) {
+ // webglFiles 배열에서 fileKey 추출
+ data.webglFiles.forEach((vf: any) => {
+ if (vf.fileKey || vf.key) {
+ vrFileKeys.push(vf.fileKey || vf.key);
+ }
+ });
+ } else if (data.webglKey || data.vrKey) {
+ // 단일 fileKey
+ vrFileKeys.push(data.webglKey || data.vrKey);
+ } else if (data.webglUrl && typeof data.webglUrl === 'string') {
+ // 단일 webglUrl을 fileKey로 사용 (하위 호환성)
+ vrFileKeys.push(data.webglUrl);
+ } else if (data.vrUrl && typeof data.vrUrl === 'string') {
+ // 단일 vrUrl을 fileKey로 사용 (하위 호환성)
+ vrFileKeys.push(data.vrUrl);
+ }
+
+ // fileKey 배열이 있으면 각각에 대해 파일 조회 API 호출
+ if (vrFileKeys.length > 0) {
+ const vrFilePromises = vrFileKeys.map(async (fileKey, index) => {
+ try {
+ const fileUrl = await apiService.getFile(fileKey);
+ return {
+ id: String(index + 1),
+ fileName: data.webglFiles?.[index]?.fileName || data.webglFiles?.[index]?.name || data.vrFileName || data.webglFileName || `VR_콘텐츠_${index + 1}.zip`,
+ fileSize: data.webglFiles?.[index]?.fileSize || '796.35 KB',
+ fileKey: fileKey,
+ url: fileUrl || undefined,
+ };
+ } catch (err) {
+ console.error(`VR 파일 ${index + 1} 조회 실패:`, err);
+ // 조회 실패해도 fileKey는 저장
+ return {
+ id: String(index + 1),
+ fileName: data.webglFiles?.[index]?.fileName || data.webglFiles?.[index]?.name || data.vrFileName || data.webglFileName || `VR_콘텐츠_${index + 1}.zip`,
+ fileSize: data.webglFiles?.[index]?.fileSize || '796.35 KB',
+ fileKey: fileKey,
+ url: undefined,
+ };
+ }
+ });
+
+ const resolvedVrFiles = await Promise.all(vrFilePromises);
+ vrFiles.push(...resolvedVrFiles);
+ } else if (data.webglUrl || data.vrUrl) {
+ // fileKey 배열이 없고 webglUrl이 있으면 기존 방식대로 처리
vrFiles.push({
id: '1',
fileName: data.vrFileName || data.webglFileName || 'VR_콘텐츠.zip',
@@ -217,6 +334,16 @@ export default function AdminCourseDetailPage() {
fetchCourse();
}, [params?.id]);
+ // 토스트 자동 닫기
+ useEffect(() => {
+ if (showToast) {
+ const timer = setTimeout(() => {
+ setShowToast(false);
+ }, 3000);
+ return () => clearTimeout(timer);
+ }
+ }, [showToast]);
+
if (loading) {
return (
@@ -324,6 +451,38 @@ export default function AdminCourseDetailPage() {
}
};
+ const handleDeleteClick = () => {
+ setIsDeleteModalOpen(true);
+ };
+
+ const handleDeleteCancel = () => {
+ setIsDeleteModalOpen(false);
+ };
+
+ const handleDeleteConfirm = async () => {
+ if (!params?.id || isDeleting) return;
+
+ setIsDeleting(true);
+ try {
+ const response = await apiService.deleteLecture(params.id as string);
+ // 응답 메시지 확인
+ if (response.data?.message === '삭제 완료') {
+ // 토스트 팝업 표시
+ setShowToast(true);
+ // 강좌 목록으로 이동
+ router.push('/admin/lessons');
+ } else {
+ // 예상치 못한 응답
+ alert('강좌 삭제에 실패했습니다.');
+ setIsDeleting(false);
+ }
+ } catch (err) {
+ console.error('강좌 삭제 실패:', err);
+ alert('강좌 삭제에 실패했습니다.');
+ setIsDeleting(false);
+ }
+ };
+
const goalLines = course.goal.split('\n').filter(line => line.trim());
return (
@@ -582,7 +741,8 @@ export default function AdminCourseDetailPage() {
@@ -621,7 +781,71 @@ export default function AdminCourseDetailPage() {
-
+
+ {/* 삭제 확인 모달 */}
+ {isDeleteModalOpen && (
+
+
+
+
+
+
+
+
삭제 버튼을 누르면 강좌 정보가 삭제됩니다.
+
정말 삭제하시겠습니까?
+
+
+
+
+
+
+
+
+
+ )}
+
+ {/* 삭제 완료 토스트 */}
+ {showToast && (
+
+ )}
+
);
}
diff --git a/src/app/admin/lessons/page.tsx b/src/app/admin/lessons/page.tsx
index e7ce450..9a53108 100644
--- a/src/app/admin/lessons/page.tsx
+++ b/src/app/admin/lessons/page.tsx
@@ -39,11 +39,14 @@ export default function AdminLessonsPage() {
const [courseVideoCount, setCourseVideoCount] = useState(0);
const [courseVideoFiles, setCourseVideoFiles] = useState([]);
const [courseVideoFileObjects, setCourseVideoFileObjects] = useState([]);
+ const [courseVideoFileKeys, setCourseVideoFileKeys] = useState([]);
const [vrContentCount, setVrContentCount] = useState(0);
const [vrContentFiles, setVrContentFiles] = useState([]);
const [vrContentFileObjects, setVrContentFileObjects] = useState([]);
+ const [vrContentFileKeys, setVrContentFileKeys] = useState([]);
const [questionFileCount, setQuestionFileCount] = useState(0);
const [questionFileObject, setQuestionFileObject] = useState(null);
+ const [questionFileKey, setQuestionFileKey] = useState(null);
// 에러 상태
const [errors, setErrors] = useState<{
@@ -234,11 +237,14 @@ export default function AdminLessonsPage() {
setCourseVideoCount(0);
setCourseVideoFiles([]);
setCourseVideoFileObjects([]);
+ setCourseVideoFileKeys([]);
setVrContentCount(0);
setVrContentFiles([]);
setVrContentFileObjects([]);
+ setVrContentFileKeys([]);
setQuestionFileCount(0);
setQuestionFileObject(null);
+ setQuestionFileKey(null);
setErrors({});
};
@@ -274,72 +280,27 @@ export default function AdminLessonsPage() {
setErrors({});
try {
- // 파일 업로드 및 키 추출
- let videoUrl: string | undefined;
- let webglUrl: string | undefined;
+ // 이미 업로드된 fileKey 배열 사용
+ const videoFileKeys = courseVideoFileKeys;
+ const vrFileKeys = vrContentFileKeys;
+ const csvFileKey = questionFileKey;
+
+ // 강좌 영상 fileKey 배열 (모든 fileKey를 배열로 저장)
+ let videoUrl: string[] | undefined;
+ if (videoFileKeys.length > 0) {
+ videoUrl = videoFileKeys; // 모든 fileKey를 배열로 저장
+ }
+
+ // VR 콘텐츠 fileKey 배열 (모든 fileKey를 배열로 저장)
+ let webglUrl: string[] | undefined;
+ if (vrFileKeys.length > 0) {
+ webglUrl = vrFileKeys; // 모든 fileKey를 배열로 저장
+ }
+
+ // 학습 평가 문제 fileKey
let csvKey: string | undefined;
-
- // 강좌 영상 업로드 (첫 번째 파일만 사용)
- if (courseVideoFileObjects.length > 0) {
- try {
- const uploadResponse = await apiService.uploadFile(courseVideoFileObjects[0]);
- if (uploadResponse.data) {
- const fileKey = uploadResponse.data.key
- || uploadResponse.data.fileKey
- || uploadResponse.data.id
- || uploadResponse.data.imageKey
- || uploadResponse.data.fileId
- || (uploadResponse.data.data && (uploadResponse.data.data.key || uploadResponse.data.data.fileKey))
- || null;
- if (fileKey) {
- videoUrl = fileKey;
- }
- }
- } catch (error) {
- console.error('강좌 영상 업로드 실패:', error);
- }
- }
-
- // VR 콘텐츠 업로드 (첫 번째 파일만 사용)
- if (vrContentFileObjects.length > 0) {
- try {
- const uploadResponse = await apiService.uploadFile(vrContentFileObjects[0]);
- if (uploadResponse.data) {
- const fileKey = uploadResponse.data.key
- || uploadResponse.data.fileKey
- || uploadResponse.data.id
- || uploadResponse.data.imageKey
- || uploadResponse.data.fileId
- || (uploadResponse.data.data && (uploadResponse.data.data.key || uploadResponse.data.data.fileKey))
- || null;
- if (fileKey) {
- webglUrl = fileKey;
- }
- }
- } catch (error) {
- console.error('VR 콘텐츠 업로드 실패:', error);
- }
- }
-
- // 학습 평가 문제 업로드
- if (questionFileObject) {
- try {
- const uploadResponse = await apiService.uploadFile(questionFileObject);
- if (uploadResponse.data) {
- const fileKey = uploadResponse.data.key
- || uploadResponse.data.fileKey
- || uploadResponse.data.id
- || uploadResponse.data.imageKey
- || uploadResponse.data.fileId
- || (uploadResponse.data.data && (uploadResponse.data.data.key || uploadResponse.data.data.fileKey))
- || null;
- if (fileKey) {
- csvKey = fileKey;
- }
- }
- } catch (error) {
- console.error('학습 평가 문제 업로드 실패:', error);
- }
+ if (csvFileKey) {
+ csvKey = csvFileKey;
}
// API 요청 body 구성
@@ -347,8 +308,8 @@ export default function AdminLessonsPage() {
subjectId: number;
title: string;
objective: string;
- videoUrl?: string;
- webglUrl?: string;
+ videoUrl?: string | string[];
+ webglUrl?: string | string[];
csvKey?: string;
} = {
subjectId: Number(selectedCourse),
@@ -357,10 +318,10 @@ export default function AdminLessonsPage() {
};
// 선택적 필드 추가
- if (videoUrl) {
+ if (videoUrl && videoUrl.length > 0) {
requestBody.videoUrl = videoUrl;
}
- if (webglUrl) {
+ if (webglUrl && webglUrl.length > 0) {
requestBody.webglUrl = webglUrl;
}
if (csvKey) {
@@ -416,11 +377,14 @@ export default function AdminLessonsPage() {
setCourseVideoCount(0);
setCourseVideoFiles([]);
setCourseVideoFileObjects([]);
+ setCourseVideoFileKeys([]);
setVrContentCount(0);
setVrContentFiles([]);
setVrContentFileObjects([]);
+ setVrContentFileKeys([]);
setQuestionFileCount(0);
setQuestionFileObject(null);
+ setQuestionFileKey(null);
// 토스트 팝업 표시
setShowToast(true);
@@ -628,37 +592,56 @@ export default function AdminLessonsPage() {
{
const files = e.target.files;
if (!files) return;
const MAX_SIZE = 30 * 1024 * 1024; // 30MB
+ const MAX_COUNT = 10; // 최대 10개
const validFiles: File[] = [];
const oversizedFiles: string[] = [];
+ const invalidTypeFiles: string[] = [];
+
+ // 영상 파일 확장자 확인
+ const videoExtensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm', '.mkv'];
Array.from(files).forEach((file) => {
- // mp4 파일인지 확인
- if (!file.name.toLowerCase().endsWith('.mp4')) {
+ const fileExtension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'));
+ if (!videoExtensions.includes(fileExtension)) {
+ invalidTypeFiles.push(file.name);
return;
}
- // 각 파일이 30MB 미만인지 검사
- if (file.size < MAX_SIZE) {
+ // 각 파일이 30MB 이하인지 검사
+ if (file.size <= MAX_SIZE) {
validFiles.push(file);
} else {
oversizedFiles.push(file.name);
}
});
- // 30MB 이상인 파일이 있으면 알림
+ // 파일 타입 오류
+ if (invalidTypeFiles.length > 0) {
+ alert(`다음 파일은 영상 파일 형식만 가능합니다 (MP4, AVI, MOV, WMV, FLV, WEBM, MKV):\n${invalidTypeFiles.join('\n')}`);
+ }
+
+ // 30MB 초과 파일이 있으면 알림
if (oversizedFiles.length > 0) {
- alert(`다음 파일은 30MB 미만이어야 합니다:\n${oversizedFiles.join('\n')}`);
+ alert(`다음 파일은 30MB 이하여야 합니다:\n${oversizedFiles.join('\n')}`);
}
// 파일 개수 제한 확인
- if (courseVideoCount + validFiles.length > 10) {
- alert('강좌 영상은 최대 10개까지 첨부할 수 있습니다.');
+ const totalCount = courseVideoCount + validFiles.length;
+ if (totalCount > MAX_COUNT) {
+ const availableCount = MAX_COUNT - courseVideoCount;
+ alert(`강좌 영상은 최대 ${MAX_COUNT}개까지 첨부할 수 있습니다. (현재 ${courseVideoCount}개, 추가 가능 ${availableCount > 0 ? availableCount : 0}개)`);
+ e.target.value = '';
+ return;
+ }
+
+ // 30MB 초과 파일이나 잘못된 타입 파일만 있는 경우 중단
+ if (validFiles.length === 0 && (oversizedFiles.length > 0 || invalidTypeFiles.length > 0)) {
e.target.value = '';
return;
}
@@ -666,10 +649,26 @@ export default function AdminLessonsPage() {
if (validFiles.length > 0) {
try {
// 다중 파일 업로드
- await apiService.uploadFiles(validFiles);
- setCourseVideoFiles(prev => [...prev, ...validFiles.map(f => f.name)]);
- setCourseVideoFileObjects(prev => [...prev, ...validFiles]);
- setCourseVideoCount(prev => prev + validFiles.length);
+ const uploadResponse = await apiService.uploadFiles(validFiles);
+
+ // 응답에서 fileKey 배열 추출
+ const fileKeys: string[] = [];
+ if (uploadResponse.data?.results && Array.isArray(uploadResponse.data.results)) {
+ uploadResponse.data.results.forEach((result: any) => {
+ if (result.ok && result.fileKey) {
+ fileKeys.push(result.fileKey);
+ }
+ });
+ }
+
+ if (fileKeys.length > 0) {
+ setCourseVideoFiles(prev => [...prev, ...validFiles.map(f => f.name)]);
+ setCourseVideoFileObjects(prev => [...prev, ...validFiles]);
+ setCourseVideoFileKeys(prev => [...prev, ...fileKeys]);
+ setCourseVideoCount(prev => prev + validFiles.length);
+ } else {
+ throw new Error('파일 업로드는 완료되었지만 fileKey를 받지 못했습니다.');
+ }
} catch (error) {
console.error('강좌 영상 업로드 실패:', error);
alert('파일 업로드에 실패했습니다. 다시 시도해주세요.');
@@ -703,6 +702,7 @@ export default function AdminLessonsPage() {
onClick={() => {
setCourseVideoFiles(prev => prev.filter((_, i) => i !== index));
setCourseVideoFileObjects(prev => prev.filter((_, i) => i !== index));
+ setCourseVideoFileKeys(prev => prev.filter((_, i) => i !== index));
setCourseVideoCount(prev => prev - 1);
}}
className="size-[16px] flex items-center justify-center cursor-pointer hover:opacity-70 transition-opacity shrink-0"
@@ -740,30 +740,47 @@ export default function AdminLessonsPage() {
if (!files) return;
const MAX_SIZE = 30 * 1024 * 1024; // 30MB
+ const MAX_COUNT = 10; // 최대 10개
const validFiles: File[] = [];
const oversizedFiles: string[] = [];
+ const invalidTypeFiles: string[] = [];
Array.from(files).forEach((file) => {
- // zip 파일인지 확인
- if (!file.name.toLowerCase().endsWith('.zip')) {
+ // ZIP 파일인지 확인
+ const fileExtension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'));
+ if (fileExtension !== '.zip') {
+ invalidTypeFiles.push(file.name);
return;
}
- // 각 파일이 30MB 미만인지 검사
- if (file.size < MAX_SIZE) {
+ // 각 파일이 30MB 이하인지 검사
+ if (file.size <= MAX_SIZE) {
validFiles.push(file);
} else {
oversizedFiles.push(file.name);
}
});
- // 30MB 이상인 파일이 있으면 알림
+ // 파일 타입 오류
+ if (invalidTypeFiles.length > 0) {
+ alert(`다음 파일은 ZIP 형식만 가능합니다:\n${invalidTypeFiles.join('\n')}`);
+ }
+
+ // 30MB 초과 파일이 있으면 알림
if (oversizedFiles.length > 0) {
- alert(`다음 파일은 30MB 미만이어야 합니다:\n${oversizedFiles.join('\n')}`);
+ alert(`다음 파일은 30MB 이하여야 합니다:\n${oversizedFiles.join('\n')}`);
}
// 파일 개수 제한 확인
- if (vrContentCount + validFiles.length > 10) {
- alert('VR 콘텐츠는 최대 10개까지 첨부할 수 있습니다.');
+ const totalCount = vrContentCount + validFiles.length;
+ if (totalCount > MAX_COUNT) {
+ const availableCount = MAX_COUNT - vrContentCount;
+ alert(`VR 콘텐츠는 최대 ${MAX_COUNT}개까지 첨부할 수 있습니다. (현재 ${vrContentCount}개, 추가 가능 ${availableCount > 0 ? availableCount : 0}개)`);
+ e.target.value = '';
+ return;
+ }
+
+ // 30MB 초과 파일이나 잘못된 타입 파일만 있는 경우 중단
+ if (validFiles.length === 0 && (oversizedFiles.length > 0 || invalidTypeFiles.length > 0)) {
e.target.value = '';
return;
}
@@ -771,10 +788,26 @@ export default function AdminLessonsPage() {
if (validFiles.length > 0) {
try {
// 다중 파일 업로드
- await apiService.uploadFiles(validFiles);
- setVrContentFiles(prev => [...prev, ...validFiles.map(f => f.name)]);
- setVrContentFileObjects(prev => [...prev, ...validFiles]);
- setVrContentCount(prev => prev + validFiles.length);
+ const uploadResponse = await apiService.uploadFiles(validFiles);
+
+ // 응답에서 fileKey 배열 추출
+ const fileKeys: string[] = [];
+ if (uploadResponse.data?.results && Array.isArray(uploadResponse.data.results)) {
+ uploadResponse.data.results.forEach((result: any) => {
+ if (result.ok && result.fileKey) {
+ fileKeys.push(result.fileKey);
+ }
+ });
+ }
+
+ if (fileKeys.length > 0) {
+ setVrContentFiles(prev => [...prev, ...validFiles.map(f => f.name)]);
+ setVrContentFileObjects(prev => [...prev, ...validFiles]);
+ setVrContentFileKeys(prev => [...prev, ...fileKeys]);
+ setVrContentCount(prev => prev + validFiles.length);
+ } else {
+ throw new Error('파일 업로드는 완료되었지만 fileKey를 받지 못했습니다.');
+ }
} catch (error) {
console.error('VR 콘텐츠 업로드 실패:', error);
alert('파일 업로드에 실패했습니다. 다시 시도해주세요.');
@@ -808,6 +841,7 @@ export default function AdminLessonsPage() {
onClick={() => {
setVrContentFiles(prev => prev.filter((_, i) => i !== index));
setVrContentFileObjects(prev => prev.filter((_, i) => i !== index));
+ setVrContentFileKeys(prev => prev.filter((_, i) => i !== index));
setVrContentCount(prev => prev - 1);
}}
className="size-[16px] flex items-center justify-center cursor-pointer hover:opacity-70 transition-opacity shrink-0"
@@ -844,25 +878,59 @@ export default function AdminLessonsPage() {
첨부
{
const files = e.target.files;
if (!files || files.length === 0) return;
const file = files[0];
+
// CSV 파일만 허용
- if (file.name.toLowerCase().endsWith('.csv')) {
- try {
- // 단일 파일 업로드
- await apiService.uploadFile(file);
- setQuestionFileObject(file);
- setQuestionFileCount(1);
- } catch (error) {
- console.error('학습 평가 문제 업로드 실패:', error);
- alert('파일 업로드에 실패했습니다. 다시 시도해주세요.');
- }
+ if (!file.name.toLowerCase().endsWith('.csv')) {
+ alert('CSV 파일 형식만 첨부할 수 있습니다.');
+ e.target.value = '';
+ return;
}
+
+ try {
+ // 단일 파일 업로드
+ const uploadResponse = await apiService.uploadFile(file);
+
+ // 응답에서 fileKey 추출
+ let fileKey: string | null = null;
+ if (uploadResponse.data?.fileKey) {
+ fileKey = uploadResponse.data.fileKey;
+ } else if (uploadResponse.data?.key) {
+ fileKey = uploadResponse.data.key;
+ } else if (uploadResponse.data?.id) {
+ fileKey = uploadResponse.data.id;
+ } else if (uploadResponse.data?.imageKey) {
+ fileKey = uploadResponse.data.imageKey;
+ } else if (uploadResponse.data?.fileId) {
+ fileKey = uploadResponse.data.fileId;
+ } else if (uploadResponse.data?.data && (uploadResponse.data.data.key || uploadResponse.data.data.fileKey)) {
+ fileKey = uploadResponse.data.data.key || uploadResponse.data.data.fileKey;
+ } else if (uploadResponse.data?.results && Array.isArray(uploadResponse.data.results) && uploadResponse.data.results.length > 0) {
+ const result = uploadResponse.data.results[0];
+ if (result.ok && result.fileKey) {
+ fileKey = result.fileKey;
+ }
+ }
+
+ if (fileKey) {
+ setQuestionFileObject(file);
+ setQuestionFileKey(fileKey);
+ setQuestionFileCount(1);
+ } else {
+ throw new Error('파일 업로드는 완료되었지만 fileKey를 받지 못했습니다.');
+ }
+ } catch (error) {
+ console.error('학습 평가 문제 업로드 실패:', error);
+ alert('파일 업로드에 실패했습니다. 다시 시도해주세요.');
+ }
+ // input 초기화 (같은 파일 다시 선택 가능하도록)
+ e.target.value = '';
}}
/>
diff --git a/src/app/components/CsvViewer.tsx b/src/app/components/CsvViewer.tsx
new file mode 100644
index 0000000..b9a0652
--- /dev/null
+++ b/src/app/components/CsvViewer.tsx
@@ -0,0 +1,231 @@
+'use client';
+
+import { useState, useRef } from 'react';
+
+interface CsvViewerProps {
+ onFileSelect?: (file: File) => void;
+ onDataParsed?: (data: string[][]) => void;
+}
+
+export default function CsvViewer({ onFileSelect, onDataParsed }: CsvViewerProps) {
+ const [csvData, setCsvData] = useState([]);
+ const [headers, setHeaders] = useState([]);
+ const [rows, setRows] = useState([]);
+ const [fileName, setFileName] = useState('');
+ const fileInputRef = useRef(null);
+
+ // CSV 파싱 함수
+ const parseCsv = (text: string): string[][] => {
+ const lines: string[][] = [];
+ let currentLine: string[] = [];
+ let currentField = '';
+ let inQuotes = false;
+
+ for (let i = 0; i < text.length; i++) {
+ const char = text[i];
+ const nextChar = text[i + 1];
+
+ if (char === '"') {
+ if (inQuotes && nextChar === '"') {
+ // 이스케이프된 따옴표
+ currentField += '"';
+ i++; // 다음 문자 건너뛰기
+ } else {
+ // 따옴표 시작/끝
+ inQuotes = !inQuotes;
+ }
+ } else if (char === ',' && !inQuotes) {
+ // 필드 구분자
+ currentLine.push(currentField.trim());
+ currentField = '';
+ } else if ((char === '\n' || char === '\r') && !inQuotes) {
+ // 줄바꿈
+ if (char === '\r' && nextChar === '\n') {
+ i++; // \r\n 건너뛰기
+ }
+ if (currentField || currentLine.length > 0) {
+ currentLine.push(currentField.trim());
+ lines.push(currentLine);
+ currentLine = [];
+ currentField = '';
+ }
+ } else {
+ currentField += char;
+ }
+ }
+
+ // 마지막 필드 추가
+ if (currentField || currentLine.length > 0) {
+ currentLine.push(currentField.trim());
+ lines.push(currentLine);
+ }
+
+ return lines;
+ };
+
+ const handleFileChange = (e: React.ChangeEvent) => {
+ const file = e.target.files?.[0];
+ if (!file) return;
+
+ // CSV 파일인지 확인
+ if (!file.name.toLowerCase().endsWith('.csv')) {
+ alert('CSV 파일만 업로드할 수 있습니다.');
+ e.target.value = '';
+ return;
+ }
+
+ setFileName(file.name);
+
+ const reader = new FileReader();
+ reader.onload = (event) => {
+ const text = event.target?.result as string;
+ if (!text) return;
+
+ try {
+ const parsed = parseCsv(text);
+
+ if (parsed.length === 0) {
+ alert('CSV 파일이 비어있습니다.');
+ return;
+ }
+
+ // 첫 번째 줄을 헤더로 사용
+ const csvHeaders = parsed[0];
+ const csvRows = parsed.slice(1);
+
+ setHeaders(csvHeaders);
+ setRows(csvRows);
+ setCsvData(parsed);
+
+ // 콜백 호출
+ if (onFileSelect) {
+ onFileSelect(file);
+ }
+ if (onDataParsed) {
+ onDataParsed(parsed);
+ }
+ } catch (error) {
+ console.error('CSV 파싱 오류:', error);
+ alert('CSV 파일을 읽는 중 오류가 발생했습니다.');
+ }
+ };
+
+ reader.onerror = () => {
+ alert('파일을 읽는 중 오류가 발생했습니다.');
+ };
+
+ reader.readAsText(file, 'UTF-8');
+ };
+
+ const handleClear = () => {
+ setCsvData([]);
+ setHeaders([]);
+ setRows([]);
+ setFileName('');
+ if (fileInputRef.current) {
+ fileInputRef.current.value = '';
+ }
+ };
+
+ return (
+
+ {/* 파일 업로드 영역 */}
+
+
+
+ {fileName && (
+
+
+ {fileName}
+
+
+
+ )}
+
+
+ {/* 표 영역 */}
+ {csvData.length > 0 && (
+
+
+ {/* 헤더 */}
+
+ {headers.map((header, index) => {
+ const isLast = index === headers.length - 1;
+ return (
+
+
+
{header || `열 ${index + 1}`}
+
+
+ );
+ })}
+
+
+ {/* 데이터 행 */}
+ {rows.map((row, rowIndex) => (
+
+
+ {headers.map((_, colIndex) => {
+ const isLast = colIndex === headers.length - 1;
+ const cellValue = row[colIndex] || '';
+ return (
+
+ );
+ })}
+
+
+ ))}
+
+
+ )}
+
+ {/* 데이터가 없을 때 */}
+ {csvData.length === 0 && (
+
+
+ CSV 파일을 선택하면 표 형태로 표시됩니다.
+
+
+ )}
+
+ );
+}
+
diff --git a/src/app/lib/apiService.ts b/src/app/lib/apiService.ts
index d6173e0..5dfc953 100644
--- a/src/app/lib/apiService.ts
+++ b/src/app/lib/apiService.ts
@@ -380,8 +380,8 @@ class ApiService {
subjectId: number;
title: string;
objective: string;
- videoUrl?: string;
- webglUrl?: string;
+ videoUrl?: string | string[];
+ webglUrl?: string | string[];
csvKey?: string;
}) {
return this.request('/lectures', {
@@ -397,8 +397,8 @@ class ApiService {
subjectId?: number;
title?: string;
objective?: string;
- videoUrl?: string;
- webglUrl?: string;
+ videoUrl?: string | string[];
+ webglUrl?: string | string[];
csvKey?: string;
csvUrl?: string;
}) {
@@ -408,6 +408,15 @@ class ApiService {
});
}
+ /**
+ * 강좌(lecture) 삭제
+ */
+ async deleteLecture(lectureId: string | number) {
+ return this.request(`/lectures/${lectureId}`, {
+ method: 'DELETE',
+ });
+ }
+
/**
* 리소스 조회
*/