Compare commits

..

2 Commits

Author SHA1 Message Date
5a26d96386 강좌 삭제 구현1 2025-11-28 21:37:05 +09:00
03b4fa108a 강좌 수정 삭제 작업중1 2025-11-28 20:33:25 +09:00
10 changed files with 2559 additions and 298 deletions

View File

@@ -411,7 +411,8 @@ export default function CourseRegistrationModal({ open, onClose, onSave, onDelet
}; };
// 삭제 버튼 클릭 핸들러 // 삭제 버튼 클릭 핸들러
const handleDeleteClick = () => { const handleDeleteClick = (e: React.MouseEvent) => {
e.stopPropagation();
setIsDeleteConfirmOpen(true); setIsDeleteConfirmOpen(true);
}; };
@@ -559,24 +560,27 @@ export default function CourseRegistrationModal({ open, onClose, onSave, onDelet
}); });
}; };
if (!open) return null; if (!open && !isDeleteConfirmOpen) return null;
return ( return (
<div <>
className="fixed inset-0 z-50 flex items-center justify-center" {/* 메인 모달 */}
aria-hidden={!open} {open && (
onClick={onClose} <div
> className="fixed inset-0 z-50 flex items-center justify-center"
<div aria-hidden={!open}
className="absolute inset-0 bg-black/40" onClick={onClose}
aria-hidden="true" >
/> <div
<div className="absolute inset-0 bg-black/40"
ref={modalRef} aria-hidden="true"
className="relative z-10 shadow-xl" />
onClick={handleModalClick} <div
> ref={modalRef}
<div className="bg-white border border-[var(--color-neutral-40)] rounded-[12px] w-full min-w-[480px] max-h-[90vh] overflow-y-auto"> className="relative z-10 shadow-xl"
onClick={handleModalClick}
>
<div className="bg-white border border-[var(--color-neutral-40)] rounded-[12px] w-full min-w-[480px] max-h-[90vh] overflow-y-auto">
{/* Header */} {/* Header */}
<div className="flex items-center justify-between gap-[10px] p-6"> <div className="flex items-center justify-between gap-[10px] p-6">
<h2 className="text-[20px] font-bold leading-normal text-[var(--color-neutral-700)]"> <h2 className="text-[20px] font-bold leading-normal text-[var(--color-neutral-700)]">
@@ -837,7 +841,9 @@ export default function CourseRegistrationModal({ open, onClose, onSave, onDelet
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div>
)}
{/* 삭제 확인 모달 */} {/* 삭제 확인 모달 */}
{isDeleteConfirmOpen && ( {isDeleteConfirmOpen && (
@@ -847,41 +853,48 @@ export default function CourseRegistrationModal({ open, onClose, onSave, onDelet
onClick={handleDeleteCancel} onClick={handleDeleteCancel}
aria-hidden="true" aria-hidden="true"
/> />
<div className="relative z-10 bg-white rounded-[8px] p-[24px] shadow-[0px_8px_20px_0px_rgba(0,0,0,0.06),0px_24px_60px_0px_rgba(0,0,0,0.12)] flex flex-col gap-[32px] items-end justify-end min-w-[500px]"> <div className="relative z-10 bg-white rounded-[8px] p-[24px] shadow-[0px_8px_20px_0px_rgba(0,0,0,0.06),0px_24px_60px_0px_rgba(0,0,0,0.12)] flex flex-col gap-[32px] items-end justify-end">
<div className="flex flex-col gap-[16px] items-start justify-center w-full"> <div className="flex flex-col gap-[16px] items-start justify-center w-full">
<h2 className="text-[18px] font-semibold leading-normal text-[var(--color-neutral-700)]"> <div className="flex gap-[8px] items-start w-full">
? <p className="text-[18px] font-semibold leading-[1.5] text-[#333c47]">
</h2> ?
<p className="text-[15px] font-normal leading-normal text-[var(--color-basic-text)]"> </p>
. </div>
<br /> <div className="flex gap-[8px] items-start w-full">
? <div className="text-[15px] font-normal leading-[1.5] text-[#4c5561]">
</p> <p className="mb-0"> .</p>
<p> ?</p>
</div>
</div>
{errors.submit && ( {errors.submit && (
<p className="text-[var(--color-error)] text-[13px] leading-tight">{errors.submit}</p> <p className="text-[var(--color-error)] text-[13px] leading-tight">{errors.submit}</p>
)} )}
</div> </div>
<div className="flex gap-2 items-center justify-end"> <div className="flex gap-[8px] items-center justify-end shrink-0">
<button <button
type="button" type="button"
onClick={handleDeleteCancel} onClick={handleDeleteCancel}
className="h-[40px] px-2 rounded-[8px] bg-[var(--color-bg-gray-light)] text-[16px] font-semibold leading-normal text-[var(--color-basic-text)] w-[80px] hover:bg-[var(--color-bg-gray-hover)] cursor-pointer transition-colors" className="bg-[#f1f3f5] h-[40px] rounded-[8px] px-[8px] flex items-center justify-center shrink-0 w-[80px] hover:bg-[#e9ecef] cursor-pointer transition-colors"
> >
<p className="text-[16px] font-semibold leading-[1.5] text-[#4c5561] text-center whitespace-pre">
</p>
</button> </button>
<button <button
type="button" type="button"
onClick={handleDeleteConfirm} onClick={handleDeleteConfirm}
disabled={isDeleting} disabled={isDeleting}
className="h-[40px] px-4 rounded-[8px] bg-[#fef2f2] text-[16px] font-semibold leading-normal text-[var(--color-error)] hover:bg-[#fae6e6] cursor-pointer transition-colors disabled:opacity-50 disabled:cursor-not-allowed" className="bg-[#f64c4c] h-[40px] rounded-[8px] px-[8px] flex items-center justify-center shrink-0 w-[80px] hover:bg-[#e63939] cursor-pointer transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
> >
{isDeleting ? '삭제 중...' : '삭제하기'} <p className="text-[16px] font-semibold leading-[1.5] text-white text-center whitespace-pre">
{isDeleting ? '삭제 중...' : '삭제'}
</p>
</button> </button>
</div> </div>
</div> </div>
</div> </div>
)} )}
</div> </>
); );
} }

File diff suppressed because it is too large Load Diff

View File

@@ -2,29 +2,46 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation'; import { useParams, useRouter } from 'next/navigation';
import Image from 'next/image';
import AdminSidebar from '@/app/components/AdminSidebar'; import AdminSidebar from '@/app/components/AdminSidebar';
import BackArrowSvg from '@/app/svgs/backarrow'; import BackArrowSvg from '@/app/svgs/backarrow';
import DownloadIcon from '@/app/svgs/downloadicon';
import apiService from '@/app/lib/apiService'; import apiService from '@/app/lib/apiService';
import { getCourses } from '@/app/admin/courses/mockData';
type Lesson = { type VideoFile = {
id: string; id: string;
title: string; fileName: string;
duration: string; // "12:46" 형식 fileSize: string;
state: "제출완료" | "제출대기"; fileKey?: string;
action: "복습하기" | "이어서 수강하기" | "수강하기"; url?: string;
};
type VrFile = {
id: string;
fileName: string;
fileSize: string;
fileKey?: string;
url?: string;
};
type QuizQuestion = {
id: string;
number: number;
question: string;
correctAnswer: string;
wrongAnswer1: string;
wrongAnswer2: string;
wrongAnswer3: string;
}; };
type CourseDetail = { type CourseDetail = {
id: string; id: string;
status: "수강 중" | "수강 예정" | "수강 완료"; courseName: string; // 교육 과정명
title: string; title: string; // 강좌명
goal: string; goal: string; // 학습 목표 (여러 줄)
method: string; videoFiles: VideoFile[];
summary: string; // VOD · 총 n강 · n시간 n분 vrFiles: VrFile[];
submitSummary: string; // 학습 제출 n/n quizData: QuizQuestion[];
thumbnail: string;
lessons: Lesson[];
}; };
export default function AdminCourseDetailPage() { export default function AdminCourseDetailPage() {
@@ -33,6 +50,9 @@ export default function AdminCourseDetailPage() {
const [course, setCourse] = useState<CourseDetail | null>(null); const [course, setCourse] = useState<CourseDetail | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const [showToast, setShowToast] = useState(false);
useEffect(() => { useEffect(() => {
const fetchCourse = async () => { const fetchCourse = async () => {
@@ -74,20 +94,8 @@ export default function AdminCourseDetailPage() {
throw new Error('강좌를 찾을 수 없습니다.'); throw new Error('강좌를 찾을 수 없습니다.');
} }
// 첨부파일 정보 구성 // 첨부파일 정보 구성 (나중에 videoFiles와 vrFiles 길이로 업데이트됨)
const attachmentParts: string[] = []; // 이 부분은 videoFiles와 vrFiles가 구성된 후에 업데이트됩니다
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(', ')
: '없음';
// 썸네일 이미지 가져오기 // 썸네일 이미지 가져오기
let thumbnail = '/imgs/talk.png'; let thumbnail = '/imgs/talk.png';
@@ -102,25 +110,216 @@ export default function AdminCourseDetailPage() {
} }
} }
// 교육 과정명 가져오기 - AdminLessonsPage와 동일한 방식
let courseName = '';
const subjectId = data.subjectId || data.subject_id;
if (subjectId) {
try {
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[] = [];
// 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);
}
// 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 파일 목록 구성 - fileKey 배열에서 파일 조회
const vrFiles: VrFile[] = [];
// 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',
fileSize: '796.35 KB',
fileKey: data.webglKey || data.vrKey,
url: data.webglUrl || data.vrUrl,
});
}
// 퀴즈 데이터 구성 (CSV 파일이 있으면 파싱, 없으면 빈 배열)
const quizData: QuizQuestion[] = [];
if (data.csvKey || data.quizData) {
// 실제로는 CSV 파일을 파싱하거나 API에서 퀴즈 데이터를 가져와야 함
// 여기서는 예시 데이터만 추가
if (data.quizData && Array.isArray(data.quizData)) {
data.quizData.forEach((q: any, index: number) => {
quizData.push({
id: String(q.id || index + 1),
number: q.number || index + 1,
question: q.question || '블라블라블라블라블라블라블라블라블라',
correctAnswer: q.correctAnswer || q.correct_answer || '{정답}',
wrongAnswer1: q.wrongAnswer1 || q.wrong_answer1 || '{오답1}',
wrongAnswer2: q.wrongAnswer2 || q.wrong_answer2 || '{오답2}',
wrongAnswer3: q.wrongAnswer3 || q.wrong_answer3 || '{오답3}',
});
});
}
}
// API 응답 구조에 맞게 데이터 매핑 // API 응답 구조에 맞게 데이터 매핑
const courseDetail: CourseDetail = { const courseDetail: CourseDetail = {
id: String(data.id || params.id), id: String(data.id || params.id),
status: "수강 예정", // 관리자 페이지에서는 기본값 courseName: courseName || data.courseName || '교육 과정명',
title: data.title || data.lectureName || '', title: data.title || data.lectureName || '',
goal: data.objective || data.goal || '', goal: goalLines.length > 0 ? goalLines.join('\n') : (data.objective || data.goal || ''),
method: data.method || '', videoFiles: videoFiles,
summary: `VOD · 총 1강`, vrFiles: vrFiles,
submitSummary: '', quizData: quizData,
thumbnail: thumbnail,
lessons: [
{
id: String(data.id || params.id),
title: data.title || data.lectureName || '',
duration: '00:00',
state: "제출대기",
action: "수강하기",
}
],
}; };
setCourse(courseDetail); setCourse(courseDetail);
@@ -135,6 +334,16 @@ export default function AdminCourseDetailPage() {
fetchCourse(); fetchCourse();
}, [params?.id]); }, [params?.id]);
// 토스트 자동 닫기
useEffect(() => {
if (showToast) {
const timer = setTimeout(() => {
setShowToast(false);
}, 3000);
return () => clearTimeout(timer);
}
}, [showToast]);
if (loading) { if (loading) {
return ( return (
<div className="min-h-screen flex flex-col bg-white"> <div className="min-h-screen flex flex-col bg-white">
@@ -145,8 +354,18 @@ export default function AdminCourseDetailPage() {
</div> </div>
<main className="w-[1120px] bg-white"> <main className="w-[1120px] bg-white">
<div className="h-full flex flex-col px-8"> <div className="h-full flex flex-col px-8">
<div className="h-[100px] flex items-center"> <div className="h-[100px] flex items-center justify-between px-8">
<h1 className="text-[24px] font-bold leading-[1.5] text-[#1b2027]"> </h1> <div className="flex items-center gap-[12px]">
<button
type="button"
onClick={() => router.push('/admin/lessons')}
className="flex items-center justify-center size-[32px] cursor-pointer hover:opacity-80"
aria-label="뒤로가기"
>
<BackArrowSvg width={32} height={32} />
</button>
<h1 className="text-[24px] font-bold leading-[1.5] text-[#1b2027]"> </h1>
</div>
</div> </div>
<section className="px-8 pb-20"> <section className="px-8 pb-20">
<div className="flex items-center justify-center py-20"> <div className="flex items-center justify-center py-20">
@@ -171,8 +390,18 @@ export default function AdminCourseDetailPage() {
</div> </div>
<main className="w-[1120px] bg-white"> <main className="w-[1120px] bg-white">
<div className="h-full flex flex-col px-8"> <div className="h-full flex flex-col px-8">
<div className="h-[100px] flex items-center"> <div className="h-[100px] flex items-center justify-between px-8">
<h1 className="text-[24px] font-bold leading-[1.5] text-[#1b2027]"> </h1> <div className="flex items-center gap-[12px]">
<button
type="button"
onClick={() => router.push('/admin/lessons')}
className="flex items-center justify-center size-[32px] cursor-pointer hover:opacity-80"
aria-label="뒤로가기"
>
<BackArrowSvg width={32} height={32} />
</button>
<h1 className="text-[24px] font-bold leading-[1.5] text-[#1b2027]"> </h1>
</div>
</div> </div>
<section className="px-8 pb-20"> <section className="px-8 pb-20">
<div className="flex flex-col items-center justify-center py-20"> <div className="flex flex-col items-center justify-center py-20">
@@ -194,6 +423,68 @@ export default function AdminCourseDetailPage() {
); );
} }
const handleDownload = async (fileKey?: string, url?: string, fileName?: string) => {
if (url) {
// URL이 있으면 직접 다운로드
const link = document.createElement('a');
link.href = url;
link.download = fileName || 'download';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} else if (fileKey) {
// fileKey가 있으면 API를 통해 다운로드
try {
const fileUrl = await apiService.getFile(fileKey);
if (fileUrl) {
const link = document.createElement('a');
link.href = fileUrl;
link.download = fileName || 'download';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
} catch (err) {
console.error('파일 다운로드 실패:', err);
alert('파일 다운로드에 실패했습니다.');
}
}
};
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 ( return (
<div className="min-h-screen flex flex-col bg-white"> <div className="min-h-screen flex flex-col bg-white">
<div className="flex flex-1 min-h-0 justify-center"> <div className="flex flex-1 min-h-0 justify-center">
@@ -204,9 +495,9 @@ export default function AdminCourseDetailPage() {
</div> </div>
{/* 메인 콘텐츠 */} {/* 메인 콘텐츠 */}
<main className="w-[1120px] bg-white"> <main className="w-[1120px] bg-white">
<div className="h-full flex flex-col px-8"> <div className="h-full flex flex-col">
{/* 헤더 */} {/* 헤더 */}
<div className="h-[100px] flex items-center"> <div className="h-[100px] flex items-center px-8">
<div className="flex items-center gap-[12px]"> <div className="flex items-center gap-[12px]">
<button <button
type="button" type="button"
@@ -217,104 +508,344 @@ export default function AdminCourseDetailPage() {
<BackArrowSvg width={32} height={32} /> <BackArrowSvg width={32} height={32} />
</button> </button>
<h1 className="text-[24px] font-bold leading-[1.5] text-[#1b2027]"> <h1 className="text-[24px] font-bold leading-[1.5] text-[#1b2027]">
</h1> </h1>
</div> </div>
</div> </div>
{/* 콘텐츠 */} {/* 콘텐츠 */}
<section className="pb-20"> <div className="flex flex-col gap-[40px] pb-20 pt-6 px-8">
<div className="rounded-[8px] bg-white px-8 pb-20 pt-6"> {/* 강좌 정보 섹션 */}
{/* 상단 소개 카드 */} <div className="flex flex-col gap-[8px]">
<div className="flex gap-6 rounded-[8px] bg-[#f8f9fa] p-6"> <div className="flex flex-col gap-[8px]">
<div className="relative h-[159px] w-[292px] overflow-hidden rounded"> <p className="text-[18px] font-bold leading-[1.5] text-[#333c47]"> </p>
<Image
src={course.thumbnail}
alt={course.title}
fill
sizes="292px"
className="object-cover"
unoptimized
/>
</div>
<div className="flex-1">
<div className="flex h-[27px] items-center gap-2">
<span className="h-[20px] rounded-[4px] bg-[#e5f5ec] px-1.5 text-[13px] font-semibold leading-[1.4] text-[#0c9d61]">
{course.status}
</span>
<h2 className="text-[18px] font-semibold leading-[1.5] text-[#333c47]">{course.title}</h2>
</div>
<div className="mt-3 space-y-1">
<p className="text-[15px] leading-[1.5] text-[#333c47]">
<span className="font-medium"> :</span> {course.goal}
</p>
<p className="text-[15px] leading-[1.5] text-[#333c47]">
<span className="font-medium"> :</span> {course.method}
</p>
</div>
<div className="mt-3 flex items-center gap-5 text-[13px] leading-[1.4] text-[#8c95a1]">
<span>{course.summary}</span>
{course.submitSummary && <span>{course.submitSummary}</span>}
</div>
</div>
</div> </div>
<div className="flex flex-col gap-[24px]">
{/* 교육 과정명 */}
<div className="flex flex-col gap-[4px]">
<div className="w-[96px]">
<p className="text-[15px] font-semibold leading-[1.5] text-[#6c7682]"> </p>
</div>
<div>
<p className="text-[16px] font-normal leading-[1.5] text-[#333c47]">{course.courseName}</p>
</div>
</div>
{/* 차시 리스트 */} {/* 강좌명 */}
<div className="mt-6 space-y-2"> <div className="flex flex-col gap-[4px]">
{course.lessons.map((l) => { <div className="w-[96px]">
const isSubmitted = l.state === "제출완료"; <p className="text-[15px] font-semibold leading-[1.5] text-[#6c7682]"></p>
const submitBtnStyle = </div>
l.state === "제출완료" <div>
? "border border-transparent text-[#384fbf]" <p className="text-[16px] font-normal leading-[1.5] text-[#333c47]">{course.title}</p>
: "border " + (l.action === "이어서 수강하기" || l.action === "수강하기" ? "border-[#b1b8c0]" : "border-[#8c95a1]"); </div>
const rightBtnStyle = </div>
l.action === "이어서 수강하기"
? "bg-[#ecf0ff] text-[#384fbf]" {/* 학습 목표 */}
: l.action === "수강하기" <div className="flex flex-col gap-[4px]">
? "bg-[#ecf0ff] text-[#384fbf]" <div className="w-[96px]">
: "bg-[#f1f3f5] text-[#4c5561]"; <p className="text-[15px] font-semibold leading-[1.5] text-[#6c7682]"> </p>
return ( </div>
<div key={l.id} className="rounded-[8px] border border-[#dee1e6] bg-white"> <div className="flex flex-col">
<div className="flex items-center justify-between gap-4 rounded-[8px] px-6 py-4"> {goalLines.map((line, index) => (
<div className="min-w-0"> <p key={index} className="text-[16px] font-normal leading-[1.5] text-[#333c47] mb-0">
<p className="text-[16px] font-semibold leading-[1.5] text-[#333c47]">{l.title}</p> {line}
<div className="mt-1 flex items-center gap-3"> </p>
<p className="w-[40px] text-[13px] leading-[1.4] text-[#8c95a1]">{l.duration}</p> ))}
</div> </div>
</div> </div>
<div className="flex items-center gap-2">
<button
type="button"
className={[
"h-8 rounded-[6px] px-4 text-[14px] font-medium leading-[1.5]",
"bg-white",
submitBtnStyle,
].join(" ")}
>
{isSubmitted ? "학습 제출 완료" : "학습 제출 하기"}
</button>
<button
type="button"
className={[
"h-8 rounded-[6px] px-4 text-[14px] font-medium leading-[1.5]",
rightBtnStyle,
].join(" ")}
>
{l.action}
</button>
</div>
</div>
</div>
);
})}
</div> </div>
</div> </div>
</section>
{/* 파일 첨부 섹션 */}
<div className="flex flex-col gap-[8px]">
<p className="text-[18px] font-bold leading-[1.5] text-[#1b2027]"> </p>
<div className="flex flex-col gap-[40px]">
{/* 강좌 영상 */}
<div className="flex flex-col gap-[8px]">
<div className="flex gap-[12px] h-[32px] items-center">
<div className="flex gap-[8px] items-center">
<p className="text-[15px] font-semibold leading-[1.5] text-[#6c7682]"> </p>
</div>
</div>
<div className="border border-[#dee1e6] rounded-[8px] bg-gray-50">
{course.videoFiles.length > 0 ? (
<div className="flex flex-col py-[12px]">
{course.videoFiles.map((video) => (
<div
key={video.id}
className="bg-white border border-[#dee1e6] rounded-[6px] h-[64px] flex items-center gap-[12px] px-[17px] mx-[12px] mb-[8px] last:mb-0"
>
<div className="size-[24px] shrink-0">
<img src="/imgs/play.svg" alt="" className="size-full" />
</div>
<div className="flex-1 flex items-center gap-[8px] min-w-0">
<p className="text-[15px] font-normal leading-[1.5] text-[#1b2027] truncate">
{video.fileName}
</p>
<p className="text-[13px] font-normal leading-[1.4] text-[#8c95a1] shrink-0">
{video.fileSize}
</p>
</div>
<button
type="button"
onClick={() => handleDownload(video.fileKey, video.url, video.fileName)}
className="bg-white border border-[#8c95a1] h-[32px] rounded-[6px] px-4 flex items-center justify-center gap-[4px] shrink-0"
>
<DownloadIcon className="size-[16px] text-[#4c5561]" />
<p className="text-[13px] font-medium leading-[1.4] text-[#4c5561]"></p>
</button>
</div>
))}
</div>
) : (
<div className="h-[64px] flex items-center justify-center">
<p className="text-[14px] font-normal leading-[1.5] text-[#8c95a1] text-center">
.
</p>
</div>
)}
</div>
</div>
{/* VR 콘텐츠 */}
<div className="flex flex-col gap-[8px]">
<div className="flex gap-[12px] h-[32px] items-center">
<div className="flex gap-[8px] items-center">
<p className="text-[15px] font-semibold leading-[1.5] text-[#6c7682]">VR </p>
</div>
</div>
<div className="border border-[#dee1e6] rounded-[8px] bg-gray-50">
{course.vrFiles.length > 0 ? (
<div className="flex flex-col py-[12px]">
{course.vrFiles.map((vr) => (
<div
key={vr.id}
className="bg-white border border-[#dee1e6] rounded-[6px] h-[64px] flex items-center gap-[12px] px-[17px] mx-[12px] mb-[8px] last:mb-0"
>
<div className="size-[24px] shrink-0">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14 2H6C5.46957 2 4.96086 2.21071 4.58579 2.58579C4.21071 2.96086 4 3.46957 4 4V20C4 20.5304 4.21071 21.0391 4.58579 21.4142C4.96086 21.7893 5.46957 22 6 22H18C18.5304 22 19.0391 21.7893 19.4142 21.4142C19.7893 21.0391 20 20.5304 20 20V8L14 2Z" stroke="#4c5561" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
<path d="M14 2V8H20" stroke="#4c5561" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
</div>
<div className="flex-1 flex items-center gap-[8px] min-w-0">
<p className="text-[15px] font-normal leading-[1.5] text-[#1b2027] truncate">
{vr.fileName}
</p>
<p className="text-[13px] font-normal leading-[1.4] text-[#8c95a1] shrink-0">
{vr.fileSize}
</p>
</div>
<button
type="button"
onClick={() => handleDownload(vr.fileKey, vr.url, vr.fileName)}
className="bg-white border border-[#8c95a1] h-[32px] rounded-[6px] px-4 flex items-center justify-center gap-[4px] shrink-0"
>
<DownloadIcon className="size-[16px] text-[#4c5561]" />
<p className="text-[13px] font-medium leading-[1.4] text-[#4c5561]"></p>
</button>
</div>
))}
</div>
) : (
<div className="h-[64px] flex items-center justify-center">
<p className="text-[14px] font-normal leading-[1.5] text-[#8c95a1] text-center">
VR .
</p>
</div>
)}
</div>
</div>
{/* 학습 평가 문제 */}
<div className="flex flex-col gap-[8px]">
<div className="flex gap-[12px] h-[32px] items-center justify-between">
<div className="flex gap-[8px] items-center">
<p className="text-[15px] font-semibold leading-[1.5] text-[#6c7682]"> </p>
</div>
{course.quizData.length > 0 && (
<button
type="button"
className="bg-white border border-[#8c95a1] h-[32px] rounded-[6px] px-4 flex items-center justify-center gap-[4px]"
>
<DownloadIcon className="size-[16px] text-[#4c5561]" />
<p className="text-[13px] font-medium leading-[1.4] text-[#4c5561]"></p>
</button>
)}
</div>
<div className="border border-[#dee1e6] rounded-[8px] bg-gray-50">
{course.quizData.length > 0 ? (
<div className="p-6">
<div className="bg-white border border-[#dee1e6] rounded-[8px] overflow-hidden">
{/* 테이블 헤더 */}
<div className="bg-[#f1f8ff] h-[48px] flex">
<div className="w-[48px] border-r border-[#dee1e6] flex items-center justify-center px-2 py-3">
<p className="text-[14px] font-semibold leading-[1.5] text-[#4c5561]"></p>
</div>
<div className="flex-1 border-r border-[#dee1e6] flex items-center px-2 py-3">
<p className="text-[14px] font-semibold leading-[1.5] text-[#4c5561]"></p>
</div>
<div className="w-[140px] border-r border-[#dee1e6] flex items-center px-2 py-3">
<p className="text-[14px] font-semibold leading-[1.5] text-[#4c5561]"></p>
</div>
<div className="w-[140px] border-r border-[#dee1e6] flex items-center px-2 py-3">
<p className="text-[14px] font-semibold leading-[1.5] text-[#4c5561]">1</p>
</div>
<div className="w-[140px] border-r border-[#dee1e6] flex items-center px-2 py-3">
<p className="text-[14px] font-semibold leading-[1.5] text-[#4c5561]">2</p>
</div>
<div className="w-[140px] flex items-center px-2 py-3">
<p className="text-[14px] font-semibold leading-[1.5] text-[#4c5561]">3</p>
</div>
</div>
{/* 테이블 행 */}
{course.quizData.map((quiz) => (
<div key={quiz.id} className="border-t border-[#dee1e6] h-[48px] flex">
<div className="w-[48px] border-r border-[#dee1e6] flex items-center justify-center px-2 py-3">
<p className="text-[15px] font-medium leading-[1.5] text-[#1b2027]">{quiz.number}</p>
</div>
<div className="flex-1 border-r border-[#dee1e6] flex items-center px-2 py-3">
<p className="text-[15px] font-medium leading-[1.5] text-[#1b2027] truncate">{quiz.question}</p>
</div>
<div className="w-[140px] border-r border-[#dee1e6] flex items-center px-2 py-3">
<p className="text-[15px] font-medium leading-[1.5] text-[#1b2027] truncate">{quiz.correctAnswer}</p>
</div>
<div className="w-[140px] border-r border-[#dee1e6] flex items-center px-2 py-3">
<p className="text-[15px] font-medium leading-[1.5] text-[#1b2027] truncate">{quiz.wrongAnswer1}</p>
</div>
<div className="w-[140px] border-r border-[#dee1e6] flex items-center px-2 py-3">
<p className="text-[15px] font-medium leading-[1.5] text-[#1b2027] truncate">{quiz.wrongAnswer2}</p>
</div>
<div className="w-[140px] flex items-center px-2 py-3">
<p className="text-[15px] font-medium leading-[1.5] text-[#1b2027] truncate">{quiz.wrongAnswer3}</p>
</div>
</div>
))}
</div>
</div>
) : (
<div className="h-[64px] flex items-center justify-center">
<p className="text-[14px] font-normal leading-[1.5] text-[#8c95a1] text-center">
.
</p>
</div>
)}
</div>
</div>
</div>
</div>
{/* Footer 버튼 */}
<div className="flex gap-[12px] items-center justify-end">
<button
type="button"
onClick={handleDeleteClick}
className="bg-[#fef2f2] h-[48px] rounded-[10px] px-2 flex items-center justify-center min-w-[80px] cursor-pointer hover:bg-[#fae6e6] transition-colors"
>
<p className="text-[16px] font-semibold leading-[1.5] text-[#f64c4c]"></p>
</button>
<button
type="button"
onClick={async () => {
// 현재 강좌 데이터를 sessionStorage에 저장
if (course && params?.id) {
try {
// API에서 원본 강좌 데이터 가져오기
const response = await apiService.getLectures();
const lectures = Array.isArray(response.data)
? response.data
: response.data?.items || response.data?.lectures || response.data?.data || [];
const lectureData = lectures.find((l: any) => String(l.id || l.lectureId) === params.id);
if (lectureData) {
// sessionStorage에 원본 데이터 저장
sessionStorage.setItem('selectedLecture', JSON.stringify(lectureData));
}
router.push(`/admin/lessons/${params.id}/edit`);
} catch (error) {
console.error('강좌 데이터 가져오기 실패:', error);
// 실패해도 수정 페이지로 이동
router.push(`/admin/lessons/${params.id}/edit`);
}
}
}}
className="bg-[#f1f3f5] h-[48px] rounded-[10px] px-4 flex items-center justify-center min-w-[114px] cursor-pointer hover:bg-[#e5e7eb] transition-colors"
>
<p className="text-[16px] font-semibold leading-normal text-normal"></p>
</button>
</div>
</div>
</div> </div>
</main> </main>
</div> </div>
</div> </div>
</div>
{/* 삭제 확인 모달 */}
{isDeleteModalOpen && (
<div className="fixed inset-0 z-[60] flex items-center justify-center">
<div
className="absolute inset-0 bg-black/40"
onClick={handleDeleteCancel}
aria-hidden="true"
/>
<div className="relative z-10 bg-white rounded-[8px] p-[24px] shadow-[0px_8px_20px_0px_rgba(0,0,0,0.06),0px_24px_60px_0px_rgba(0,0,0,0.12)] flex flex-col gap-[32px] items-end justify-end min-w-[500px]">
<div className="flex flex-col gap-[16px] items-start justify-center w-full">
<div className="flex gap-[8px] items-start w-full">
<p className="text-[18px] font-semibold leading-[1.5] text-[#333c47]">
?
</p>
</div>
<div className="flex gap-[8px] items-start w-full">
<div className="text-[15px] font-normal leading-[1.5] text-[#4c5561]">
<p className="mb-0"> .</p>
<p> ?</p>
</div>
</div>
</div>
<div className="flex gap-[8px] items-center justify-end shrink-0">
<button
type="button"
onClick={handleDeleteCancel}
className="bg-[#f1f3f5] h-[40px] rounded-[8px] px-[8px] flex items-center justify-center shrink-0 w-[80px] hover:bg-[#e9ecef] cursor-pointer transition-colors"
>
<p className="text-[16px] font-semibold leading-[1.5] text-[#4c5561] text-center whitespace-pre">
</p>
</button>
<button
type="button"
onClick={handleDeleteConfirm}
disabled={isDeleting}
className="bg-[#f64c4c] h-[40px] rounded-[8px] px-[8px] flex items-center justify-center shrink-0 w-[80px] hover:bg-[#e63939] cursor-pointer transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
<p className="text-[16px] font-semibold leading-[1.5] text-white text-center whitespace-pre">
{isDeleting ? '삭제 중...' : '삭제'}
</p>
</button>
</div>
</div>
</div>
)}
{/* 삭제 완료 토스트 */}
{showToast && (
<div className="fixed right-[60px] bottom-[60px] z-50">
<div className="bg-white border border-[#dee1e6] rounded-[8px] p-4 min-w-[360px] flex gap-[10px] items-center">
<div className="relative shrink-0 w-[16.667px] h-[16.667px]">
<svg width="17" height="17" viewBox="0 0 17 17" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="8.5" cy="8.5" r="8.5" fill="#384FBF"/>
<path d="M5.5 8.5L7.5 10.5L11.5 6.5" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
</div>
<p className="text-[15px] font-medium leading-[1.5] text-[#1b2027] text-nowrap">
.
</p>
</div>
</div>
)}
</div>
); );
} }

View File

@@ -39,11 +39,14 @@ export default function AdminLessonsPage() {
const [courseVideoCount, setCourseVideoCount] = useState(0); const [courseVideoCount, setCourseVideoCount] = useState(0);
const [courseVideoFiles, setCourseVideoFiles] = useState<string[]>([]); const [courseVideoFiles, setCourseVideoFiles] = useState<string[]>([]);
const [courseVideoFileObjects, setCourseVideoFileObjects] = useState<File[]>([]); const [courseVideoFileObjects, setCourseVideoFileObjects] = useState<File[]>([]);
const [courseVideoFileKeys, setCourseVideoFileKeys] = useState<string[]>([]);
const [vrContentCount, setVrContentCount] = useState(0); const [vrContentCount, setVrContentCount] = useState(0);
const [vrContentFiles, setVrContentFiles] = useState<string[]>([]); const [vrContentFiles, setVrContentFiles] = useState<string[]>([]);
const [vrContentFileObjects, setVrContentFileObjects] = useState<File[]>([]); const [vrContentFileObjects, setVrContentFileObjects] = useState<File[]>([]);
const [vrContentFileKeys, setVrContentFileKeys] = useState<string[]>([]);
const [questionFileCount, setQuestionFileCount] = useState(0); const [questionFileCount, setQuestionFileCount] = useState(0);
const [questionFileObject, setQuestionFileObject] = useState<File | null>(null); const [questionFileObject, setQuestionFileObject] = useState<File | null>(null);
const [questionFileKey, setQuestionFileKey] = useState<string | null>(null);
// 에러 상태 // 에러 상태
const [errors, setErrors] = useState<{ const [errors, setErrors] = useState<{
@@ -234,11 +237,14 @@ export default function AdminLessonsPage() {
setCourseVideoCount(0); setCourseVideoCount(0);
setCourseVideoFiles([]); setCourseVideoFiles([]);
setCourseVideoFileObjects([]); setCourseVideoFileObjects([]);
setCourseVideoFileKeys([]);
setVrContentCount(0); setVrContentCount(0);
setVrContentFiles([]); setVrContentFiles([]);
setVrContentFileObjects([]); setVrContentFileObjects([]);
setVrContentFileKeys([]);
setQuestionFileCount(0); setQuestionFileCount(0);
setQuestionFileObject(null); setQuestionFileObject(null);
setQuestionFileKey(null);
setErrors({}); setErrors({});
}; };
@@ -274,72 +280,27 @@ export default function AdminLessonsPage() {
setErrors({}); setErrors({});
try { try {
// 파일 업로드 및 키 추출 // 이미 업로드된 fileKey 배열 사용
let videoUrl: string | undefined; const videoFileKeys = courseVideoFileKeys;
let webglUrl: string | undefined; 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; let csvKey: string | undefined;
if (csvFileKey) {
// 강좌 영상 업로드 (첫 번째 파일만 사용) csvKey = csvFileKey;
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);
}
} }
// API 요청 body 구성 // API 요청 body 구성
@@ -347,8 +308,8 @@ export default function AdminLessonsPage() {
subjectId: number; subjectId: number;
title: string; title: string;
objective: string; objective: string;
videoUrl?: string; videoUrl?: string | string[];
webglUrl?: string; webglUrl?: string | string[];
csvKey?: string; csvKey?: string;
} = { } = {
subjectId: Number(selectedCourse), subjectId: Number(selectedCourse),
@@ -357,10 +318,10 @@ export default function AdminLessonsPage() {
}; };
// 선택적 필드 추가 // 선택적 필드 추가
if (videoUrl) { if (videoUrl && videoUrl.length > 0) {
requestBody.videoUrl = videoUrl; requestBody.videoUrl = videoUrl;
} }
if (webglUrl) { if (webglUrl && webglUrl.length > 0) {
requestBody.webglUrl = webglUrl; requestBody.webglUrl = webglUrl;
} }
if (csvKey) { if (csvKey) {
@@ -416,11 +377,14 @@ export default function AdminLessonsPage() {
setCourseVideoCount(0); setCourseVideoCount(0);
setCourseVideoFiles([]); setCourseVideoFiles([]);
setCourseVideoFileObjects([]); setCourseVideoFileObjects([]);
setCourseVideoFileKeys([]);
setVrContentCount(0); setVrContentCount(0);
setVrContentFiles([]); setVrContentFiles([]);
setVrContentFileObjects([]); setVrContentFileObjects([]);
setVrContentFileKeys([]);
setQuestionFileCount(0); setQuestionFileCount(0);
setQuestionFileObject(null); setQuestionFileObject(null);
setQuestionFileKey(null);
// 토스트 팝업 표시 // 토스트 팝업 표시
setShowToast(true); setShowToast(true);
@@ -628,37 +592,56 @@ export default function AdminLessonsPage() {
<input <input
type="file" type="file"
multiple multiple
accept=".mp4,video/mp4" accept=".mp4,.avi,.mov,.wmv,.flv,.webm,.mkv,video/mp4,video/avi,video/quicktime,video/x-ms-wmv,video/x-flv,video/webm,video/x-matroska"
className="hidden" className="hidden"
onChange={async (e) => { onChange={async (e) => {
const files = e.target.files; const files = e.target.files;
if (!files) return; if (!files) return;
const MAX_SIZE = 30 * 1024 * 1024; // 30MB const MAX_SIZE = 30 * 1024 * 1024; // 30MB
const MAX_COUNT = 10; // 최대 10개
const validFiles: File[] = []; const validFiles: File[] = [];
const oversizedFiles: string[] = []; const oversizedFiles: string[] = [];
const invalidTypeFiles: string[] = [];
// 영상 파일 확장자 확인
const videoExtensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm', '.mkv'];
Array.from(files).forEach((file) => { Array.from(files).forEach((file) => {
// mp4 파일인지 확인 const fileExtension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'));
if (!file.name.toLowerCase().endsWith('.mp4')) { if (!videoExtensions.includes(fileExtension)) {
invalidTypeFiles.push(file.name);
return; return;
} }
// 각 파일이 30MB 미만인지 검사 // 각 파일이 30MB 이하인지 검사
if (file.size < MAX_SIZE) { if (file.size <= MAX_SIZE) {
validFiles.push(file); validFiles.push(file);
} else { } else {
oversizedFiles.push(file.name); 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) { if (oversizedFiles.length > 0) {
alert(`다음 파일은 30MB 미만이어야 합니다:\n${oversizedFiles.join('\n')}`); alert(`다음 파일은 30MB 이하여야 합니다:\n${oversizedFiles.join('\n')}`);
} }
// 파일 개수 제한 확인 // 파일 개수 제한 확인
if (courseVideoCount + validFiles.length > 10) { const totalCount = courseVideoCount + validFiles.length;
alert('강좌 영상은 최대 10개까지 첨부할 수 있습니다.'); 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 = ''; e.target.value = '';
return; return;
} }
@@ -666,10 +649,26 @@ export default function AdminLessonsPage() {
if (validFiles.length > 0) { if (validFiles.length > 0) {
try { try {
// 다중 파일 업로드 // 다중 파일 업로드
await apiService.uploadFiles(validFiles); const uploadResponse = await apiService.uploadFiles(validFiles);
setCourseVideoFiles(prev => [...prev, ...validFiles.map(f => f.name)]);
setCourseVideoFileObjects(prev => [...prev, ...validFiles]); // 응답에서 fileKey 배열 추출
setCourseVideoCount(prev => prev + validFiles.length); 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) { } catch (error) {
console.error('강좌 영상 업로드 실패:', error); console.error('강좌 영상 업로드 실패:', error);
alert('파일 업로드에 실패했습니다. 다시 시도해주세요.'); alert('파일 업로드에 실패했습니다. 다시 시도해주세요.');
@@ -703,6 +702,7 @@ export default function AdminLessonsPage() {
onClick={() => { onClick={() => {
setCourseVideoFiles(prev => prev.filter((_, i) => i !== index)); setCourseVideoFiles(prev => prev.filter((_, i) => i !== index));
setCourseVideoFileObjects(prev => prev.filter((_, i) => i !== index)); setCourseVideoFileObjects(prev => prev.filter((_, i) => i !== index));
setCourseVideoFileKeys(prev => prev.filter((_, i) => i !== index));
setCourseVideoCount(prev => prev - 1); setCourseVideoCount(prev => prev - 1);
}} }}
className="size-[16px] flex items-center justify-center cursor-pointer hover:opacity-70 transition-opacity shrink-0" 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; if (!files) return;
const MAX_SIZE = 30 * 1024 * 1024; // 30MB const MAX_SIZE = 30 * 1024 * 1024; // 30MB
const MAX_COUNT = 10; // 최대 10개
const validFiles: File[] = []; const validFiles: File[] = [];
const oversizedFiles: string[] = []; const oversizedFiles: string[] = [];
const invalidTypeFiles: string[] = [];
Array.from(files).forEach((file) => { Array.from(files).forEach((file) => {
// zip 파일인지 확인 // ZIP 파일인지 확인
if (!file.name.toLowerCase().endsWith('.zip')) { const fileExtension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'));
if (fileExtension !== '.zip') {
invalidTypeFiles.push(file.name);
return; return;
} }
// 각 파일이 30MB 미만인지 검사 // 각 파일이 30MB 이하인지 검사
if (file.size < MAX_SIZE) { if (file.size <= MAX_SIZE) {
validFiles.push(file); validFiles.push(file);
} else { } else {
oversizedFiles.push(file.name); oversizedFiles.push(file.name);
} }
}); });
// 30MB 이상인 파일이 있으면 알림 // 파일 타입 오류
if (invalidTypeFiles.length > 0) {
alert(`다음 파일은 ZIP 형식만 가능합니다:\n${invalidTypeFiles.join('\n')}`);
}
// 30MB 초과 파일이 있으면 알림
if (oversizedFiles.length > 0) { if (oversizedFiles.length > 0) {
alert(`다음 파일은 30MB 미만이어야 합니다:\n${oversizedFiles.join('\n')}`); alert(`다음 파일은 30MB 이하여야 합니다:\n${oversizedFiles.join('\n')}`);
} }
// 파일 개수 제한 확인 // 파일 개수 제한 확인
if (vrContentCount + validFiles.length > 10) { const totalCount = vrContentCount + validFiles.length;
alert('VR 콘텐츠는 최대 10개까지 첨부할 수 있습니다.'); 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 = ''; e.target.value = '';
return; return;
} }
@@ -771,10 +788,26 @@ export default function AdminLessonsPage() {
if (validFiles.length > 0) { if (validFiles.length > 0) {
try { try {
// 다중 파일 업로드 // 다중 파일 업로드
await apiService.uploadFiles(validFiles); const uploadResponse = await apiService.uploadFiles(validFiles);
setVrContentFiles(prev => [...prev, ...validFiles.map(f => f.name)]);
setVrContentFileObjects(prev => [...prev, ...validFiles]); // 응답에서 fileKey 배열 추출
setVrContentCount(prev => prev + validFiles.length); 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) { } catch (error) {
console.error('VR 콘텐츠 업로드 실패:', error); console.error('VR 콘텐츠 업로드 실패:', error);
alert('파일 업로드에 실패했습니다. 다시 시도해주세요.'); alert('파일 업로드에 실패했습니다. 다시 시도해주세요.');
@@ -808,6 +841,7 @@ export default function AdminLessonsPage() {
onClick={() => { onClick={() => {
setVrContentFiles(prev => prev.filter((_, i) => i !== index)); setVrContentFiles(prev => prev.filter((_, i) => i !== index));
setVrContentFileObjects(prev => prev.filter((_, i) => i !== index)); setVrContentFileObjects(prev => prev.filter((_, i) => i !== index));
setVrContentFileKeys(prev => prev.filter((_, i) => i !== index));
setVrContentCount(prev => prev - 1); setVrContentCount(prev => prev - 1);
}} }}
className="size-[16px] flex items-center justify-center cursor-pointer hover:opacity-70 transition-opacity shrink-0" 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() {
<span></span> <span></span>
<input <input
type="file" type="file"
accept=".csv" accept=".csv,text/csv,application/vnd.ms-excel"
className="hidden" className="hidden"
onChange={async (e) => { onChange={async (e) => {
const files = e.target.files; const files = e.target.files;
if (!files || files.length === 0) return; if (!files || files.length === 0) return;
const file = files[0]; const file = files[0];
// CSV 파일만 허용 // CSV 파일만 허용
if (file.name.toLowerCase().endsWith('.csv')) { if (!file.name.toLowerCase().endsWith('.csv')) {
try { alert('CSV 파일 형식만 첨부할 수 있습니다.');
// 단일 파일 업로드 e.target.value = '';
await apiService.uploadFile(file); return;
setQuestionFileObject(file);
setQuestionFileCount(1);
} catch (error) {
console.error('학습 평가 문제 업로드 실패:', error);
alert('파일 업로드에 실패했습니다. 다시 시도해주세요.');
}
} }
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 = '';
}} }}
/> />
</label> </label>

View File

@@ -0,0 +1,37 @@
export type Resource = {
id: number;
title: string;
date: string; // 게시일
views: number; // 조회수
writer: string; // 작성자
content?: string[]; // 본문 내용 (상세 페이지용)
hasAttachment?: boolean; // 첨부파일 여부
};
// TODO: 나중에 DB에서 가져오도록 변경
export const MOCK_RESOURCES: Resource[] = [
{
id: 2,
title: '학습 자료 제목이 노출돼요',
date: '2025-09-10',
views: 1230,
writer: '문지호',
content: [
'학습 자료 관련 주요 내용을 안내드립니다.',
'학습 자료는 수강 기간 동안 언제든지 다운로드 가능합니다.',
],
},
{
id: 1,
title: '📚 방사선학 학습 자료 모음',
date: '2025-06-28',
views: 594,
writer: '문지호',
hasAttachment: true,
content: [
'방사선학 강의에 필요한 학습 자료를 첨부합니다.',
'학습 자료는 강의 수강 시 참고하시기 바랍니다.',
],
},
];

View File

@@ -1,21 +1,103 @@
'use client'; 'use client';
import { useState, useMemo } from "react"; import { useState, useMemo, useRef, ChangeEvent } from "react";
import AdminSidebar from "@/app/components/AdminSidebar"; import AdminSidebar from "@/app/components/AdminSidebar";
import ChevronDownSvg from "@/app/svgs/chevrondownsvg"; import ChevronDownSvg from "@/app/svgs/chevrondownsvg";
import BackArrowSvg from "@/app/svgs/backarrow";
import { MOCK_RESOURCES, type Resource } from "@/app/admin/resources/mockData";
import apiService from "@/app/lib/apiService";
export default function AdminResourcesPage() { export default function AdminResourcesPage() {
// TODO: 나중에 실제 데이터로 교체 const [resources, setResources] = useState<Resource[]>(MOCK_RESOURCES);
const items: any[] = [];
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const [isWritingMode, setIsWritingMode] = useState(false);
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [attachedFile, setAttachedFile] = useState<File | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const totalCount = useMemo(() => resources.length, [resources]);
const characterCount = useMemo(() => content.length, [content]);
const handleBack = () => {
setIsWritingMode(false);
setTitle('');
setContent('');
setAttachedFile(null);
};
const handleFileAttach = () => {
fileInputRef.current?.click();
};
const handleFileChange = async (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
if (file.size > 30 * 1024 * 1024) {
alert('30MB 미만의 파일만 첨부할 수 있습니다.');
return;
}
try {
// 단일 파일 업로드
await apiService.uploadFile(file);
setAttachedFile(file);
} catch (error) {
console.error('파일 업로드 실패:', error);
alert('파일 업로드에 실패했습니다. 다시 시도해주세요.');
}
}
};
const handleSave = () => {
if (!title.trim()) {
alert('제목을 입력해주세요.');
return;
}
if (!content.trim()) {
alert('내용을 입력해주세요.');
return;
}
// 새 학습 자료 추가
const newResource: Resource = {
id: resources.length > 0 ? Math.max(...resources.map(r => r.id)) + 1 : 1,
title: title.trim(),
date: new Date().toISOString().split('T')[0],
views: 0,
writer: '관리자', // TODO: 실제 작성자 정보 사용
content: content.split('\n'),
hasAttachment: attachedFile !== null,
};
setResources([newResource, ...resources]);
handleBack();
};
const handleCancel = () => {
if (title.trim() || content.trim() || attachedFile) {
if (confirm('작성 중인 내용이 있습니다. 정말 취소하시겠습니까?')) {
handleBack();
}
} else {
handleBack();
}
};
const ITEMS_PER_PAGE = 10; const ITEMS_PER_PAGE = 10;
const totalPages = Math.ceil(items.length / ITEMS_PER_PAGE); const sortedResources = useMemo(() => {
const paginatedItems = useMemo(() => { return [...resources].sort((a, b) => {
// 생성일 내림차순 정렬 (최신 날짜가 먼저)
return b.date.localeCompare(a.date);
});
}, [resources]);
const totalPages = Math.ceil(sortedResources.length / ITEMS_PER_PAGE);
const paginatedResources = useMemo(() => {
const startIndex = (currentPage - 1) * ITEMS_PER_PAGE; const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
const endIndex = startIndex + ITEMS_PER_PAGE; const endIndex = startIndex + ITEMS_PER_PAGE;
return items.slice(startIndex, endIndex); return sortedResources.slice(startIndex, endIndex);
}, [items, currentPage]); }, [sortedResources, currentPage]);
return ( return (
<div className="min-h-screen flex flex-col bg-white"> <div className="min-h-screen flex flex-col bg-white">
@@ -30,27 +112,219 @@ export default function AdminResourcesPage() {
{/* 메인 콘텐츠 */} {/* 메인 콘텐츠 */}
<main className="w-[1120px] bg-white"> <main className="w-[1120px] bg-white">
<div className="h-full flex flex-col px-8"> <div className="h-full flex flex-col px-8">
{/* 제목 영역 */} {isWritingMode ? (
<div className="h-[100px] flex items-center"> <>
<h1 className="text-[24px] font-bold leading-[1.5] text-[#1b2027]"> {/* 작성 모드 헤더 */}
<div className="h-[100px] flex items-center">
</h1> <div className="flex gap-3 items-center">
</div> <button
type="button"
onClick={handleBack}
className="flex items-center justify-center w-8 h-8 cursor-pointer"
aria-label="뒤로가기"
>
<BackArrowSvg width={32} height={32} />
</button>
<h1 className="text-[24px] font-bold leading-[1.5] text-[#1b2027]">
</h1>
</div>
</div>
{/* 콘텐츠 영역 */} {/* 작성 폼 */}
<div className="flex-1 pt-8 flex flex-col"> <div className="flex-1 flex flex-col gap-10 pb-20 pt-8 w-full">
{items.length === 0 ? ( <div className="flex flex-col gap-6 w-full">
{/* 제목 입력 */}
<div className="flex flex-col gap-2 items-start justify-center w-full">
<label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682] w-[100px]">
</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="제목을 입력해 주세요."
className="w-full h-[40px] px-3 py-2 rounded-[8px] border border-[#dee1e6] bg-white text-[16px] font-normal leading-[1.5] text-[#1b2027] placeholder:text-[#b1b8c0] focus:outline-none focus:ring-2 focus:ring-[#1f2b91] focus:border-transparent"
/>
</div>
{/* 내용 입력 */}
<div className="flex flex-col gap-2 items-start justify-center w-full">
<label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682] w-[100px]">
</label>
<div className="relative w-full">
<textarea
value={content}
onChange={(e) => {
const newContent = e.target.value;
if (newContent.length <= 1000) {
setContent(newContent);
}
}}
placeholder="내용을 입력해 주세요. (최대 1,000자 이내)"
className="w-full h-[320px] px-3 py-2 rounded-[8px] border border-[#dee1e6] bg-white text-[16px] font-normal leading-[1.5] text-[#1b2027] placeholder:text-[#b1b8c0] resize-none focus:outline-none focus:ring-2 focus:ring-[#1f2b91] focus:border-transparent"
/>
<div className="absolute bottom-3 right-3">
<p className="text-[13px] font-normal leading-[1.4] text-[#6c7682] text-right">
{characterCount}/1000
</p>
</div>
</div>
</div>
{/* 첨부 파일 */}
<div className="flex flex-col gap-2 items-start justify-center w-full">
<div className="flex items-center justify-between h-8 w-full">
<div className="flex items-center gap-3 flex-1 min-w-0">
<label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682] whitespace-nowrap">
{' '}
<span className="font-normal">
({attachedFile ? 1 : 0}/1)
</span>
</label>
<p className="text-[13px] font-normal leading-[1.4] text-[#8c95a1] whitespace-nowrap">
30MB
</p>
</div>
<button
type="button"
onClick={handleFileAttach}
className="h-[32px] w-[62px] px-[4px] py-[3px] rounded-[6px] border border-[#8c95a1] bg-white flex items-center justify-center cursor-pointer hover:bg-gray-50 transition-colors shrink-0"
>
<span className="text-[13px] font-medium leading-[1.4] text-[#4c5561] whitespace-nowrap">
</span>
</button>
<input
ref={fileInputRef}
type="file"
onChange={handleFileChange}
className="hidden"
accept="*/*"
/>
</div>
<div className="h-16 w-full rounded-[8px] border border-[#dee1e6] bg-gray-50 flex items-center justify-center">
{attachedFile ? (
<p className="text-[14px] font-normal leading-[1.5] text-[#1b2027]">
{attachedFile.name}
</p>
) : (
<p className="text-[14px] font-normal leading-[1.5] text-[#8c95a1] text-center">
.
</p>
)}
</div>
</div>
</div>
{/* 액션 버튼 */}
<div className="flex gap-3 items-center justify-end shrink-0 w-full">
<button
type="button"
onClick={handleCancel}
className="h-12 px-8 rounded-[10px] bg-[#f1f3f5] text-[16px] font-semibold leading-[1.5] text-[#4c5561] whitespace-nowrap hover:bg-[#e5e8eb] transition-colors cursor-pointer"
>
</button>
<button
type="button"
onClick={handleSave}
className="h-12 px-4 rounded-[10px] bg-[#1f2b91] text-[16px] font-semibold leading-[1.5] text-white whitespace-nowrap hover:bg-[#1a2478] transition-colors cursor-pointer"
>
</button>
</div>
</div>
</>
) : (
<>
{/* 제목 영역 */}
<div className="h-[100px] flex items-center">
<h1 className="text-[24px] font-bold leading-[1.5] text-[#1b2027]">
</h1>
</div>
{/* 헤더 영역 (제목과 콘텐츠 사이) */}
<div className="pt-2 pb-4 flex items-center justify-between">
<p className="text-[15px] font-medium leading-[1.5] text-[#333c47] whitespace-nowrap">
{totalCount}
</p>
<button
type="button"
onClick={() => setIsWritingMode(true)}
className="h-[40px] px-4 rounded-[8px] bg-[#1f2b91] text-[16px] font-semibold leading-[1.5] text-white whitespace-nowrap hover:bg-[#1a2478] transition-colors cursor-pointer"
>
</button>
</div>
{/* 콘텐츠 영역 */}
<div className="flex-1 pt-2 flex flex-col">
{resources.length === 0 ? (
<div className="rounded-lg border border-[#dee1e6] bg-white min-h-[400px] flex items-center justify-center"> <div className="rounded-lg border border-[#dee1e6] bg-white min-h-[400px] flex items-center justify-center">
<p className="text-[16px] font-medium leading-[1.5] text-[#333c47]"> <p className="text-[16px] font-medium leading-[1.5] text-[#333c47]">
. .
<br />
.
</p> </p>
</div> </div>
) : ( ) : (
<> <>
{/* TODO: 테이블 또는 리스트를 여기에 추가 */} <div className="rounded-[8px]">
<div className="w-full rounded-[8px] border border-[#dee1e6] overflow-visible">
<table className="min-w-full border-collapse">
<colgroup>
<col style={{ width: 80 }} />
<col />
<col style={{ width: 140 }} />
<col style={{ width: 120 }} />
<col style={{ width: 120 }} />
</colgroup>
<thead>
<tr className="h-12 bg-gray-50 text-left">
<th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]"></th>
<th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]"></th>
<th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]"></th>
<th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]"></th>
<th className="px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]"></th>
</tr>
</thead>
<tbody>
{paginatedResources.map((resource, index) => {
// 번호는 전체 목록에서의 순서 (정렬된 목록 기준)
const resourceNumber = sortedResources.length - (currentPage - 1) * ITEMS_PER_PAGE - index;
return (
<tr
key={resource.id}
className="h-12 hover:bg-[#F5F7FF] transition-colors"
>
<td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap text-center">
{resourceNumber}
</td>
<td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027]">
{resource.title}
</td>
<td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
{resource.date}
</td>
<td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
{resource.views.toLocaleString()}
</td>
<td className="border-t border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
{resource.writer}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
{/* 페이지네이션 - 10개 초과일 때만 표시 */} {/* 페이지네이션 - 10개 초과일 때만 표시 */}
{items.length > ITEMS_PER_PAGE && (() => { {resources.length > ITEMS_PER_PAGE && (() => {
// 페이지 번호를 10단위로 표시 // 페이지 번호를 10단위로 표시
const pageGroup = Math.floor((currentPage - 1) / 10); const pageGroup = Math.floor((currentPage - 1) / 10);
const startPage = pageGroup * 10 + 1; const startPage = pageGroup * 10 + 1;
@@ -134,7 +408,9 @@ export default function AdminResourcesPage() {
})()} })()}
</> </>
)} )}
</div> </div>
</>
)}
</div> </div>
</main> </main>
</div> </div>

View File

@@ -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<string[][]>([]);
const [headers, setHeaders] = useState<string[]>([]);
const [rows, setRows] = useState<string[][]>([]);
const [fileName, setFileName] = useState<string>('');
const fileInputRef = useRef<HTMLInputElement>(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<HTMLInputElement>) => {
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 (
<div className="flex flex-col gap-4">
{/* 파일 업로드 영역 */}
<div className="flex items-center gap-4">
<label className="h-[40px] px-4 py-2 border border-[#8c95a1] rounded-[8px] bg-white text-[16px] font-semibold leading-[1.5] text-[#4c5561] whitespace-nowrap hover:bg-gray-50 transition-colors cursor-pointer flex items-center justify-center">
<span>CSV </span>
<input
ref={fileInputRef}
type="file"
accept=".csv,text/csv,application/vnd.ms-excel"
className="hidden"
onChange={handleFileChange}
/>
</label>
{fileName && (
<div className="flex items-center gap-2">
<span className="text-[15px] font-medium leading-[1.5] text-[#1b2027]">
{fileName}
</span>
<button
type="button"
onClick={handleClear}
className="text-[14px] font-normal leading-[1.5] text-[#8c95a1] hover:text-[#4c5561] transition-colors cursor-pointer"
>
</button>
</div>
)}
</div>
{/* 표 영역 */}
{csvData.length > 0 && (
<div className="w-full border border-[#dee1e6] border-solid relative size-full bg-white">
<div className="content-stretch flex flex-col items-start justify-center relative size-full">
{/* 헤더 */}
<div className="bg-[#f1f8ff] content-stretch flex h-[48px] items-center overflow-clip relative shrink-0 w-full">
{headers.map((header, index) => {
const isLast = index === headers.length - 1;
return (
<div
key={index}
className={`border-[#dee1e6] border-[0px_1px_0px_0px] border-solid box-border content-stretch flex gap-[10px] h-full items-center justify-center px-[8px] py-[12px] relative shrink-0 ${
index === 0 ? 'w-[48px]' : index === 1 ? 'basis-0 grow min-h-px min-w-px' : 'w-[140px]'
}`}
>
<div className="flex flex-col font-['Pretendard:SemiBold',sans-serif] justify-center leading-[0] not-italic relative shrink-0 text-[#4c5561] text-[14px] text-nowrap">
<p className="leading-[1.5] whitespace-pre">{header || `${index + 1}`}</p>
</div>
</div>
);
})}
</div>
{/* 데이터 행 */}
{rows.map((row, rowIndex) => (
<div
key={rowIndex}
className="border-[#dee1e6] border-[1px_0px_0px] border-solid h-[48px] relative shrink-0 w-full"
>
<div className="content-stretch flex h-[48px] items-start overflow-clip relative rounded-[inherit] w-full">
{headers.map((_, colIndex) => {
const isLast = colIndex === headers.length - 1;
const cellValue = row[colIndex] || '';
return (
<div
key={colIndex}
className={`border-[#dee1e6] ${
isLast ? '' : 'border-[0px_1px_0px_0px]'
} border-solid box-border content-stretch flex flex-col gap-[4px] ${
colIndex === 0
? 'items-center justify-center w-[48px] px-[8px] py-[12px]'
: 'items-center min-h-px min-w-px px-[8px] py-[12px]'
} ${
colIndex === 1 ? 'basis-0 grow' : ''
} relative shrink-0`}
>
<p className="font-['Pretendard:Medium',sans-serif] leading-[1.5] not-italic relative shrink-0 text-[#1b2027] text-[15px] text-nowrap whitespace-pre">
{cellValue}
</p>
</div>
);
})}
</div>
</div>
))}
</div>
</div>
)}
{/* 데이터가 없을 때 */}
{csvData.length === 0 && (
<div className="w-full rounded-[8px] border border-[#dee1e6] bg-white min-h-[200px] flex items-center justify-center">
<p className="text-[16px] font-medium leading-[1.5] text-[#333c47]">
CSV .
</p>
</div>
)}
</div>
);
}

View File

@@ -380,8 +380,8 @@ class ApiService {
subjectId: number; subjectId: number;
title: string; title: string;
objective: string; objective: string;
videoUrl?: string; videoUrl?: string | string[];
webglUrl?: string; webglUrl?: string | string[];
csvKey?: string; csvKey?: string;
}) { }) {
return this.request('/lectures', { return this.request('/lectures', {
@@ -390,6 +390,33 @@ class ApiService {
}); });
} }
/**
* 강좌(lecture) 수정
*/
async updateLecture(lectureId: string | number, lectureData: {
subjectId?: number;
title?: string;
objective?: string;
videoUrl?: string | string[];
webglUrl?: string | string[];
csvKey?: string;
csvUrl?: string;
}) {
return this.request(`/lectures/${lectureId}`, {
method: 'PATCH',
body: lectureData,
});
}
/**
* 강좌(lecture) 삭제
*/
async deleteLecture(lectureId: string | number) {
return this.request(`/lectures/${lectureId}`, {
method: 'DELETE',
});
}
/** /**
* 리소스 조회 * 리소스 조회
*/ */

View File

@@ -159,7 +159,8 @@ export default function LoginPage() {
} }
return ( return (
<div className="min-h-screen w-full flex flex-col items-center justify-between"> <>
<div className="min-h-screen w-full flex flex-col items-center pt-[180px]">
<LoginErrorModal <LoginErrorModal
open={isLoginErrorOpen} open={isLoginErrorOpen}
@@ -321,9 +322,10 @@ export default function LoginPage() {
</form> </form>
</div> </div>
<div></div> <div></div>
<p className="text-center py-[40px] text-[15px] text-basic-text">
Copyright 2025 XL LMS. All rights reserved
</p>
</div> </div>
<p className="text-center py-[40px] text-[15px] text-basic-text">
Copyright 2025 XL LMS. All rights reserved
</p>
</>
); );
} }

View File

@@ -0,0 +1,25 @@
import React from "react";
type DownloadIconProps = React.SVGProps<SVGSVGElement>;
export default function DownloadIcon(props: DownloadIconProps) {
return (
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
{...props}
>
<path
d="M12 3v12m0 0l-4-4m4 4l4-4M5 21h14"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
);
}