diff --git a/app/admin-login/page.tsx b/app/admin-login/page.tsx new file mode 100644 index 0000000..ed8da3b --- /dev/null +++ b/app/admin-login/page.tsx @@ -0,0 +1,9 @@ +import LoginCard from "@/components/login-card" + +export default function AdminLoginPage() { + return ( +
+ +
+ ) +} diff --git a/app/admin-signup/page.tsx b/app/admin-signup/page.tsx index cdce291..5e38521 100644 --- a/app/admin-signup/page.tsx +++ b/app/admin-signup/page.tsx @@ -1,10 +1,8 @@ -"use client"; - import AdminSignupForm from "@/components/admin-signup-form"; export default function AdminSignupPage() { return ( -
+
); diff --git a/app/admin/results/[entryCode]/[participantId]/page.tsx b/app/admin/results/[entryCode]/[participantId]/page.tsx index 3a676ea..1840099 100644 --- a/app/admin/results/[entryCode]/[participantId]/page.tsx +++ b/app/admin/results/[entryCode]/[participantId]/page.tsx @@ -16,6 +16,7 @@ export default function ParticipantEvaluationPage() { const searchParams = useSearchParams(); const from = searchParams.get("from"); const sessionId = searchParams.get("sessionId"); + const participantName = searchParams.get("participantName") ?? undefined; const decodedEntryCode = decodeURIComponent(entryCode); @@ -36,12 +37,11 @@ export default function ParticipantEvaluationPage() { }; return ( -
- -
+ ); } diff --git a/app/admin/results/[entryCode]/page.tsx b/app/admin/results/[entryCode]/page.tsx index d3509ac..b143653 100644 --- a/app/admin/results/[entryCode]/page.tsx +++ b/app/admin/results/[entryCode]/page.tsx @@ -1,24 +1,24 @@ // app/admin/results/[entryCode]/page.tsx +// Next.js 15+ / 16: 동적 라우트의 params는 Promise — 반드시 await 후 사용 import { ParticipantListContent } from "@/components/participant-list-content"; type ResultParticipantsPageProps = { - params: { - entryCode: string; - }; + params: Promise<{ entryCode: string }>; }; -// ⚠️ 맨 위에 "use client" 가 있었다면 삭제해주세요. -// 이 파일은 서버 컴포넌트로 두는게 편합니다. - -export default function ResultParticipantsPage({ +export default async function ResultParticipantsPage({ params, }: ResultParticipantsPageProps) { - // Next.js 동적 세그먼트에서 받은 값 - const rawEntryCode = params?.entryCode ?? ""; + const { entryCode: rawEntryCode } = await params; + const safe = rawEntryCode ?? ""; + let decodedEntryCode = safe; - // 혹시 인코딩 되어 있을 수 있으니 decode - const decodedEntryCode = decodeURIComponent(rawEntryCode); + try { + decodedEntryCode = decodeURIComponent(safe); + } catch { + decodedEntryCode = safe; + } return ; } diff --git a/app/master/layout.tsx b/app/master/layout.tsx index 7edc1bf..da6ac73 100644 --- a/app/master/layout.tsx +++ b/app/master/layout.tsx @@ -1,16 +1,7 @@ -import type React from "react" -import type { ReactNode } from "react"; +import type { ReactNode } from "react" import type { Metadata } from "next" -import { Geist, Geist_Mono } from "next/font/google" -import { Analytics } from "@vercel/analytics/next" -import "../globals.css" -import { Sidebar } from "@/components/sidebar"; -import { TopNavBar } from "@/components/top-nav-bar"; +import { Sidebar } from "@/components/sidebar" -const _geist = Geist({ subsets: ["latin"] }) -const _geistMono = Geist_Mono({ subsets: ["latin"] }) - -// Updated metadata for Master Dashboard export const metadata: Metadata = { title: "Master Dashboard - AI Vibe Coding Test", description: "Admin dashboard for AI Vibe Coding Test platform", @@ -34,23 +25,23 @@ export const metadata: Metadata = { }, } -export default function RootLayout({ +export default function MasterLayout({ children, }: Readonly<{ - children: React.ReactNode + children: ReactNode }>) { return ( -
- {/* 왼쪽 고정 사이드바 */} - +
+
+ +
- {/* 오른쪽 영역(상단바 + 페이지 내용) */} -
- -
- {children} -
+
+
{children}
- ); + ) } diff --git a/app/master/test-sessions/[ID]/page.tsx b/app/master/test-sessions/[ID]/page.tsx index 9814d6d..2583db2 100644 --- a/app/master/test-sessions/[ID]/page.tsx +++ b/app/master/test-sessions/[ID]/page.tsx @@ -1,29 +1,18 @@ -"use client"; +"use client" -import { useRouter, useParams } from "next/navigation"; -import TestSessionDetailsContent from "@/components/test-session-details-content"; +import { useParams, useRouter } from "next/navigation" +import TestSessionDetailsContent from "@/components/test-session-details-content" +import { parseExamIdParam } from "@/lib/master-test-sessions" export default function Page() { - const router = useRouter(); - const params = useParams<{ id: string }>(); - const sessionId = params?.id; - - // 임시 더미 데이터 (나중에 실제 API 연동 시 여기만 교체) - const session = { - id: Number(sessionId), - sessionId: `SESSION-${sessionId}`, // ➜ Session ID - createdBy: "Master Admin", // ➜ Created By - createdAt: "2025-12-05 10:00", // ➜ Created At - status: "Completed", // ➜ Status (Active / Completed 등) - participants: 48, // ➜ Participants - }; + const router = useRouter() + const params = useParams<{ ID?: string; id?: string }>() + const examId = parseExamIdParam(params?.ID ?? params?.id) return ( -
- router.push("/master/test-sessions")} - /> -
- ); + router.push("/master/test-sessions")} + /> + ) } diff --git a/app/master/test-sessions/[ID]/participants/[participantId]/page.tsx b/app/master/test-sessions/[ID]/participants/[participantId]/page.tsx new file mode 100644 index 0000000..f399967 --- /dev/null +++ b/app/master/test-sessions/[ID]/participants/[participantId]/page.tsx @@ -0,0 +1,41 @@ +"use client" + +import { useParams, useRouter, useSearchParams } from "next/navigation" +import { ParticipantEvaluationContent } from "@/components/participant-evaluation-content" +import { parseExamIdParam } from "@/lib/master-test-sessions" + +export default function MasterParticipantEvaluationPage() { + const router = useRouter() + const params = useParams<{ ID?: string; id?: string; participantId: string }>() + const searchParams = useSearchParams() + + const examId = parseExamIdParam(params?.ID ?? params?.id) + const participantId = String(params?.participantId ?? "") + const participantName = searchParams.get("participantName") ?? undefined + + const handleBack = () => { + if (examId != null) { + router.push(`/master/test-sessions/${examId}`) + } else { + router.push("/master/test-sessions") + } + } + + if (examId == null || !participantId.trim()) { + return ( +
+

세션 또는 참가자 정보를 찾을 수 없습니다.

+
+ ) + } + + return ( + + ) +} diff --git a/app/test/page.tsx b/app/test/page.tsx index da684f8..40e12e4 100644 --- a/app/test/page.tsx +++ b/app/test/page.tsx @@ -1,7 +1,114 @@ "use client"; +import { useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; import UserTestScreen from "@/components/user-test-screen" +import { useExamSessionStore } from "@/lib/stores/exam-session-store"; +import { getActiveSession, getActiveSessionByExam } from "@/lib/api/exams"; export default function TestPage() { + const router = useRouter(); + const [isRestoring, setIsRestoring] = useState(true); + const [restoreError, setRestoreError] = useState(null); + const examId = useExamSessionStore((state) => state.examId); + const participantId = useExamSessionStore((state) => state.participantId); + + useEffect(() => { + let cancelled = false; + let redirectTimeoutId: ReturnType | undefined; + + const scheduleRedirect = () => { + if (redirectTimeoutId !== undefined) { + clearTimeout(redirectTimeoutId); + } + redirectTimeoutId = setTimeout(() => { + if (!cancelled) { + router.replace("/"); + } + }, 1200); + }; + + const restoreSession = async () => { + const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + + // 시험 시작 직후(관리자 start 직후)에는 서버가 아직 "RUNNING/active-session"으로 + // 판단되기 전에 FE가 먼저 조회할 수 있어 404(NO_ACTIVE_SESSION)가 일시적으로 발생할 수 있다. + // 이 경우 즉시 entry로 튕기지 말고 짧게 재시도 후 실패 시에만 리다이렉트한다. + const maxAttempts = 6; // 총 5~6초 내 재시도 + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + if (cancelled) return; + + try { + const currentExamId = useExamSessionStore.getState().examId; + const activeSession = currentExamId + ? await getActiveSessionByExam(currentExamId) + : await getActiveSession(); + if (cancelled) return; + + if (activeSession) { + const current = useExamSessionStore.getState(); + useExamSessionStore.setState({ + examId: activeSession.examId, + participantId: activeSession.participantId ?? current.participantId, + examParticipantId: activeSession.examParticipantId, + tokenLimit: activeSession.tokenLimit, + }); + return; + } + + if (attempt === maxAttempts) { + setRestoreError("활성 시험 세션이 없습니다. 다시 입장해주세요."); + scheduleRedirect(); + return; + } + + await sleep(300 + attempt * 250); + if (cancelled) return; + } catch (error: any) { + if (cancelled) return; + // 인증 실패(쿠키 누락/만료)는 재시도해도 의미 없으므로 즉시 리다이렉트 + if (error?.status === 401) { + setRestoreError("인증이 필요합니다. 다시 입장해주세요."); + scheduleRedirect(); + return; + } + + console.error("[TestPage] active session restore failed:", error); + + if (attempt === maxAttempts) { + setRestoreError("세션 복구에 실패했습니다. 다시 입장해주세요."); + scheduleRedirect(); + return; + } + + await sleep(300 + attempt * 250); + if (cancelled) return; + } + } + }; + + void restoreSession().finally(() => { + if (!cancelled) setIsRestoring(false); + }); + return () => { + cancelled = true; + if (redirectTimeoutId !== undefined) { + clearTimeout(redirectTimeoutId); + } + }; + }, [router]); + + if (isRestoring || !examId || !participantId) { + return ( +
+
+

+ {restoreError ?? "시험 세션을 복구하는 중입니다..."} +

+
+
+ ); + } + return } diff --git a/components/admin-accounts-content.tsx b/components/admin-accounts-content.tsx index 4e39ee4..14da240 100644 --- a/components/admin-accounts-content.tsx +++ b/components/admin-accounts-content.tsx @@ -1,7 +1,7 @@ "use client" -import { useState, useEffect } from "react" -import { MoreHorizontal, Copy, Check, Eye, Power, RotateCcw, KeyRound, Trash2, EyeOff } from "lucide-react" +import { useState, useEffect, type CSSProperties } from "react" +import { MoreHorizontal, Copy, Check, Eye, Power, RotateCcw, Trash2 } from "lucide-react" import { Button } from "@/components/ui/button" import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table" @@ -19,109 +19,100 @@ import { Input } from "@/components/ui/input" import { ScrollArea } from "@/components/ui/scroll-area" import { useToast } from "@/hooks/use-toast" import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet" -import { Separator } from "@/components/ui/separator" -import { getAllAdmins, AdminInfo, LoginFailedError, NetworkError, issueAdminNumber, updateAdminNumber, AdminNumberUpdateRequest, toggleAdminNumberActive, AdminNumberDto } from "@/lib/api/admin" -import { isMasterAdmin, isSystemMasterAdmin, SYSTEM_MASTER_ADMIN_NUMBER } from "@/lib/auth/utils" +import { + fetchMasterAdminAccounts, + issueMasterAdminNumber, + updateMasterAdminAccountStatus, + resetMasterAdminPassword, + deleteMasterAdminAccount, + sortMasterAdminAccounts, + LoginFailedError, + NetworkError, + type MasterAdminAccount, +} from "@/lib/api/master-admin-accounts" +import { isMasterAdmin, isSystemMasterAdmin } from "@/lib/auth/utils" import { useRouter } from "next/navigation" +import { AdminPageHeader } from "@/components/admin-page-header" -type Admin = AdminInfo & { - status?: string; // UI 표시용: "활성화" | "비활성화" - lastLogin?: string; - createdAt?: string; - secretKey?: string; - lastKeyIssued?: string; -} - -function generateSecretKey(): string { - const chars = "abcdefghijklmnopqrstuvwxyz0123456789" - let key = "sk_prod_" - for (let i = 0; i < 22; i++) { - key += chars.charAt(Math.floor(Math.random() * chars.length)) - } - return key +function displayValue(value: string | null | undefined): string { + return value && value.trim() ? value : "-" } -function generateTempPassword(): string { - const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" - let password = "temp-" - for (let i = 0; i < 5; i++) { - password += chars.charAt(Math.floor(Math.random() * chars.length)) +/** 관리자 계정 상태 Badge (활성=초록, 비활성=빨간 계열) */ +function adminAccountStatusBadgeStyle(status: MasterAdminAccount["status"]): CSSProperties { + if (status === "활성화") { + return { backgroundColor: "#DCFCE7", color: "#166534" } } - password += "!" - password += chars.charAt(Math.floor(Math.random() * 26)) // Add a letter at the end - return password + return { backgroundColor: "#FEE2E2", color: "#DC2626" } } export function AdminAccountsContent() { - const [adminUsers, setAdminUsers] = useState([]) + const [adminUsers, setAdminUsers] = useState([]) const [isLoading, setIsLoading] = useState(true) + const [listError, setListError] = useState(null) const [isGenerateModalOpen, setIsGenerateModalOpen] = useState(false) const [generatedKey, setGeneratedKey] = useState("") const [copied, setCopied] = useState(false) - const [selectedAdmin, setSelectedAdmin] = useState(null) + const [selectedAdmin, setSelectedAdmin] = useState(null) const [isChangeStatusOpen, setIsChangeStatusOpen] = useState(false) const [isResetPasswordOpen, setIsResetPasswordOpen] = useState(false) const [isResetPasswordResultOpen, setIsResetPasswordResultOpen] = useState(false) const [tempPassword, setTempPassword] = useState("") const [tempPasswordCopied, setTempPasswordCopied] = useState(false) - const [isReissueKeyOpen, setIsReissueKeyOpen] = useState(false) - const [isReissueKeyResultOpen, setIsReissueKeyResultOpen] = useState(false) - const [reissuedSecretKey, setReissuedSecretKey] = useState("") - const [reissuedKeyCopied, setReissuedKeyCopied] = useState(false) const [isDeleteAdminOpen, setIsDeleteAdminOpen] = useState(false) const [isDetailsOpen, setIsDetailsOpen] = useState(false) - const [showSecretKey, setShowSecretKey] = useState(false) - const [detailsKeyCopied, setDetailsKeyCopied] = useState(false) const [isChangingStatus, setIsChangingStatus] = useState(false) + const [isResettingPassword, setIsResettingPassword] = useState(false) + const [isDeletingAdmin, setIsDeletingAdmin] = useState(false) const { toast } = useToast() const router = useRouter() - // 관리자 목록 조회 함수 const fetchAdmins = async () => { - setIsLoading(true); + setIsLoading(true) + setListError(null) try { - const response = await getAllAdmins(); - // 백엔드 AdminInfo를 Admin 타입으로 변환 - const admins: Admin[] = response.admins.map((admin) => ({ - ...admin, - status: "활성화", // 백엔드에 상태 필드가 없으면 기본값 - lastLogin: "-", // 백엔드에 마지막 로그인 필드가 없으면 기본값 - createdAt: "-", // 백엔드에 생성일 필드가 없으면 기본값 - })); - setAdminUsers(admins); + const { admins } = await fetchMasterAdminAccounts() + setAdminUsers(admins) } catch (error) { + setAdminUsers([]) if (error instanceof LoginFailedError) { - if (error.message.includes('인증')) { + const message = error.message || "관리자 목록 조회에 실패했습니다." + setListError(message) + if (error.message.includes("인증")) { toast({ title: "인증 오류", description: "다시 로그인해주세요.", variant: "destructive", - }); - router.push("/"); + }) + router.push("/") } else { toast({ title: "조회 실패", - description: error.message, + description: message, variant: "destructive", - }); + }) } } else if (error instanceof NetworkError) { + const message = error.message + setListError(message) toast({ title: "네트워크 오류", - description: error.message, + description: message, variant: "destructive", - }); + }) } else { + const message = "관리자 목록을 불러오는 중 오류가 발생했습니다." + setListError(message) toast({ title: "오류", - description: "관리자 목록을 불러오는 중 오류가 발생했습니다.", + description: message, variant: "destructive", - }); + }) } } finally { - setIsLoading(false); + setIsLoading(false) } - }; + } // 관리자 목록 조회 useEffect(() => { @@ -149,7 +140,7 @@ export function AdminAccountsContent() { if (!generatedKey) { // 관리자 번호 발급 API 호출 try { - const response = await issueAdminNumber({ + const response = await issueMasterAdminNumber({ label: undefined, expiresAt: undefined, }) @@ -187,7 +178,7 @@ export function AdminAccountsContent() { } } - const handleOpenChangeStatus = (admin: Admin) => { + const handleOpenChangeStatus = (admin: MasterAdminAccount) => { // MASTER-0001 보호 로직 if (isSystemMasterAdmin({ adminNumber: admin.adminNumber })) { toast({ @@ -203,7 +194,7 @@ export function AdminAccountsContent() { } // 공용 상태 변경 핸들러 (모달에서 확인 버튼을 누른 후 호출됨) - const handleToggleStatus = async (admin: Admin) => { + const handleToggleStatus = async (admin: MasterAdminAccount) => { // MASTER-0001 보호 로직 (이중 체크) if (isSystemMasterAdmin({ adminNumber: admin.adminNumber })) { toast({ @@ -218,47 +209,24 @@ export function AdminAccountsContent() { setIsChangingStatus(true); try { - // 현재 상태를 기반으로 active 값 추론 - const currentActive = admin.status === "활성화"; - - // AdminNumberDto 구성 (status 기반으로 active 추론) - const adminNumberDto: AdminNumberDto = { - adminNumber: admin.adminNumber, - label: undefined, - active: currentActive, - issuedBy: 0, // 실제 값은 필요 없음 (API에서 사용하지 않음) - assignedAdminId: admin.id, - expiresAt: undefined, - usedAt: undefined, - createdAt: "", - }; - - // toggleAdminNumberActive 호출 - const updated = await toggleAdminNumberActive(adminNumberDto); + const updated = await updateMasterAdminAccountStatus(admin) - // 성공 시 목록(state) 즉시 업데이트 setAdminUsers((prevUsers) => prevUsers.map((user) => - user.adminNumber === admin.adminNumber - ? { ...user, status: updated.active ? "활성화" : "비활성화" } - : user + user.adminNumber === admin.adminNumber ? updated : user ) - ); + ) - // 상세 패널이 열려 있으면 selectedAdmin도 업데이트 if (selectedAdmin && selectedAdmin.adminNumber === admin.adminNumber) { - setSelectedAdmin({ - ...selectedAdmin, - status: updated.active ? "활성화" : "비활성화", - }); + setSelectedAdmin(updated) } toast({ title: "상태 변경 성공", - description: updated.active + description: updated.isActive ? "관리자 계정이 활성화되었습니다." : "관리자 계정이 비활성화되었습니다.", - }); + }) setIsChangeStatusOpen(false); setSelectedAdmin(null); @@ -292,9 +260,8 @@ export function AdminAccountsContent() { await handleToggleStatus(selectedAdmin); } - const handleOpenResetPassword = (admin: Admin) => { - // MASTER-0001 보호 로직 - if (isSystemMasterAdmin({ adminNumber: admin.adminNumber })) { + const handleOpenResetPassword = (admin: MasterAdminAccount) => { + if (isSystemMasterAdmin({ adminNumber: admin.adminNumber }) || admin.role === "MASTER") { toast({ title: "변경 불가", description: "마스터 관리자 계정은 비밀번호를 재설정할 수 없습니다.", @@ -307,12 +274,29 @@ export function AdminAccountsContent() { setIsResetPasswordOpen(true) } - const handleConfirmResetPassword = () => { - const newTempPassword = generateTempPassword() - setTempPassword(newTempPassword) - setTempPasswordCopied(false) - setIsResetPasswordOpen(false) - setIsResetPasswordResultOpen(true) + const handleConfirmResetPassword = async () => { + if (!selectedAdmin) return + + setIsResettingPassword(true) + try { + const { temporaryPassword } = await resetMasterAdminPassword(selectedAdmin) + setTempPassword(temporaryPassword) + setTempPasswordCopied(false) + setIsResetPasswordOpen(false) + setIsResetPasswordResultOpen(true) + } catch (error) { + const message = + error instanceof LoginFailedError || error instanceof NetworkError + ? error.message + : "비밀번호 재설정에 실패했습니다." + toast({ + title: "비밀번호 재설정 불가", + description: message, + variant: "destructive", + }) + } finally { + setIsResettingPassword(false) + } } const handleCopyTempPassword = async () => { @@ -324,75 +308,14 @@ export function AdminAccountsContent() { setTimeout(() => setTempPasswordCopied(false), 2000) } - const handleOpenReissueKey = (admin: Admin) => { - // MASTER-0001 보호 로직 - if (isSystemMasterAdmin({ adminNumber: admin.adminNumber })) { - toast({ - title: "변경 불가", - description: "마스터 관리자 계정은 시크릿 키를 재발급할 수 없습니다.", - variant: "destructive", - }); - return; - } - - setSelectedAdmin(admin) - setIsReissueKeyOpen(true) - } - - const formatDateToKorean = (date: Date) => { - const year = date.getFullYear() - const month = date.getMonth() + 1 - const day = date.getDate() - const hours = date.getHours() - const minutes = date.getMinutes() - const ampm = hours >= 12 ? "오후" : "오전" - const displayHours = hours % 12 || 12 - const displayMinutes = minutes.toString().padStart(2, "0") - return `${year}년 ${month}월 ${day}일 ${ampm} ${displayHours}:${displayMinutes}` - } - - const handleConfirmReissueKey = () => { - const randomStr = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 11) - const newKey = `sk_prod_${randomStr}` - setReissuedSecretKey(newKey) - - // Update the admin user's secret key and lastKeyIssued date - if (selectedAdmin) { - const now = new Date() - const koreanDate = formatDateToKorean(now) - setAdminUsers((prevUsers) => - prevUsers.map((user) => - user.id === selectedAdmin.id - ? { ...user, secretKey: newKey, lastKeyIssued: koreanDate } - : user - ) - ) - // Update selectedAdmin to reflect the changes - setSelectedAdmin((prev) => prev ? { - ...prev, - secretKey: newKey, - lastKeyIssued: koreanDate, - } : null) - } - - setIsReissueKeyOpen(false) - setIsReissueKeyResultOpen(true) - setReissuedKeyCopied(false) - } - - const copyReissuedKey = async () => { - await navigator.clipboard.writeText(reissuedSecretKey) - setReissuedKeyCopied(true) - toast({ - title: "Secret key copied to clipboard", - duration: 2000, - }) - setTimeout(() => setReissuedKeyCopied(false), 2000) + const handleCloseResetPasswordResult = () => { + setIsResetPasswordResultOpen(false) + setTempPassword("") + setTempPasswordCopied(false) } - const handleOpenDeleteAdmin = (admin: Admin) => { - // MASTER-0001 보호 로직 - if (isSystemMasterAdmin({ adminNumber: admin.adminNumber })) { + const handleOpenDeleteAdmin = (admin: MasterAdminAccount) => { + if (isSystemMasterAdmin({ adminNumber: admin.adminNumber }) || admin.role === "MASTER") { toast({ title: "삭제 불가", description: "마스터 관리자 계정은 삭제할 수 없습니다.", @@ -405,40 +328,48 @@ export function AdminAccountsContent() { setIsDeleteAdminOpen(true) } - const handleConfirmDeleteAdmin = () => { - if (selectedAdmin) { + const handleConfirmDeleteAdmin = async () => { + if (!selectedAdmin) return + setIsDeletingAdmin(true) + try { + await deleteMasterAdminAccount(selectedAdmin) setAdminUsers((prev) => prev.filter((a) => a.id !== selectedAdmin.id)) setIsDeleteAdminOpen(false) + setIsDetailsOpen(false) + setSelectedAdmin(null) + toast({ + title: "관리자 삭제 완료", + description: "관리자 계정이 삭제되었습니다.", + }) + } catch (error) { + const message = + error instanceof LoginFailedError || error instanceof NetworkError + ? error.message + : "관리자 삭제에 실패했습니다." + toast({ + title: "관리자 삭제 불가", + description: message, + variant: "destructive", + }) + } finally { + setIsDeletingAdmin(false) } } - const handleOpenDetails = (admin: Admin) => { + const handleOpenDetails = (admin: MasterAdminAccount) => { setSelectedAdmin(admin) - setShowSecretKey(false) - setDetailsKeyCopied(false) setIsDetailsOpen(true) } - const handleCopyDetailsKey = async () => { - if (selectedAdmin) { - // 시크릿 키는 백엔드에 없는 필드이므로 임시로 관리자 번호 복사 - await navigator.clipboard.writeText(selectedAdmin.adminNumber) - setDetailsKeyCopied(true) - toast({ - description: "관리자 번호가 클립보드에 복사되었습니다.", - }) - setTimeout(() => setDetailsKeyCopied(false), 2000) - } - } - const handleChangeStatusFromPanel = () => { setIsDetailsOpen(false) setIsChangeStatusOpen(true) } const handleResetPasswordFromPanel = () => { + if (!selectedAdmin) return setIsDetailsOpen(false) - setIsResetPasswordOpen(true) + handleOpenResetPassword(selectedAdmin) } const handleDeleteAdminFromPanel = () => { @@ -447,29 +378,13 @@ export function AdminAccountsContent() { } return ( -
- {/* Page Header */} -
-

- 관리자 계정 관리 -

-

- 관리자 계정과 접근 권한을 관리합니다. -

-
+
+ +
{/* Admin Users Card */} @@ -496,6 +411,14 @@ export function AdminAccountsContent() { + {listError && !isLoading && ( +

+ {listError} +

+ )} @@ -522,7 +445,7 @@ export function AdminAccountsContent() { 이메일 ) : ( - adminUsers.map((user) => { + sortMasterAdminAccounts(adminUsers).map((user) => { const isMaster = isMasterAdmin({ adminNumber: user.adminNumber, role: user.role, }); - const isSystemMaster = isSystemMasterAdmin({ adminNumber: user.adminNumber }); + const isSystemMaster = + isSystemMasterAdmin({ adminNumber: user.adminNumber }) || + user.role === "MASTER"; return ( @@ -623,45 +548,52 @@ export function AdminAccountsContent() { > {user.email} - - - {user.role === "MASTER" ? "마스터" : "관리자"} - + +
+ + {user.role === "MASTER" ? "마스터" : "관리자"} + +
- - - {user.status} - + +
+ + {user.status} + +
- - {user.lastLogin} - - - + + {displayValue(user.lastLogin)} + + +
+
+
+
); }) )} @@ -919,24 +847,26 @@ export function AdminAccountsContent() { fontSize: "14px", color: "#6B7280", marginBottom: "12px", + lineHeight: "1.6", }} > - 관리자의 다음 로그인을 위해 임시 비밀번호가 생성됩니다. + 해당 관리자의 비밀번호를 임시 비밀번호로 재설정하시겠습니까?

- 이 관리자의 비밀번호를 재설정하시겠습니까? + 생성된 임시 비밀번호는 한 번만 표시됩니다. 관리자에게 안전하게 전달한 뒤, 해당 관리자는 설정 화면에서 본인이 직접 비밀번호를 변경할 수 있습니다.

{/* Modal — Temporary password generated (result) */} - + { + if (!open) handleCloseResetPasswordResult() + }} + > - 이 비밀번호를 복사하여 관리자에게 안전하게 전달해주세요. + 이 비밀번호는 한 번만 표시됩니다. 모달을 닫으면 다시 확인할 수 없습니다.
@@ -1019,7 +956,7 @@ export function AdminAccountsContent() {
- {/* Modal — Reissue Secret Key confirmation dialog */} - - - - - Reissue Secret Key - - -
-

- The current secret key will be invalidated and replaced with a new one. Do you want to continue? -

-
- - - - -
-
- - {/* Modal — Reissue Secret Key result dialog */} - - - - - New Secret Key Issued - - -
-

- This secret key will only be shown once. Please copy and store it safely. -

-
- -
- - -
-
-
- - - -
-
- {/* Modal — Delete Admin confirmation dialog */} - Delete Admin + 관리자 삭제

- Are you sure you want to permanently delete this admin? + 해당 관리자 계정을 삭제하시겠습니까?

-

This action cannot be undone.

+

삭제된 계정은 복구할 수 없습니다.

{selectedAdmin && ( @@ -1113,14 +993,18 @@ export function AdminAccountsContent() {
)} -

All access for this admin will be removed immediately.

+

해당 관리자의 접근 권한이 즉시 제거됩니다.

-
@@ -1145,28 +1029,9 @@ export function AdminAccountsContent() {

관리자 번호

-
-

- {selectedAdmin?.adminNumber} -

- {selectedAdmin && isMasterAdmin({ - adminNumber: selectedAdmin.adminNumber, - role: selectedAdmin.role, - }) && ( - - MASTER - - )} -
+

+ {selectedAdmin?.adminNumber} +

역할

+
+

이름

+

+ {displayValue(selectedAdmin?.displayName)} +

+

이메일

@@ -1196,8 +1067,7 @@ export function AdminAccountsContent() { style={{ fontSize: "12px", fontWeight: 500, - backgroundColor: selectedAdmin?.status === "활성화" ? "#DCFCE7" : "#F3F4F6", - color: selectedAdmin?.status === "활성화" ? "#166534" : "#6B7280", + ...(selectedAdmin ? adminAccountStatusBadgeStyle(selectedAdmin.status) : {}), border: "none", }} > @@ -1207,69 +1077,13 @@ export function AdminAccountsContent() {

마지막 로그인

- {selectedAdmin?.lastLogin} + {displayValue(selectedAdmin?.lastLogin)}

생성일

- {selectedAdmin?.createdAt} -

-
-
-
- - - - {/* Security Settings Section */} -
-

보안 설정

-
-
-

비밀번호 상태

-

- 비밀번호 설정됨 -

-
-
-

시크릿 키

-
-
- {showSecretKey ? selectedAdmin?.adminNumber : "•••••••••••••••••••••"} -
- - -
-
-
-

마지막 시크릿 키 발급일

-

- {selectedAdmin?.lastKeyIssued} + {displayValue(selectedAdmin?.createdAt)}

@@ -1304,18 +1118,6 @@ export function AdminAccountsContent() { > 비밀번호 재설정 - -
+ ) } diff --git a/components/admin-page-header.tsx b/components/admin-page-header.tsx new file mode 100644 index 0000000..395253e --- /dev/null +++ b/components/admin-page-header.tsx @@ -0,0 +1,19 @@ +import type { ReactNode } from "react" + +export type AdminPageHeaderProps = { + title: string + description?: string + actions?: ReactNode +} + +export function AdminPageHeader({ title, description, actions }: AdminPageHeaderProps) { + return ( +
+
+

{title}

+ {description ?

{description}

: null} +
+ {actions ?
{actions}
: null} +
+ ) +} diff --git a/components/admin-sidebar.tsx b/components/admin-sidebar.tsx index 6ba0a73..a85e0cd 100644 --- a/components/admin-sidebar.tsx +++ b/components/admin-sidebar.tsx @@ -1,6 +1,6 @@ "use client" -import { useState } from "react" +import { useState, useEffect } from "react" import Link from "next/link" import { usePathname, useRouter } from "next/navigation" import { @@ -25,7 +25,7 @@ import { DialogTitle, } from "@/components/ui/dialog" import { Button } from "@/components/ui/button" -import { logoutAdmin } from "@/lib/api/admin" +import { getMe, logoutAdmin, resolveAdminDisplayNameFromMe } from "@/lib/api/admin" const menuGroupA = [ { icon: LayoutDashboard, label: "대시보드", href: "/admin/dashboard" }, @@ -74,6 +74,30 @@ export function AdminSidebar() { const router = useRouter() const [showLogoutModal, setShowLogoutModal] = useState(false) const [isLoggingOut, setIsLoggingOut] = useState(false) + const [displayName, setDisplayName] = useState("알 수 없음") + + useEffect(() => { + let cancelled = false + + const fetchAdminDisplayName = async () => { + try { + const response = await getMe() + if (!cancelled) { + setDisplayName(resolveAdminDisplayNameFromMe(response)) + } + } catch { + if (!cancelled) { + setDisplayName("관리자") + } + } + } + + fetchAdminDisplayName() + + return () => { + cancelled = true + } + }, []) const isActive = (href: string) => { if (href === "/") { @@ -124,7 +148,7 @@ export function AdminSidebar() {
- Admin + {displayName} 관리자
diff --git a/components/admin-signup-form.tsx b/components/admin-signup-form.tsx index 5480290..5414acf 100644 --- a/components/admin-signup-form.tsx +++ b/components/admin-signup-form.tsx @@ -3,7 +3,7 @@ import type React from "react" import { useState } from "react" - +import Link from "next/link" import { useRouter } from "next/navigation"; import { signUpAdmin, LoginFailedError, NetworkError } from "@/lib/api/admin" import { useToast } from "@/hooks/use-toast" @@ -11,6 +11,7 @@ import { useToast } from "@/hooks/use-toast" export default function AdminSignupForm() { const [formData, setFormData] = useState({ adminNumber: "", + displayName: "", email: "", password: "", confirmPassword: "", @@ -35,6 +36,10 @@ export default function AdminSignupForm() { setError("관리자 번호를 입력해주세요.") return } + if (!formData.displayName.trim()) { + setError("이름을 입력해주세요.") + return + } if (!formData.email.trim()) { setError("이메일을 입력해주세요.") return @@ -63,6 +68,7 @@ export default function AdminSignupForm() { try { await signUpAdmin({ adminNumber: formData.adminNumber.trim(), + displayName: formData.displayName.trim(), email: formData.email.trim(), password: formData.password.trim(), }) @@ -91,6 +97,13 @@ export default function AdminSignupForm() { return (
+ + ← 로그인으로 + + {/* Header */}

관리자 회원가입

@@ -110,6 +123,19 @@ export default function AdminSignupForm() { />
+ {/* Display Name */} +
+ + +
+ {/* Email Address */}
diff --git a/components/analytics-content.tsx b/components/analytics-content.tsx index 3116c36..96f0779 100644 --- a/components/analytics-content.tsx +++ b/components/analytics-content.tsx @@ -2,24 +2,30 @@ import { useState, useMemo, useEffect } from "react" import Link from "next/link" -import { Download, TrendingUp, TrendingDown, Minus, ChevronDown, X, CheckCircle } from "lucide-react" -import { getExams, getBoard, Exam, ExamineeBoardEntry } from "@/lib/api/admin" - -type Trend = "높음" | "보통" | "낮음" -type Status = "완료" | "진행 중" - -interface Participant { - id: string - name: string - entryCode: string - avgScore: number - status: Status - trend: Trend - sparklineData: number[] - testDate: Date - promptScore: number - performanceScore: number - correctnessScore: number +import { Download, ChevronDown, X, CheckCircle } from "lucide-react" +import { + getExams, + getBoard, + formatBoardSubmissionLabelKo, + type Exam, + type ExamineeBoardEntry, +} from "@/lib/api/admin" +import { + computeParticipantLetterGrade, + computeSessionAnalytics, + isExamineeBoardSubmitted, +} from "@/lib/admin-board-analytics" +import { + buildBoardParticipantsCsvBody, + downloadUtf8Csv, +} from "@/lib/admin-board-csv-export" +import { adminParticipantEvaluationHref } from "@/lib/paths/admin-participant-evaluation" + +interface BoardRow { + entry: ExamineeBoardEntry + examId: number + examTitle: string + examResultsSegment: string } interface Toast { @@ -28,128 +34,77 @@ interface Toast { description: string } -function mapBoardToParticipant(entry: ExamineeBoardEntry, examTitle: string): Participant { - const submitted = entry.submitted - // tokenUsed를 0~100 스케일로 정규화 (tokenLimit 기준) - const tokenRatio = - entry.tokenLimit > 0 ? Math.min(100, Math.round((entry.tokenUsed / entry.tokenLimit) * 100)) : 0 - - return { - id: entry.examParticipantId.toString(), - name: entry.name, - entryCode: examTitle, - avgScore: 0, // 채점 API 미연동 — 채점 완료 후 집계 예정 - status: submitted ? "완료" : "진행 중", - trend: "보통", - sparklineData: [0, tokenRatio], // 토큰 사용 추이 - testDate: new Date(), - promptScore: 0, - performanceScore: 0, - correctnessScore: 0, - } -} - -function Sparkline({ data, trend }: { data: number[]; trend: Trend }) { - const width = 100 - const height = 32 - const padding = 4 - - const min = Math.min(...data) - const max = Math.max(...data) - const range = max - min || 1 - - const points = data - .map((value, index) => { - const x = padding + (index / (data.length - 1)) * (width - padding * 2) - const y = height - padding - ((value - min) / range) * (height - padding * 2) - return `${x},${y}` - }) - .join(" ") - - const lineColor = trend === "높음" ? "#4AA785" : trend === "낮음" ? "#D6455D" : "#9CA3AF" - - return ( - - - - ) -} - -function TrendIcon({ trend }: { trend: Trend }) { - if (trend === "높음") { - return - } else if (trend === "낮음") { - return - } - return -} - -function StatusBadge({ status }: { status: Status }) { - const styles = status === "완료" ? "bg-[#DCFCE7] text-[#16A34A]" : "bg-[#E0E7FF] text-[#6366F1]" - return {status} -} - -function TrendBadge({ trend }: { trend: Trend }) { - const styles = { - "높음": "bg-[#DCFCE7] text-[#16A34A]", - "보통": "bg-[#F3F4F6] text-[#6B7280]", - "낮음": "bg-[#FEE2E2] text-[#DC2626]", - } - return {trend} -} - -function MetricCard({ label, value, suffix }: { label: string; value: string; suffix?: string }) { +function MetricCard({ + label, + value, + suffix, + isLoading, +}: { + label: string + value: string + suffix?: string + isLoading?: boolean +}) { + const display = isLoading ? "–" : value return (

{label}

- {value} - {suffix && {suffix}} + {display} + {suffix && !isLoading && ( + {suffix} + )}

) } -function ParticipantCard({ participant }: { participant: Participant }) { +function ParticipantCard({ row }: { row: BoardRow }) { + const { entry, examTitle, examResultsSegment } = row + const grade = computeParticipantLetterGrade(entry) + const statusLabel = formatBoardSubmissionLabelKo(entry) + + const gradeColor = + grade === "A" + ? "text-[#16A34A]" + : grade === "B" + ? "text-[#2563EB]" + : grade === "C" + ? "text-[#D97706]" + : grade === "D" + ? "text-[#EA580C]" + : grade === "F" + ? "text-[#DC2626]" + : "text-[#9CA3AF]" + return (
-
-
-

{participant.name}

-

{participant.entryCode}

+
+
+

{entry.name || "–"}

+

{examTitle}

-
- - +
+ + {grade} + + 등급
-
-
-
-

제출 상태

-
- {participant.status} - -
-
-
- +
+

제출 상태

+

{statusLabel}

상세 보기 → @@ -159,61 +114,121 @@ function ParticipantCard({ participant }: { participant: Participant }) { ) } +async function loadBoardRowsForExams(exams: Exam[]): Promise { + const boards = await Promise.all( + exams.map(async (exam) => { + try { + const entries = await getBoard(exam.id) + return entries.map((entry) => ({ + entry, + examId: exam.id, + examTitle: exam.title, + examResultsSegment: String(exam.id), + })) + } catch (e) { + console.error(`[Analytics] getBoard failed for examId=${exam.id}`, e) + return [] as BoardRow[] + } + }) + ) + return boards.flat() +} + export function AnalyticsContent() { const [exams, setExams] = useState([]) - const [participants, setParticipants] = useState([]) + const [boardRows, setBoardRows] = useState([]) const [isLoadingExams, setIsLoadingExams] = useState(true) const [isLoadingBoard, setIsLoadingBoard] = useState(false) + const [boardLoadError, setBoardLoadError] = useState(false) const [selectedExamId, setSelectedExamId] = useState("all") const [toasts, setToasts] = useState([]) - // 시험 목록 로드 useEffect(() => { + let cancelled = false async function loadExams() { try { const data = await getExams() - setExams(data) + if (!cancelled) setExams(data) } catch (e) { - console.error("Failed to load exams", e) + console.error("[Analytics] Failed to load exams", e) + if (!cancelled) setExams([]) } finally { - setIsLoadingExams(false) + if (!cancelled) setIsLoadingExams(false) } } loadExams() + return () => { + cancelled = true + } }, []) - // 선택된 시험 보드 로드 useEffect(() => { + if (isLoadingExams) return + + let cancelled = false + async function loadBoard() { - if (isLoadingExams) return setIsLoadingBoard(true) + setBoardLoadError(false) try { if (selectedExamId === "all") { - // 모든 시험의 보드를 병렬 조회 - const boards = await Promise.all( - exams.map((e) => - getBoard(e.id) - .then((entries) => entries.map((p) => mapBoardToParticipant(p, e.title))) - .catch(() => [] as Participant[]) - ) + if (exams.length === 0) { + if (!cancelled) setBoardRows([]) + return + } + const rows = await loadBoardRowsForExams(exams) + if (!cancelled) setBoardRows(rows) + return + } + + const examId = Number.parseInt(selectedExamId, 10) + if (Number.isNaN(examId)) { + if (!cancelled) setBoardRows([]) + return + } + + const exam = exams.find((e) => e.id === examId) + const board = await getBoard(examId) + if (!cancelled) { + setBoardRows( + board.map((entry) => ({ + entry, + examId, + examTitle: exam?.title ?? String(examId), + examResultsSegment: String(examId), + })) ) - setParticipants(boards.flat()) - } else { - const examId = parseInt(selectedExamId, 10) - const exam = exams.find((e) => e.id === examId) - const board = await getBoard(examId) - setParticipants(board.map((p) => mapBoardToParticipant(p, exam?.title ?? selectedExamId))) } } catch (e) { - console.error("Failed to load board", e) - setParticipants([]) + console.error("[Analytics] Failed to load board", e) + if (!cancelled) { + setBoardRows([]) + setBoardLoadError(true) + } } finally { - setIsLoadingBoard(false) + if (!cancelled) setIsLoadingBoard(false) } } + loadBoard() - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [selectedExamId, isLoadingExams]) + return () => { + cancelled = true + } + }, [selectedExamId, isLoadingExams, exams]) + + const entries = useMemo(() => boardRows.map((r) => r.entry), [boardRows]) + + const analytics = useMemo(() => computeSessionAnalytics(entries), [entries]) + + const submittedRows = useMemo( + () => boardRows.filter((r) => isExamineeBoardSubmitted(r.entry)), + [boardRows] + ) + + const inProgressRows = useMemo( + () => boardRows.filter((r) => !isExamineeBoardSubmitted(r.entry)), + [boardRows] + ) const showToast = (title: string, description: string) => { const id = crypto.randomUUID() @@ -228,29 +243,14 @@ export function AnalyticsContent() { } const handleExport = () => { - const csvContent = - "이름,시험,제출상태\n" + - participants.map((p) => `${p.name},${p.entryCode},${p.status}`).join("\n") - const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" }) - const url = URL.createObjectURL(blob) - const link = document.createElement("a") - link.href = url - link.download = "analytics-results.csv" - document.body.appendChild(link) - link.click() - document.body.removeChild(link) - URL.revokeObjectURL(url) - showToast("내보내기 시작", "통계 분석 결과가 CSV 파일로 다운로드되고 있습니다.") + const csvBody = buildBoardParticipantsCsvBody( + boardRows.map((r) => ({ entry: r.entry, examLabel: r.examTitle })) + ) + downloadUtf8Csv("analytics-results.csv", csvBody) + showToast("보내기 시작", "통계 분석 결과가 CSV 파일로 다운로드되고 있습니다.") } - const completedParticipants = useMemo( - () => participants.filter((p) => p.status === "완료"), - [participants] - ) - const inProgressParticipants = useMemo( - () => participants.filter((p) => p.status === "진행 중"), - [participants] - ) + const metricsLoading = isLoadingExams || isLoadingBoard return (
@@ -258,7 +258,7 @@ export function AnalyticsContent() {

통계 분석

- 모든 시험 세션의 참가자 현황 및 제출 상태를 시각화합니다. + 선택한 시험 세션의 참가자 현황·채점 점수를 집계합니다.

@@ -285,61 +285,81 @@ export function AnalyticsContent() {
- {/* 메트릭 카드 — 점수는 채점 완료 후 집계됨 */}
- - - - + + + +
- {/* 점수 미집계 안내 */} + {boardLoadError && ( +
+

+ 참가자 데이터를 불러오지 못했습니다. 잠시 후 다시 시도해 주세요. +

+
+ )} +

- 평가 점수는 채점 완료 후 집계됩니다. 현재는 참가자 현황 및 제출 상태를 기준으로 표시합니다. + 평균 점수는 채점이 완료된 참가자만 집계합니다. 채점 전이거나 점수가 없으면 "–"로 + 표시됩니다. 등급(A~F)은 종합 점수(또는 항목 점수 평균)를 100점 만점 기준으로 산정합니다.

- {isLoadingBoard ? ( + {metricsLoading ? (

불러오는 중...

- ) : participants.length === 0 ? ( + ) : boardRows.length === 0 ? (

조회된 참가자가 없습니다

시험 세션을 선택하거나 참가자를 확인해보세요.

) : ( <> - {completedParticipants.length > 0 && ( + {submittedRows.length > 0 && (

- 제출 완료 ({completedParticipants.length}명) + 제출 완료 ({submittedRows.length}명)

- {completedParticipants.map((participant) => ( - + {submittedRows.map((row) => ( + ))}
)} - {inProgressParticipants.length > 0 && ( + {inProgressRows.length > 0 && (

- 진행 중 ({inProgressParticipants.length}명) + 진행 중 ({inProgressRows.length}명)

- {inProgressParticipants.map((participant) => ( - + {inProgressRows.map((row) => ( + ))}
@@ -362,6 +382,7 @@ export function AnalyticsContent() {

{toast.description}

- )}
@@ -257,4 +265,4 @@ export function CodeEditorSection({
) -} +}) diff --git a/components/dashboard-content.tsx b/components/dashboard-content.tsx index 8700277..5286682 100644 --- a/components/dashboard-content.tsx +++ b/components/dashboard-content.tsx @@ -4,6 +4,7 @@ import { useState, useEffect } from "react" import Link from "next/link" import { Users, CheckCircle, Play, Plus, BarChart3, ArrowRight } from "lucide-react" import { getExams, getBoard } from "@/lib/api/admin" +import { computeSessionAnalytics } from "@/lib/admin-board-analytics" // Sample recent activity data (정적 - 활동 로그 API 미지원) const recentActivity = [ @@ -48,6 +49,7 @@ export function DashboardContent() { const [totalParticipants, setTotalParticipants] = useState(null) const [completedCount, setCompletedCount] = useState(null) const [runningExams, setRunningExams] = useState(null) + const [avgPromptScore, setAvgPromptScore] = useState(null) const [isLoading, setIsLoading] = useState(true) useEffect(() => { @@ -66,8 +68,10 @@ export function DashboardContent() { const allParticipants = boards.flat() setTotalParticipants(allParticipants.length) setCompletedCount(allParticipants.filter((p) => p.submitted).length) + setAvgPromptScore(computeSessionAnalytics(allParticipants).avgPrompt) } catch (e) { console.error("Failed to load dashboard stats", e) + setAvgPromptScore(null) } finally { setIsLoading(false) } @@ -78,6 +82,8 @@ export function DashboardContent() { const displayValue = (val: number | null) => isLoading ? "..." : val !== null ? val.toLocaleString() : "–" + const displayAvgPromptScore = isLoading ? "–" : (avgPromptScore ?? "–") + return (
{/* Section 2: Top Header Bar */} @@ -107,17 +113,17 @@ export function DashboardContent() {
- 평가 완료 수 + 코드 제출 완료 수

{displayValue(completedCount)}

{!isLoading && totalParticipants !== null && totalParticipants > 0 - ? `완료율 ${Math.round(((completedCount ?? 0) / totalParticipants) * 100)}%` - : "코드 제출 기준"} + ? `제출률 ${Math.round(((completedCount ?? 0) / totalParticipants) * 100)}%` + : "submissions 테이블 기준"}

- {/* Average Prompt Score - no API available */} + {/* Average Prompt Score */}
@@ -125,8 +131,8 @@ export function DashboardContent() {
평균 프롬프트 점수
-

–

-

채점 완료 후 집계

+

{displayAvgPromptScore}

+

채점 완료 후 집계 (전체 세션)

{/* Active Test Sessions */} diff --git a/components/entry-codes-content.tsx b/components/entry-codes-content.tsx index 7fce029..61d4e65 100644 --- a/components/entry-codes-content.tsx +++ b/components/entry-codes-content.tsx @@ -13,7 +13,8 @@ import { } from "@/components/ui/dialog" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" -import { createExam, getExams, createEntryCode, deleteExam, getEntryCodes, startExam, endExam, extendExam, Exam, LoginFailedError, NetworkError } from "@/lib/api/admin" +import { createExam, getExams, deleteExam, getEntryCodes, startExam, endExam, extendExam, Exam, LoginFailedError, NetworkError } from "@/lib/api/admin" +import { getExamSortTimestamp } from "@/lib/master-test-sessions" import { useToast } from "@/hooks/use-toast" @@ -49,6 +50,43 @@ const getExamStateLabel = (state: string): string => { } } +// 백엔드 응답의 다양한 필드명(entryCode/accessCode/code/inviteCode)에서 입장 코드를 추출 +const pickEntryCode = (source: unknown): string | undefined => { + if (!source || typeof source !== "object") return undefined + + const record = source as Record + const candidates = ["entryCode", "accessCode", "code", "inviteCode"] + for (const key of candidates) { + const value = record[key] + if (typeof value === "string" && value.trim()) { + return value + } + } + + return undefined +} + +/** 시험 시작 버튼(0) → 종료 버튼(1) → 종료됨(2). UI 버튼 분기와 동일한 state 기준 */ +function getExamEntryCodesActionPriority(state: string): number { + const normalized = (state ?? "").trim().toUpperCase() + if (["ENDED", "COMPLETED", "CLOSED", "FINISHED", "DONE"].includes(normalized)) { + return 2 + } + if (["RUNNING", "IN_PROGRESS", "ACTIVE"].includes(normalized)) { + return 1 + } + return 0 +} + +/** 상태 우선 정렬 후, 같은 그룹 내에서는 시작/생성 시각 내림차순(기존 시각 기준) */ +function sortExamsForEntryCodes(exams: T[]): T[] { + return [...exams].sort((a, b) => { + const byAction = getExamEntryCodesActionPriority(a.state) - getExamEntryCodesActionPriority(b.state) + if (byAction !== 0) return byAction + return getExamSortTimestamp(b) - getExamSortTimestamp(a) + }) +} + export function EntryCodesContent() { // 시험 생성 모달 상태 @@ -120,20 +158,20 @@ export function EntryCodesContent() { const activeEntryCode = entryCodes.find((ec) => ec.isActive) || entryCodes[0] return { ...exam, - entryCode: activeEntryCode?.code || undefined, + entryCode: activeEntryCode?.code || pickEntryCode(exam), } } catch (entryCodeError) { // 입장 코드 조회 실패 시 해당 시험의 입장 코드는 undefined로 유지 console.warn(`Failed to fetch entry codes for exam ${exam.id}:`, entryCodeError) return { ...exam, - entryCode: undefined, + entryCode: pickEntryCode(exam), } } }) ) - setExams(examsWithEntryCodes) + setExams(sortExamsForEntryCodes(examsWithEntryCodes)) // 시험 목록을 새로 가져올 때 페이지를 1로 리셋 setCurrentExamPage(1) } catch (error) { @@ -211,42 +249,32 @@ export function EntryCodesContent() { setIsSubmitting(true) try { const createdExam = await createExam(payload) - console.log("Exam created:", createdExam) + const responseEntryCode = pickEntryCode(createdExam) + let createdExamWithEntryCode: Exam = { + ...createdExam, + entryCode: responseEntryCode, + } - // 시험 생성 후 자동으로 입장 코드 생성 - let entryCodeValue: string | undefined = undefined + // 생성 직후 entry-codes API에서 실제 활성 코드를 한번 더 조회해 반영 try { - const entryCodeResponse = await createEntryCode({ - label: undefined, - examId: createdExam.id, - problemSetId: 0, - expiresAt: undefined, - maxUses: 0, - }) - entryCodeValue = entryCodeResponse.code - console.log("Entry code created:", entryCodeValue) + const createdExamEntryCodes = await getEntryCodes(createdExam.id) + const activeEntryCode = createdExamEntryCodes.find((ec) => ec.isActive) || createdExamEntryCodes[0] + createdExamWithEntryCode = { + ...createdExam, + entryCode: activeEntryCode?.code || responseEntryCode, + } } catch (entryCodeError) { - console.error("Failed to create entry code", entryCodeError) - // 입장 코드 생성 실패해도 시험 생성은 성공으로 처리 - toast({ - title: "입장 코드 생성 실패", - description: "시험은 생성되었지만 입장 코드 생성에 실패했습니다. 나중에 수동으로 생성해주세요.", - variant: "destructive", - }) + console.warn(`Failed to fetch entry codes right after exam creation (examId=${createdExam.id}):`, entryCodeError) } - // 입장 코드가 포함된 시험 객체 생성 - const examWithEntryCode: Exam = { - ...createdExam, - entryCode: entryCodeValue, - } + console.log("Exam created:", createdExamWithEntryCode) // 시험 목록에 새로 생성된 시험 추가 setExams((prev) => { if (prev === null) { - return [examWithEntryCode] + return [createdExamWithEntryCode] } - return [examWithEntryCode, ...prev] + return sortExamsForEntryCodes([createdExamWithEntryCode, ...prev]) }) // 모달 닫기 @@ -260,7 +288,7 @@ export function EntryCodesContent() { // 성공 토스트 표시 toast({ title: "시험 생성 성공", - description: `"${createdExam.title}" 시험이 성공적으로 생성되었습니다.`, + description: `"${createdExamWithEntryCode.title}" 시험이 성공적으로 생성되었습니다.`, }) } catch (error) { console.error("Failed to create exam", error) @@ -465,7 +493,7 @@ export function EntryCodesContent() { } else if (newList.length === 0) { setCurrentExamPage(1) } - return newList + return sortExamsForEntryCodes(newList) }) // 성공 토스트 표시 diff --git a/components/global-settings-content.tsx b/components/global-settings-content.tsx index 0424645..c95ff37 100644 --- a/components/global-settings-content.tsx +++ b/components/global-settings-content.tsx @@ -8,6 +8,7 @@ import { Button } from "@/components/ui/button" import { Switch } from "@/components/ui/switch" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" import { useToast } from "@/hooks/use-toast" +import { AdminPageHeader } from "@/components/admin-page-header" type Settings = { defaultTestDuration: string @@ -116,32 +117,13 @@ export function GlobalSettingsContent() { } return ( -
- {/* Page Header */} -
-

- 전역 설정 -

-

- 플랫폼 전역 설정 및 시스템 보안 정책을 관리합니다 -

-
+
+ +
{/* Settings Cards Container */}
{/* Section 1: Test Configuration */} @@ -415,6 +397,7 @@ export function GlobalSettingsContent() { )}
+
) } diff --git a/components/login-card.tsx b/components/login-card.tsx index b010301..55acc9f 100644 --- a/components/login-card.tsx +++ b/components/login-card.tsx @@ -62,6 +62,7 @@ export default function LoginCard() { useExamSessionStore.setState({ examId, participantId, + examParticipantId: response.session?.examParticipantId ?? null, tokenLimit: response.session?.tokenLimit ?? 20000, accessToken: response.accessToken, }); diff --git a/components/master-dashboard-content.tsx b/components/master-dashboard-content.tsx index 9a70ed5..301c3a6 100644 --- a/components/master-dashboard-content.tsx +++ b/components/master-dashboard-content.tsx @@ -1,12 +1,31 @@ "use client" -import { useState } from "react" +import { useEffect, useState } from "react" import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" import { Badge } from "@/components/ui/badge" import { Button } from "@/components/ui/button" import { Users, UserCheck, CheckCircle2, CalendarClock, FileCode, ScrollText, ArrowRight, KeyRound, Copy, Check } from "lucide-react" import Link from "next/link"; -import { issueAdminNumber, LoginFailedError, NetworkError } from "@/lib/api/admin" +import { + getBoard, + getExams, + getSystemStatus, + issueAdminNumber, + LoginFailedError, + NetworkError, +} from "@/lib/api/admin" +import { + countActiveExamSessions, + countTodayParticipants, + deriveMasterSystemStatusDisplay, + isActiveExam, + type MasterSystemStatusDisplay, +} from "@/lib/master-dashboard-kpi" +import { + isMasterSessionInProgress, + pickRecentSessions, + type MasterRecentSession, +} from "@/lib/master-test-sessions" import { useToast } from "@/hooks/use-toast" import { Dialog, @@ -18,13 +37,7 @@ import { } from "@/components/ui/dialog" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" - -const recentSessions = [ - { id: 1, sessionId: "SESSION-2025-001", status: "진행 중", createdAt: "2025년 1월 14일", participants: 18 }, - { id: 2, sessionId: "SESSION-2025-002", status: "완료", createdAt: "2025년 1월 13일", participants: 25 }, - { id: 3, sessionId: "SESSION-2025-003", status: "진행 중", createdAt: "2025년 1월 12일", participants: 12 }, - { id: 4, sessionId: "SESSION-2025-004", status: "완료", createdAt: "2025년 1월 11일", participants: 30 }, -] +import { AdminPageHeader } from "@/components/admin-page-header" const recentLogs = [ { id: 1, timestamp: "오전 10:33", type: "관리자", description: "관리자 'john.smith'가 플랫폼 설정을 업데이트했습니다" }, @@ -43,8 +56,85 @@ export function MasterDashboardContent({ onNavigate }: DashboardContentProps) { const [issuedAdminNumber, setIssuedAdminNumber] = useState(null) const [copied, setCopied] = useState(false) const [isLoading, setIsLoading] = useState(false) + const [activeSessions, setActiveSessions] = useState(null) + const [todayParticipants, setTodayParticipants] = useState(null) + const [systemStatus, setSystemStatus] = useState( + deriveMasterSystemStatusDisplay({ type: "fetch_failed" }) + ) + const [kpiLoading, setKpiLoading] = useState(true) + const [recentSessions, setRecentSessions] = useState([]) + const [recentSessionsLoading, setRecentSessionsLoading] = useState(true) + const [recentSessionsError, setRecentSessionsError] = useState(false) const { toast } = useToast() + useEffect(() => { + let cancelled = false + + async function loadKpi() { + setKpiLoading(true) + setRecentSessionsLoading(true) + setRecentSessionsError(false) + try { + const [examsResult, statusResult] = await Promise.allSettled([ + (async () => { + const exams = await getExams() + // ACTIVE(state) 시험에만 getBoard 호출 — 전체 시험 대상 board 조회 제거 + const boardByExamId = new Map>>() + await Promise.all( + exams.filter(isActiveExam).map(async (e) => { + const board = await getBoard(e.id).catch(() => []) + boardByExamId.set(e.id, board) + }) + ) + const boards = exams.map((e) => boardByExamId.get(e.id) ?? []) + return { exams, boards } + })(), + getSystemStatus(), + ]) + + if (cancelled) return + + if (examsResult.status === "fulfilled") { + const { exams, boards } = examsResult.value + setActiveSessions(countActiveExamSessions(exams)) + setTodayParticipants(countTodayParticipants(exams, boards)) + setRecentSessions(pickRecentSessions(exams)) + } else { + console.error("[MasterDashboard] Failed to load session/participant KPI", examsResult.reason) + setActiveSessions(0) + setTodayParticipants(0) + setRecentSessions([]) + setRecentSessionsError(true) + } + + if (statusResult.status === "fulfilled") { + setSystemStatus( + deriveMasterSystemStatusDisplay({ + type: "services", + services: statusResult.value.services ?? [], + }) + ) + } else { + console.error("[MasterDashboard] Failed to load system status", statusResult.reason) + setSystemStatus(deriveMasterSystemStatusDisplay({ type: "fetch_failed" })) + } + } finally { + if (!cancelled) { + setKpiLoading(false) + setRecentSessionsLoading(false) + } + } + } + + loadKpi() + return () => { + cancelled = true + } + }, []) + + const displayKpiNumber = (val: number | null) => + kpiLoading ? "..." : val !== null ? val.toLocaleString() : "0" + const handleIssueAdminNumber = async () => { setIsLoading(true) try { @@ -105,15 +195,10 @@ export function MasterDashboardContent({ onNavigate }: DashboardContentProps) { } return ( -
- {/* Page Header */} -
-

- 마스터 대시보드 -

-

플랫폼 활동 및 코딩 테스트 운영 개요.

-
+
+ +
{/* Section 1: KPI Summary Cards */}
{/* Active Sessions */} @@ -121,7 +206,9 @@ export function MasterDashboardContent({ onNavigate }: DashboardContentProps) {
- 12 + + {displayKpiNumber(activeSessions)} + 진행 중인 세션
- 148 + + {displayKpiNumber(todayParticipants)} + 오늘의 참가자
- 운영 중 + + {kpiLoading ? "..." : systemStatus.label} + 시스템 상태
- +
@@ -197,8 +297,17 @@ export function MasterDashboardContent({ onNavigate }: DashboardContentProps) { 최근 세션 -
- {recentSessions.map((session) => ( +
+ {recentSessionsLoading ? ( +

최근 세션을 불러오는 중…

+ ) : recentSessionsError ? ( +

+ 최근 세션을 불러오지 못했습니다. +

+ ) : recentSessions.length === 0 ? ( +

최근 세션이 없습니다.

+ ) : ( + recentSessions.map((session) => (
- ))} + )) + )}
+ ) } diff --git a/components/master-dashboard.tsx b/components/master-dashboard.tsx index b70d8aa..c3f601c 100644 --- a/components/master-dashboard.tsx +++ b/components/master-dashboard.tsx @@ -2,8 +2,7 @@ import { useState } from "react" import { Sidebar } from "@/components/sidebar" -import { TopNavBar } from "@/components/top-nav-bar" -import { DashboardContent } from "@/components/dashboard-content" +import { MasterDashboardContent } from "@/components/master-dashboard-content" import { AdminAccountsContent } from "@/components/admin-accounts-content" import { TestSessionsContent } from "@/components/test-sessions-content" import TestSessionDetailsContent from "@/components/test-session-details-content" @@ -43,19 +42,15 @@ export function MasterDashboard() { -
-
- -
- -
- {activeItem === "Dashboard" && } +
+
+ {activeItem === "Dashboard" && } {activeItem === "Admin Accounts" && } {activeItem === "Test Sessions" && !selectedSession && ( )} {activeItem === "Test Sessions" && selectedSession && ( - + )} {activeItem === "Global Settings" && } {activeItem === "Problem" && } diff --git a/components/participant-evaluation-content.tsx b/components/participant-evaluation-content.tsx index c1dd0dc..e1f31fa 100644 --- a/components/participant-evaluation-content.tsx +++ b/components/participant-evaluation-content.tsx @@ -1,16 +1,38 @@ "use client" -import { useState, useEffect } from "react" -import Link from "next/link" +import { useState, useEffect, useMemo } from "react" +import type { MouseEvent } from "react" import { ArrowLeft, User, Code, CheckCircle, X } from "lucide-react" import { useRouter } from "next/navigation" -import { getExams, getBoard } from "@/lib/api/admin" +import { + getExams, + getBoard, + getAdminSubmissionDetail, + formatBoardSubmissionLabelKo, + type Exam, + type ExamineeBoardEntry, + type AdminSubmissionDetailResponse, +} from "@/lib/api/admin" +import { + buildKeyValueCsvBody, + buildParticipantEvaluationCsvFilename, + downloadUtf8Csv, +} from "@/lib/admin-board-csv-export" +import { resolveBoardPerformanceLevel } from "@/lib/performance-level" +import { ParticipantEvaluationTestSummary } from "@/components/participant-evaluation-test-summary" +import { ParticipantEvaluationRubricReport } from "@/components/participant-evaluation-rubric-report" interface ParticipantEvaluationContentProps { - entryCode: string - participantName?: string // 선택적 — URL query 또는 board에서 로드 + /** Admin: entryCode / title / exam id 문자열. Master: 생략 가능(examId 사용) */ + entryCode?: string + /** Master 전용 — 지정 시 entryCode 조회 없이 직접 보드 로드 */ + examId?: number + participantName?: string + /** URL 세그먼트 — 목록·보드와 동일하게 `exam_participants.id` (examParticipantId) */ participantId: string - onBack?: () => void; + onBack?: () => void + /** 뒤로가기 버튼 문구 (기본: 이전 페이지로 돌아가기) */ + backLabel?: string } interface ToastItem { @@ -19,248 +41,190 @@ interface ToastItem { description: string } -const participantData = { - name: "Alice Johnson", - entryCode: "AJ-2024-001", - avgScore: 92, - status: "Submitted" as const, - testDate: "2024-02-11", - duration: "32 minutes", - trend: "High" as const, - language: "Python", - promptScore: 86, - performanceScore: 81, - correctnessScore: 89, -} +/** + * participant-list-content 와 동일 규칙 — 결과 URL 세그먼트 → 시험 매칭 + */ +function findExamByResultsSegment(exams: Exam[], segment: string) { + const trimmed = segment.trim() + if (!trimmed) return undefined -const dummyCode = `def solution(nums: List[int], target: int) -> List[int]: - seen = {} - for i, num in enumerate(nums): - complement = target - num - if complement in seen: - return [seen[complement], i] - seen[num] = i - return [] - -def optimize_query(data: List[Dict], filters: Dict) -> List[Dict]: - result = data - for key, value in filters.items(): - result = [item for item in result if item.get(key) == value] - return result - -class DataProcessor: - def __init__(self, config: Dict): - self.config = config - self.cache = {} - - def process(self, input_data: Any) -> Any: - cache_key = hash(str(input_data)) - if cache_key in self.cache: - return self.cache[cache_key] - result = self._transform(input_data) - self.cache[cache_key] = result - return result` - -const feedbackData = { - strengths: [ - "깔끔하고 읽기 쉬운 코드 구조", - "O(n) 시간 복잡도를 위한 해시 맵의 효율적인 사용", - "독스트링을 통한 좋은 문서화", - "코드 전반에 걸친 적절한 타입 힌트", - ], - weaknesses: [ - "빈 입력에 대한 엣지 케이스 처리 누락", - "데이터 타입에 대한 입력 검증 없음", - "캐시 무효화 전략이 구현되지 않음", - ], - suggestions: [ - "엣지 케이스를 위한 단위 테스트 추가", - "메모이제이션을 위해 functools.lru_cache 사용 고려", - "커스텀 예외를 사용한 적절한 오류 처리 구현", - ], - performanceNotes: [ - "해시 맵 접근 방식이 이 문제에 최적입니다", - "제너레이터를 사용하면 메모리 사용량을 줄일 수 있습니다", - "대용량 데이터셋에 대해 지연 평가 고려", - ], -} + const byEntryCode = exams.find( + (e) => e.entryCode != null && String(e.entryCode).length > 0 && e.entryCode === trimmed + ) + if (byEntryCode) return byEntryCode -const testCaseResults = [ - { - id: "1", - testCase: "Basic Input", - expected: "[0, 1]", - submitted: "[0, 1]", - result: "Passed" as const, - execTime: "12ms", - memory: "14.2 MB", - tokens: 128, - }, - { - id: "2", - testCase: "Empty Array", - expected: "[]", - submitted: "[]", - result: "Passed" as const, - execTime: "8ms", - memory: "13.8 MB", - tokens: 64, - }, - { - id: "3", - testCase: "Large Input", - expected: "[999, 1000]", - submitted: "[999, 1000]", - result: "Passed" as const, - execTime: "45ms", - memory: "28.4 MB", - tokens: 256, - }, - { - id: "4", - testCase: "Negative Numbers", - expected: "[2, 4]", - submitted: "[2, 3]", - result: "Failed" as const, - execTime: "15ms", - memory: "14.6 MB", - tokens: 128, - }, - { - id: "5", - testCase: "Duplicate Values", - expected: "[1, 3]", - submitted: "[1, 3]", - result: "Passed" as const, - execTime: "11ms", - memory: "14.1 MB", - tokens: 96, - }, - { - id: "6", - testCase: "Single Element", - expected: "[]", - submitted: "[]", - result: "Passed" as const, - execTime: "6ms", - memory: "13.5 MB", - tokens: 48, - }, -] - -function StatusBadge({ status }: { status: "Submitted" | "In Progress" | "Not Started" }) { - const badgeStyles: Record = { - Submitted: "bg-[#DCFCE7] text-[#16A34A]", - "In Progress": "bg-[#E0EDFF] text-[#3B82F6] font-semibold", - "Not Started": "bg-[#F3F4F6] text-[#6B7280]", - } - const statusText: Record = { - Submitted: "제출됨", - "In Progress": "진행 중", - "Not Started": "시작 안 함", - } - return {statusText[status]} -} + const byTitle = exams.find((e) => e.title === trimmed) + if (byTitle) return byTitle -function TrendBadge({ trend }: { trend: "High" | "Average" | "Low" }) { - const badgeStyles: Record = { - High: "bg-[#DCFCE7] text-[#16A34A]", - Average: "bg-[#FEF3C7] text-[#D97706]", - Low: "bg-[#FEE2E2] text-[#DC2626]", + if (/^\d+$/.test(trimmed)) { + return exams.find((e) => String(e.id) === trimmed) } - const trendText: Record = { - High: "높음", - Average: "보통", - Low: "낮음", - } - return {trendText[trend]} -} -function LanguageBadge({ language }: { language: string }) { - return {language} + return undefined } -function TestResultBadge({ result }: { result: "Passed" | "Failed" }) { - const badgeStyles: Record = { - Passed: "bg-[#DCFCE7] text-[#16A34A]", - Failed: "bg-[#FEE2E2] text-[#DC2626]", - } - const resultText: Record = { - Passed: "통과", - Failed: "실패", - } - return {resultText[result]} +function PerformanceLevelBadge({ totalScore }: { totalScore: number | null | undefined }) { + const { label, badgeClass } = resolveBoardPerformanceLevel(totalScore) + return {label} } -function generateParticipantCSV(): string { - const header = "Metric,Value" - const rows = [ - "Name," + participantData.name, - "Entry Code," + participantData.entryCode, - "Average Score," + participantData.avgScore + "%", - "Status," + participantData.status, - "Test Date," + participantData.testDate, - "Duration," + participantData.duration, - "Trend," + participantData.trend, - "Language," + participantData.language, - "Prompt Score," + participantData.promptScore + "%", - "Performance Score," + participantData.performanceScore + "%", - "Correctness Score," + participantData.correctnessScore + "%", - ] - return [header, ...rows].join("\n") +function LanguageBadge({ language }: { language: string }) { + return {language} } -function downloadCSV() { - const csvContent = generateParticipantCSV() - const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" }) - const url = URL.createObjectURL(blob) - const link = document.createElement("a") - link.href = url - link.download = "participants.csv" - document.body.appendChild(link) - link.click() - document.body.removeChild(link) - URL.revokeObjectURL(url) +function formatScore(n: number | null | undefined): string { + if (n === null || n === undefined || Number.isNaN(Number(n))) return "–" + return `${Number(n).toFixed(1)}` } -export function ParticipantEvaluationContent({ entryCode, participantName: participantNameProp, participantId, onBack }: ParticipantEvaluationContentProps) { +export function ParticipantEvaluationContent({ + entryCode = "", + examId: examIdProp, + participantName: participantNameProp, + participantId, + onBack, + backLabel = "이전 페이지로 돌아가기", +}: ParticipantEvaluationContentProps) { const router = useRouter() const [toasts, setToasts] = useState([]) - // 실제 참가자 정보 (board에서 로드) - const [boardParticipantName, setBoardParticipantName] = useState(null) - const [tokenUsed, setTokenUsed] = useState(null) - const [submitted, setSubmitted] = useState(null) + const [examId, setExamId] = useState(examIdProp ?? null) + const [examTitle, setExamTitle] = useState(null) + const [boardEntry, setBoardEntry] = useState(null) + const [boardError, setBoardError] = useState(null) const [isLoadingBoard, setIsLoadingBoard] = useState(true) + const [submissionDetail, setSubmissionDetail] = useState(null) + const [submissionDetailError, setSubmissionDetailError] = useState(null) + const [isLoadingSubmission, setIsLoadingSubmission] = useState(false) + useEffect(() => { - async function loadParticipantFromBoard() { + let cancelled = false + async function loadBoard() { setIsLoadingBoard(true) + setBoardError(null) + setBoardEntry(null) + setExamTitle(null) + setExamId(null) + + const directExamId = + examIdProp != null && Number.isFinite(examIdProp) && examIdProp > 0 ? examIdProp : null + try { - const exams = await getExams() - const matched = exams.find((e) => e.entryCode === entryCode) - if (!matched) { - setIsLoadingBoard(false) + let resolvedExamId: number | null = directExamId + let resolvedTitle: string | null = null + + if (directExamId != null) { + const exams = await getExams() + const matched = exams.find((e) => e.id === directExamId) + resolvedTitle = matched?.title?.trim() || `시험 #${directExamId}` + } else { + const exams = await getExams() + const matched = findExamByResultsSegment(exams, entryCode) + if (!matched) { + if (!cancelled) setBoardError("해당 입장 코드·시험명에 맞는 시험을 찾을 수 없습니다.") + return + } + resolvedExamId = matched.id + resolvedTitle = matched.title?.trim() || entryCode + } + + if (resolvedExamId == null) { + if (!cancelled) setBoardError("시험 정보를 확인할 수 없습니다.") return } - const board = await getBoard(matched.id) - const entry = board.find((p) => p.examParticipantId.toString() === participantId) - if (entry) { - setBoardParticipantName(entry.name) - setTokenUsed(entry.tokenUsed) - setSubmitted(entry.submitted) + + const board = await getBoard(resolvedExamId) + const entry = board.find((p) => String(p.examParticipantId) === String(participantId)) + if (!cancelled) { + setExamId(resolvedExamId) + setExamTitle(resolvedTitle) + if (entry) setBoardEntry(entry) + else setBoardError("참가자를 보드에서 찾을 수 없습니다. (ID가 examParticipantId와 일치하는지 확인하세요)") } } catch (e) { - console.error("Failed to load participant from board", e) + console.error("Failed to load board for evaluation detail", e) + if (!cancelled) setBoardError("참가자·시험 정보를 불러오지 못했습니다.") } finally { - setIsLoadingBoard(false) + if (!cancelled) setIsLoadingBoard(false) } } - loadParticipantFromBoard() - }, [entryCode, participantId]) + loadBoard() + return () => { + cancelled = true + } + }, [entryCode, examIdProp, participantId]) + + const submissionId = boardEntry?.submissionId ?? null - // 이름 우선순위: prop > board > fallback - const displayName = participantNameProp || boardParticipantName || participantData.name + useEffect(() => { + if (submissionId == null) { + setSubmissionDetail(null) + setSubmissionDetailError(null) + return + } + const submissionIdNum = submissionId + let cancelled = false + async function loadSubmission() { + setIsLoadingSubmission(true) + setSubmissionDetailError(null) + try { + const detail = await getAdminSubmissionDetail(submissionIdNum) + if (!cancelled) setSubmissionDetail(detail) + } catch (e: unknown) { + console.error("getAdminSubmissionDetail failed", e) + if (!cancelled) { + setSubmissionDetail(null) + setSubmissionDetailError( + e instanceof Error ? e.message : "제출 상세를 불러오지 못했습니다. (권한 또는 네트워크를 확인하세요)" + ) + } + } finally { + if (!cancelled) setIsLoadingSubmission(false) + } + } + loadSubmission() + return () => { + cancelled = true + } + }, [submissionId]) + + const displayName = useMemo(() => { + if (participantNameProp?.trim()) return participantNameProp.trim() + if (boardEntry?.name) return boardEntry.name + return "–" + }, [participantNameProp, boardEntry]) + + const submissionStatusLabel = useMemo(() => { + if (!boardEntry) return null + return formatBoardSubmissionLabelKo(boardEntry) + }, [boardEntry]) + + const scoreFromDetail = submissionDetail?.score + /** BE는 Score 행이 없어도 0으로 채워 보냄 → 전부 0이면 ‘실제 점수 없음’으로 간주 */ + const detailScoresMeaningful = + scoreFromDetail && + (Number(scoreFromDetail.prompt) !== 0 || + Number(scoreFromDetail.perf) !== 0 || + Number(scoreFromDetail.correctness) !== 0 || + Number(scoreFromDetail.total) !== 0) + + const showBoardTotalOnly = + boardEntry?.totalScore != null && + !Number.isNaN(Number(boardEntry.totalScore)) && + !detailScoresMeaningful + + const effectiveTotalScore = useMemo((): number | null => { + if (detailScoresMeaningful && scoreFromDetail?.total != null) { + const n = Number(scoreFromDetail.total) + return Number.isNaN(n) ? null : n + } + if (boardEntry?.totalScore != null) { + const n = Number(boardEntry.totalScore) + return Number.isNaN(n) ? null : n + } + return null + }, [detailScoresMeaningful, scoreFromDetail, boardEntry]) const showToast = (title: string, description: string) => { const id = crypto.randomUUID() @@ -275,49 +239,88 @@ export function ParticipantEvaluationContent({ entryCode, participantName: parti } const handleExport = () => { - downloadCSV() - showToast("Participant results exported successfully.", "File: participants.csv") + try { + const examLabel = (examTitle ?? entryCode).trim() || "session" + const csvBody = buildKeyValueCsvBody([ + { label: "이름", value: displayName }, + { label: "시험", value: examLabel, excelTextValue: true }, + { label: "제출 상태", value: submissionStatusLabel ?? "–" }, + { + label: "총점", + value: effectiveTotalScore != null ? formatScore(effectiveTotalScore) : "–", + }, + { + label: "프롬프트 점수", + value: detailScoresMeaningful ? formatScore(scoreFromDetail?.prompt ?? null) : "–", + }, + { + label: "성능 점수", + value: detailScoresMeaningful ? formatScore(scoreFromDetail?.perf ?? null) : "–", + }, + { + label: "정답률 점수", + value: detailScoresMeaningful ? formatScore(scoreFromDetail?.correctness ?? null) : "–", + }, + { + label: "코드 LOC", + value: + submissionDetail?.metrics?.loc != null + ? String(submissionDetail.metrics.loc) + : "–", + }, + { label: "제출 언어", value: submissionDetail?.lang ?? "–" }, + { label: "참가자 ID", value: participantId }, + ...(submissionId != null + ? [{ label: "제출 ID", value: String(submissionId) }] + : []), + ]) + + const filename = buildParticipantEvaluationCsvFilename(examLabel, displayName) + downloadUtf8Csv(filename, csvBody) + showToast("보내기 완료", filename) + } catch (e) { + console.error("[ParticipantEvaluation] CSV export failed", e) + showToast("보내기 실패", "CSV 파일을 생성하지 못했습니다.") + } } + const handleBackClick = (e: MouseEvent) => { + e.preventDefault() + if (onBack) onBack() + else router.back() + } - const handleBackClick = ( - e: React.MouseEvent - ) => { - e.preventDefault(); - if (onBack) { - onBack(); // 🔹 page.tsx 에서 만들어준 분기 로직 실행 - } else { - router.back(); // 🔹 혹시 onBack이 없을 때 기본 동작 - } - }; + const langDisplay = submissionDetail?.lang ?? "–" return (
- {/* Top Header Bar */}

참가자 평가 상세

- 이 참가자의 평가 결과와 제출 세부 정보를 모두 확인할 수 있습니다. + 보드 API와 관리자 전용 제출 상세 API에서 불러온 데이터입니다. 미제공 필드는 안내 문구로 표시됩니다.

- {/* Main Content Panel - Scrollable */} -
- {/* Back Link */} -
+
+
- {/* Summary Cards - Row 1 */} + {boardError && ( +
+ {boardError} +
+ )} +
참가자 @@ -326,192 +329,191 @@ export function ParticipantEvaluationContent({ entryCode, participantName: parti
- {isLoadingBoard ? "..." : displayName} + {isLoadingBoard ? "…" : displayName}
- 입장 코드 -

{entryCode}

+ + {examIdProp != null ? "시험" : "시험 구분 (URL)"} + +

+ {isLoadingBoard ? "…" : (examTitle ?? entryCode) || "–"} +

+ {examId != null &&

examId: {examId}

}
토큰 사용량

- {isLoadingBoard ? "..." : tokenUsed !== null ? tokenUsed.toLocaleString() : "–"} + {isLoadingBoard || !boardEntry ? ( + "…" + ) : ( + <> + {boardEntry.tokenUsed.toLocaleString()} / {boardEntry.tokenLimit.toLocaleString()} + + )}

- {/* Summary Cards - Row 2 */}
- 참가자 ID + + 응시 참가 ID (examParticipantId) +

{participantId}

+ {submissionId != null && ( +

submissionId: {submissionId}

+ )}
- 성과 수준 + + 성과 수준 (총점 기준) +
- +
+ {effectiveTotalScore != null && ( +

+ 기준: 80점 이상 높음 · 50점 이상 보통 · 50점 미만 낮음 + {detailScoresMeaningful + ? " (관리자 제출 상세 API 총점)" + : showBoardTotalOnly + ? " (관리자 보드 총점)" + : ""} +

+ )}
- 제출 상태 + 제출·채점 상태
{isLoadingBoard ? ( - ... - ) : submitted !== null ? ( - + … + ) : submissionStatusLabel ? ( + + {submissionStatusLabel} + ) : ( - + – )}
+ {boardEntry?.submittedAt && ( +

제출 시각: {boardEntry.submittedAt}

+ )} + {boardEntry?.evaluatedAt && ( +

점수 갱신: {boardEntry.evaluatedAt}

+ )}
- {/* Evaluation Breakdown Section */}

평가 점수 세부 내역

+ {isLoadingSubmission && submissionId != null && ( +

제출 상세를 불러오는 중…

+ )} + {submissionDetailError && ( +

{submissionDetailError}

+ )}
-

{participantData.promptScore}%

+

+ {detailScoresMeaningful ? formatScore(scoreFromDetail?.prompt ?? null) : "–"} +

프롬프트 점수

-

이해 및 문제 해석 능력

+

관리자 제출 상세 API의 score.prompt

-

{participantData.performanceScore}%

+

+ {detailScoresMeaningful ? formatScore(scoreFromDetail?.perf ?? null) : "–"} +

성능 점수

-

실행 효율 및 최적화

+

관리자 제출 상세 API의 score.perf

-

{participantData.correctnessScore}%

+

+ {detailScoresMeaningful ? formatScore(scoreFromDetail?.correctness ?? null) : "–"} +

정답률 점수

-

솔루션 정확도 및 테스트 결과 일치율

+

+ {detailScoresMeaningful + ? "관리자 제출 상세 API score.correctness" + : showBoardTotalOnly + ? "항목별 값 없음 — 아래 총점만 보드 참고" + : "데이터 없음"} +

+ {detailScoresMeaningful && ( +

+ 총점 {formatScore(scoreFromDetail?.total ?? null)} (관리자 제출 상세 API) +

+ )} + {!detailScoresMeaningful && showBoardTotalOnly && ( +

+ 총점 {formatScore(Number(boardEntry!.totalScore))} (관리자 보드 — 상세 점수 행 없음) +

+ )} + {!detailScoresMeaningful && !showBoardTotalOnly && !isLoadingSubmission && ( +

표시할 점수 데이터가 없습니다.

+ )}
- {/* Submitted Code Section */}

제출한 코드

-
-
-
-
- - 코드 구현 -
- -
-
-
-                  {dummyCode}
-                
+
+
+
+ + 코드
+
-
-
- AI 피드백 요약 -
-
-
-

강점

-
    - {feedbackData.strengths.map((item, index) => ( -
  • - • {item} -
  • - ))} -
-
-
-

약점

-
    - {feedbackData.weaknesses.map((item, index) => ( -
  • - • {item} -
  • - ))} -
-
-
-

개선 제안

-
    - {feedbackData.suggestions.map((item, index) => ( -
  • - • {item} -
  • - ))} -
-
-
-

- 성능 관련 메모 -

-
    - {feedbackData.performanceNotes.map((item, index) => ( -
  • - • {item} -
  • - ))} -
-
-
+
+ {isLoadingSubmission ? ( +

불러오는 중…

+ ) : submissionDetail?.codeInline != null && submissionDetail.codeInline.trim() !== "" ? ( +
+                  {submissionDetail.codeInline}
+                
+ ) : submissionDetail ? ( +

저장된 제출 코드가 없습니다.

+ ) : ( +

제출 상세를 불러오면 표시됩니다.

+ )}
- {/* Test Case Results Section */}
-

테스트 케이스 결과

-
-
- 전체 테스트 케이스 -
-
- 테스트 케이스 - 기대 출력값 - 제출된 출력값 - 결과 - - 실행 시간 - - 메모리 사용량 - 토큰 수 -
-
- {testCaseResults.map((testCase, index) => ( -
- {testCase.testCase} - {testCase.expected} - {testCase.submitted} -
- -
- {testCase.execTime} - {testCase.memory} - {testCase.tokens} -
- ))} -
+

AI 피드백 (루브릭·턴 평가)

+
+
-
+
+ +
+

채점·테스트 요약

+ +
- {/* Toast Notifications */}
{toasts.map((toast) => (
{toast.description}

+ {open &&
{children}
} + + ) +} + +function MetricCell({ + label, + value, + description, +}: { + label: string + value: string + description?: string +}) { + return ( +
+
+

{label}

+ {description && ( + + + + )} +
+

{value}

+
+ ) +} + +function TextBlock({ text }: { text: string }) { + const displayText = useMemo(() => cleanupAiFeedbackText(text), [text]) + return ( +

+ {displayText} +

+ ) +} + +function Unavailable({ label = "제공되지 않음" }: { label?: string }) { + return

{label}

+} + +function formatDisplayLabel(raw: string): string { + return raw + .replace(/_/g, " ") + .replace(/\b\w/g, (c) => c.toUpperCase()) +} + +function formatScoreDisplay(n: number | null): string { + if (n === null) return "–" + return Number.isInteger(n) ? String(n) : n.toFixed(1) +} + +function SummarySection({ data }: { data: RubricJsonRecord }) { + const grade = asString(data.grade) + const total = pickScore(data, "total_score", "totalScore") + const prompt = pickScore(data, "prompt_score", "promptScore") + const correctness = pickScore( + data, + "correctness_score", + "correctnessScore", + "code_correctness_score", + "codeCorrectnessScore" + ) + const performance = pickScore( + data, + "performance_score", + "performanceScore", + "code_performance_score", + "codePerformanceScore" + ) + const holistic = pickScore(data, "holistic_flow_score", "holisticFlowScore") + const weights = isRecord(data.weights) ? data.weights : null + + const hasAny = + grade || + total !== null || + prompt !== null || + correctness !== null || + performance !== null || + holistic !== null || + weights + + if (!hasAny) return null + + return ( +
+
+ {grade && } + {total !== null && } + {prompt !== null && } + {correctness !== null && ( + + )} + {performance !== null && ( + + )} + {holistic !== null && ( + + )} +
+ {weights && ( +
+

가중치

+
+ {formatWeightLabel(weights.prompt, "프롬프트") && ( + {formatWeightLabel(weights.prompt, "프롬프트")} + )} + {formatWeightLabel(weights.correctness, "정답률") && ( + {formatWeightLabel(weights.correctness, "정답률")} + )} + {formatWeightLabel(weights.performance, "성능") && ( + {formatWeightLabel(weights.performance, "성능")} + )} +
+
+ )} +
+ ) +} + +const R4_CONTEXT_SECTION_TITLE = "R4 맥락 유지" +const R4_CONTEXT_SECTION_HINT = "대화 흐름과 문맥 유지 능력 평가" + +function HolisticSubsectionTitle({ title }: { title: string }) { + const displayTitle = useMemo(() => cleanupAiFeedbackText(title), [title]) + const showHint = displayTitle === R4_CONTEXT_SECTION_TITLE + return ( +
+

{displayTitle}

+ {showHint && ( + + + + )} +
+ ) +} + +function HolisticSection({ data }: { data: RubricJsonRecord }) { + const analysis = asString(data.holistic_flow_analysis) ?? asString(data.holisticFlowAnalysis) + if (!analysis) return null + + const sections = splitHolisticFlowAnalysis(analysis) + + return ( +
+
+ {sections.map((sec, i) => ( +
+ + +
+ ))} +
+
+ ) +} + +function CodeEvalReportSection({ data }: { data: RubricJsonRecord }) { + const report = data.code_eval_report ?? data.codeEvalReport + if (!isRecord(report)) return null + + const fields: { key: string; label: string }[] = [ + { key: "overall_summary", label: "종합 요약" }, + { key: "efficiency_review", label: "효율성 리뷰" }, + { key: "readability_review", label: "가독성 리뷰" }, + { key: "error_handling_review", label: "예외 처리 리뷰" }, + { key: "score_adjustment_note", label: "점수 조정 참고" }, + ] + + const items = fields + .map(({ key, label }) => { + const text = asString(report[key]) + return text ? { label, text } : null + }) + .filter((x): x is { label: string; text: string } => x != null) + + if (items.length === 0) return null + + return ( +
+
+ {items.map((item) => ( +
+

+ {item.label} +

+ +
+ ))} +
+
+ ) +} + +const DEBATE_AGENT_ORDER = ["strict", "advocate", "neutral"] + +function pickDebateBriefSummary(entry: RubricJsonRecord): string | null { + return ( + asString(entry.stance) ?? + asString(entry.summary) ?? + asString(entry.opinion) ?? + asString(entry.overview) ?? + null + ) +} + +function debateAgentSortKey(entry: RubricJsonRecord): number { + const agent = asString(entry.agent)?.toLowerCase() ?? "" + const idx = DEBATE_AGENT_ORDER.indexOf(agent) + return idx >= 0 ? idx : 100 +} + +function DebateAgentBadge({ agent }: { agent: string }) { + const key = agent.toLowerCase() + const tone = + key === "strict" + ? "bg-[#FEE2E2] text-[#B91C1C]" + : key === "advocate" + ? "bg-[#DCFCE7] text-[#15803D]" + : key === "neutral" + ? "bg-[#F3F4F6] text-[#374151]" + : "bg-[#E0EDFF] text-[#1D4ED8]" + return ( + + {formatDisplayLabel(agent)} + + ) +} + +function DebateRoundCompactRow({ entry }: { entry: RubricJsonRecord }) { + const agent = asString(entry.agent) ?? "–" + const summary = pickDebateBriefSummary(entry) + const suggested = asNumber(entry.suggested_score ?? entry.suggestedScore) + + return ( +
+
+ +
+
+ {summary ? ( +

+ {cleanupAiFeedbackText(summary)} +

+ ) : ( +

제공되지 않음

+ )} + {suggested !== null && ( +

제안 점수 {formatScoreDisplay(suggested)}

+ )} +
+
+ ) +} + +function DebateVerdictCard({ entry }: { entry: RubricJsonRecord }) { + const suggested = asNumber(entry.suggested_score ?? entry.suggestedScore) + const keyPoints = asStringArray(entry.key_points ?? entry.keyPoints) + const codeQ = asString(entry.code_quality_assessment ?? entry.codeQualityAssessment) + const promptQ = asString(entry.prompt_quality_assessment ?? entry.promptQualityAssessment) + const consensus = asString(entry.consensus_summary ?? entry.consensusSummary) + const holistic = asNumber(entry.holistic_flow_score ?? entry.holisticFlowScore) + const holisticAnalysis = asString(entry.holistic_flow_analysis ?? entry.holisticFlowAnalysis) + const scoreRationale = asString(entry.score_rationale ?? entry.scoreRationale) + const grade = asString(entry.grade) + const r4 = asNumber(entry.r4_context_maintenance_score ?? entry.r4ContextMaintenanceScore) + + return ( +
+
+ + Verdict + + {grade && ( + + 등급 {grade} + + )} + {holistic !== null && ( + Holistic {formatScoreDisplay(holistic)} + )} + {r4 !== null && R4 {formatScoreDisplay(r4)}} + {suggested !== null && ( + 제안 점수: {formatScoreDisplay(suggested)} + )} +
+ {consensus && ( +
+

합의 요약

+ +
+ )} + {holisticAnalysis && ( +
+

종합 분석

+ +
+ )} + {scoreRationale && ( +
+

점수 근거

+ +
+ )} + {keyPoints.length > 0 && ( +
+

핵심 포인트

+
    + {keyPoints.map((p, i) => ( +
  • + {cleanupAiFeedbackText(p)} +
  • + ))} +
+
+ )} + {codeQ && ( +
+

코드 품질 평가

+ +
+ )} + {promptQ && ( +
+

프롬프트 품질 평가

+ +
+ )} +
+ ) +} + +function DebateSection({ data }: { data: RubricJsonRecord }) { + const entries = collectDebateEntries(data) + if (entries.length === 0) return null + + const { roundNumbers, byRound, verdicts } = groupDebateEntriesByRound(entries) + + for (const list of byRound.values()) { + list.sort((a, b) => debateAgentSortKey(a) - debateAgentSortKey(b)) + } + + return ( +
+
+ {roundNumbers.map((roundNum) => { + const roundEntries = byRound.get(roundNum) ?? [] + if (roundEntries.length === 0) return null + return ( +
+

Round {roundNum}

+
+ {roundEntries.map((entry, i) => ( + + ))} +
+
+ ) + })} + {verdicts.length > 0 && ( +
+

최종 Verdict

+ {verdicts.map((entry, i) => ( + + ))} +
+ )} +
+
+ ) +} + +function TurnScoresSection({ data }: { data: RubricJsonRecord }) { + const raw = data.turn_scores ?? data.turnScores + if (!isRecord(raw) && !Array.isArray(raw)) return null + + const rows: { turn: string; score: string; detail: string }[] = [] + + if (isRecord(raw)) { + for (const [turn, val] of Object.entries(raw)) { + if (isRecord(val)) { + const ts = asNumber(val.turn_score ?? val.turnScore ?? val.score) + const parts: string[] = [] + if (hasPresentValue(val.intent)) parts.push(`intent: ${asString(val.intent)}`) + if (hasPresentValue(val.feedback)) { + parts.push(cleanupAiFeedbackText(asString(val.feedback) ?? "")) + } + rows.push({ + turn, + score: ts !== null ? formatScoreDisplay(ts) : "–", + detail: parts.join(" · ") || "–", + }) + } else { + const n = asNumber(val) + rows.push({ turn, score: n !== null ? formatScoreDisplay(n) : String(val), detail: "–" }) + } + } + } + + if (rows.length === 0) return null + + rows.sort((a, b) => { + const na = Number(a.turn) + const nb = Number(b.turn) + if (!Number.isNaN(na) && !Number.isNaN(nb)) return na - nb + return a.turn.localeCompare(b.turn) + }) + + return ( +
+
+
+ + + + + + + + + {rows.map((r) => ( + + + + + + ))} + +
Turn점수비고
{r.turn}{r.score}{r.detail}
+
+ + ) +} + +function QualityMetricsSection({ data }: { data: RubricJsonRecord }) { + const qm = data.code_quality_metrics ?? data.codeQualityMetrics + if (!isRecord(qm)) return null + + const radon = isRecord(qm.radon_cc) ? qm.radon_cc : isRecord(qm.radonCc) ? qm.radonCc : null + const refRadon = isRecord(qm.reference_radon_cc) + ? qm.reference_radon_cc + : isRecord(qm.referenceRadonCc) + ? qm.referenceRadonCc + : null + const deltaRef = isRecord(qm.delta_cc_vs_reference) + ? qm.delta_cc_vs_reference + : isRecord(qm.deltaCcVsReference) + ? qm.deltaCcVsReference + : null + const deltaCc = isRecord(qm.delta_cc) ? qm.delta_cc : isRecord(qm.deltaCc) ? qm.deltaCc : null + const v2Radon = isRecord(qm.v2_metrics) && isRecord(qm.v2_metrics.radon_cc) ? qm.v2_metrics.radon_cc : null + const functionLines = collectFunctionComplexityDisplayLines( + qm.functions, + radon?.functions, + v2Radon?.functions + ) + + const metrics: { key: string; label: string; value: string }[] = [] + const push = (metricKey: string, v: unknown) => { + const n = asNumber(v) + const s = asString(v) + const label = formatCodeQualityMetricLabel(metricKey) + if (n !== null) metrics.push({ key: metricKey, label, value: formatScoreDisplay(n) }) + else if (s) metrics.push({ key: metricKey, label, value: s }) + } + + if (radon) { + push("radon_cc.avg_cc", radon.avg_cc ?? radon.avgCc) + push("radon_cc.max_cc", radon.max_cc ?? radon.maxCc) + } + if (refRadon) { + push("reference_radon_cc.avg_cc", refRadon.avg_cc ?? refRadon.avgCc) + push("reference_radon_cc.max_cc", refRadon.max_cc ?? refRadon.maxCc) + } + if (deltaRef) { + push("delta_cc_vs_reference.delta_cc_pct", deltaRef.delta_cc_pct ?? deltaRef.deltaCcPct) + } + if (deltaCc && !deltaRef) { + push("delta_cc.delta_cc_pct", deltaCc.delta_cc_pct ?? deltaCc.deltaCcPct) + } + + if (metrics.length === 0 && functionLines.length === 0) return null + + return ( +
+ {metrics.length > 0 && ( +
+ {metrics.map((m) => ( + + ))} +
+ )} + {functionLines.length > 0 && ( +
+

+ 함수별 복잡도 +

+
    + {functionLines.map((fn, i) => ( +
  • + {fn} +
  • + ))} +
+
+ )} +
+ ) +} + +function RawJsonSection({ raw }: { raw: string }) { + const [open, setOpen] = useState(false) + return ( +
+ + {open && ( +
+          {raw}
+        
+ )} +
+ ) +} + +function StructuredReport({ data, rawPretty }: { data: RubricJsonRecord; rawPretty: string }) { + const hasStructured = rubricHasStructuredFields(data) + + return ( +
+ {!hasStructured && ( +

+ 파싱된 루브릭 데이터에 표시할 구조화 필드가 없습니다. 아래 원본 JSON을 확인하세요. +

+ )} + + + + + + + +
+ ) +} + +export function ParticipantEvaluationRubricReport({ + rubricJson, + isLoading = false, +}: ParticipantEvaluationRubricReportProps) { + const parsed = useMemo(() => parseRubricJson(rubricJson ?? null), [rubricJson]) + + if (isLoading) { + return

AI 평가 리포트를 불러오는 중…

+ } + + if (!rubricJson?.trim()) { + return ( +

+ 채점 루브릭 JSON(scores.rubric_json)이 + 아직 없습니다. +

+ ) + } + + if (!parsed) { + return + } + + if (!parsed.ok) { + return ( +
+

+ rubricJson JSON 파싱에 실패했습니다. 원본 문자열을 표시합니다. + {parsed.error ? ` (${parsed.error})` : ""} +

+
+          {parsed.raw}
+        
+
+ ) + } + + const rawPretty = formatRubricJsonPretty(parsed.data) + return +} diff --git a/components/participant-evaluation-test-summary.tsx b/components/participant-evaluation-test-summary.tsx new file mode 100644 index 0000000..5ca005f --- /dev/null +++ b/components/participant-evaluation-test-summary.tsx @@ -0,0 +1,262 @@ +"use client" + +import type { + AdminSubmissionDetailResponse, + AdminSubmissionGroupInfo, + AdminSubmissionRunGroup, + AdminSubmissionCaseRunInfo, +} from "@/lib/api/admin" + +const TC_GROUP_ORDER: AdminSubmissionRunGroup[] = ["SAMPLE", "PUBLIC", "PRIVATE"] + +const TC_GROUP_LABEL: Record = { + SAMPLE: "샘플 (SAMPLE)", + PUBLIC: "공개 (PUBLIC)", + PRIVATE: "비공개 (PRIVATE)", +} + +const TC_GROUP_WEIGHT: Record = { + SAMPLE: 0.1, + PUBLIC: 0.3, + PRIVATE: 0.6, +} + +const VERDICT_LABEL: Record = { + AC: "정답 (AC)", + WA: "오답 (WA)", + TLE: "시간 초과 (TLE)", + MLE: "메모리 초과 (MLE)", + RE: "런타임 오류 (RE)", +} + +function formatSubmissionStatusDetailKo( + status: AdminSubmissionDetailResponse["status"] | undefined +): string { + if (!status) return "–" + const map: Record = { + QUEUED: "대기 (QUEUED)", + RUNNING: "실행·채점 중 (RUNNING)", + DONE: "완료 (DONE)", + FAILED: "실패 (FAILED)", + } + return map[status] ?? status +} + +function normalizeRunGroupName(name: unknown): AdminSubmissionRunGroup | null { + const raw = + typeof name === "string" + ? name + : name != null && typeof name === "object" && "name" in name + ? String((name as { name: unknown }).name) + : String(name) + if (raw === "SAMPLE" || raw === "PUBLIC" || raw === "PRIVATE") return raw + return null +} + +function mergeTcGroupsForDisplay(groups: AdminSubmissionGroupInfo[] | undefined) { + const map = new Map() + for (const g of groups ?? []) { + const key = normalizeRunGroupName(g.name) + if (key) map.set(key, { ...g, name: key }) + } + return TC_GROUP_ORDER.map((name) => { + const g = map.get(name) + return { + name, + label: TC_GROUP_LABEL[name], + pass: g?.pass ?? 0, + total: g?.total ?? 0, + weight: g?.weight ?? TC_GROUP_WEIGHT[name], + } + }) +} + +function aggregateGroupsFromRuns(runs: AdminSubmissionCaseRunInfo[]): AdminSubmissionGroupInfo[] { + const acc = new Map() + for (const r of runs) { + const cur = acc.get(r.grp) ?? { pass: 0, total: 0 } + cur.total += 1 + if (r.verdict === "AC") cur.pass += 1 + acc.set(r.grp, cur) + } + return TC_GROUP_ORDER.filter((name) => acc.has(name)).map((name) => ({ + name, + pass: acc.get(name)!.pass, + total: acc.get(name)!.total, + weight: TC_GROUP_WEIGHT[name], + })) +} + +export interface ParticipantEvaluationTestSummaryProps { + submissionId: number | null + isLoading: boolean + detail: AdminSubmissionDetailResponse | null + boardStatusLabel: string | null +} + +export function ParticipantEvaluationTestSummary({ + submissionId, + isLoading, + detail, + boardStatusLabel, +}: ParticipantEvaluationTestSummaryProps) { + const displayGroups = (() => { + const fromApi = detail?.tc?.groups + if (fromApi && fromApi.length > 0) return mergeTcGroupsForDisplay(fromApi) + const runs = detail?.runs + if (runs && runs.length > 0) return mergeTcGroupsForDisplay(aggregateGroupsFromRuns(runs)) + return mergeTcGroupsForDisplay([]) + })() + + const hasAnyTcData = + (detail?.tc?.groups?.length ?? 0) > 0 || (detail?.runs?.length ?? 0) > 0 + + const failedRuns = (detail?.runs ?? []).filter((r) => r.verdict !== "AC") + + return ( +
+ {isLoading && submissionId != null && ( +

제출 상세·테스트 결과를 불러오는 중…

+ )} + {!isLoading && submissionId == null && ( +

제출 기록이 없어 테스트 결과를 표시할 수 없습니다.

+ )} + {!isLoading && submissionId != null && !detail && ( +

+ 제출 상세를 불러오지 못했습니다. 네트워크·관리자 권한을 확인하세요. +

+ )} + {detail && ( +
+
+
+

제출 상태

+

+ {formatSubmissionStatusDetailKo(detail.status)} +

+ {boardStatusLabel && ( +

보드: {boardStatusLabel}

+ )} +
+
+

실행 시간

+

+ {detail.metrics?.timeMsMedian != null ? `${detail.metrics.timeMsMedian} ms` : "–"} +

+

중앙값 (submission_runs)

+
+
+

메모리

+

+ {detail.metrics?.memKbPeak != null ? `${detail.metrics.memKbPeak} KB` : "–"} +

+

peak (submission_runs)

+
+
+

코드 LOC

+

+ {detail.metrics?.loc != null ? detail.metrics.loc : "–"} +

+

submissions.code_loc

+
+
+ +
+

테스트 그룹별 결과

+ {hasAnyTcData ? ( + <> +
+ + + + + + + + + + + {displayGroups.map((g) => { + const rate = g.total > 0 ? (g.pass / g.total) * 100 : 0 + return ( + + + + + + + ) + })} + +
그룹통과 / 전체통과율가중치
{g.label} + {g.pass} / {g.total} + + {g.total > 0 ? `${rate.toFixed(0)}%` : "–"} + {(g.weight * 100).toFixed(0)}%
+
+ {detail.tc?.passRateWeighted != null && ( +

+ 가중 통과율 (API): {(Number(detail.tc.passRateWeighted) * 100).toFixed(1)}% +

+ )} + + ) : ( +

+ submission_runs 집계 데이터가 없습니다. 채점 완료 후에도 비어 있으면 테스트 결과가 DB에 + 저장되지 않았을 수 있습니다. +

+ )} +
+ + {failedRuns.length > 0 ? ( +
+

실패·비정답 케이스

+
+ + + + + + + + + + + + {failedRuns.map((r) => ( + + + + + + + + ))} + +
케이스그룹판정시간메모리
#{r.caseIndex}{TC_GROUP_LABEL[r.grp]}{VERDICT_LABEL[r.verdict] ?? r.verdict} + {r.timeMs != null ? `${r.timeMs} ms` : "–"} + + {r.memKb != null ? `${r.memKb} KB` : "–"} +
+
+

출처: 관리자 API runs[] (submission_runs)

+
+ ) : hasAnyTcData ? ( +

모든 기록된 케이스가 정답(AC)입니다.

+ ) : null} + +
+

현재 API에서 제공되지 않음

+
    +
  • 테스트 케이스별 expected / actual 입·출력 상세
  • +
  • 표준 출력·에러 본문 (stdout_bytes / stderr_bytes는 API 미노출)
  • +
+
+
+ )} +
+ ) +} diff --git a/components/participant-list-content.tsx b/components/participant-list-content.tsx index 5c22241..92af3fa 100644 --- a/components/participant-list-content.tsx +++ b/components/participant-list-content.tsx @@ -3,7 +3,8 @@ import { useState, useEffect, useMemo } from "react" import Link from "next/link" import { ArrowLeft, Eye, ChevronLeft, ChevronRight } from "lucide-react" -import { getExams, getBoard, ExamineeBoardEntry } from "@/lib/api/admin" +import { getExams, getBoard, ExamineeBoardEntry, type Exam } from "@/lib/api/admin" +import { adminParticipantEvaluationHref } from "@/lib/paths/admin-participant-evaluation" type TrendLevel = "High" | "Average" | "Low" @@ -20,6 +21,31 @@ interface ParticipantListContentProps { entryCode: string } +/** + * /admin/results/[segment] 세그먼트로 시험을 찾습니다. + * - API entryCode와 일치(있을 때) + * - 시험 제목과 일치(평가 결과 목록이 title을 URL에 넣는 기존 동작) + * - 전부 숫자면 exam.id (직접 링크용) + */ +function findExamByResultsSegment(exams: Exam[], segment: string) { + const trimmed = segment.trim() + if (!trimmed) return undefined + + const byEntryCode = exams.find( + (e) => e.entryCode != null && String(e.entryCode).length > 0 && e.entryCode === trimmed + ) + if (byEntryCode) return byEntryCode + + const byTitle = exams.find((e) => e.title === trimmed) + if (byTitle) return byTitle + + if (/^\d+$/.test(trimmed)) { + return exams.find((e) => String(e.id) === trimmed) + } + + return undefined +} + function TrendBadge({ trend }: { trend: TrendLevel }) { const styles = { High: "bg-[#DCFCE7] text-[#16A34A]", @@ -58,7 +84,7 @@ export function ParticipantListContent({ entryCode }: ParticipantListContentProp try { // 1) 시험 목록에서 entryCode에 매핑된 examId 찾기 const exams = await getExams() - const matched = exams.find((e) => e.entryCode === entryCode) + const matched = findExamByResultsSegment(exams, entryCode) if (!matched) { // entryCode로 직접 매핑이 안 될 때 — 첫 번째 시험 또는 에러 setError("해당 입장 코드에 대한 시험을 찾을 수 없습니다.") @@ -197,14 +223,12 @@ export function ParticipantListContent({ entryCode }: ParticipantListContentProp
diff --git a/components/platform-logs-content.tsx b/components/platform-logs-content.tsx index b4713fb..04503ad 100644 --- a/components/platform-logs-content.tsx +++ b/components/platform-logs-content.tsx @@ -4,6 +4,7 @@ import { useState } from "react" import { Input } from "@/components/ui/input" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" import { Search } from "lucide-react" +import { AdminPageHeader } from "@/components/admin-page-header" type LogType = "Admin Activity" | "System" | "Error" type BadgeType = "System Updated" | "Error" | "Admin Change" | "Evaluation Completed" | "Room Started" @@ -310,32 +311,13 @@ export function PlatformLogsContent() { const sortedDates = Object.keys(groupedLogs).sort((a, b) => b.localeCompare(a)) return ( -
- {/* Page Header */} -
-

- 플랫폼 로그 -

-

- 플랫폼 전역의 시스템 활동 로그를 확인하고 모니터링합니다. -

-
+
+ +
{/* Search Bar and Filters Row */}
{/* Search Bar */} @@ -555,6 +537,7 @@ export function PlatformLogsContent() {
)}
+
) } diff --git a/components/problem-content-md-view.tsx b/components/problem-content-md-view.tsx new file mode 100644 index 0000000..11c27e3 --- /dev/null +++ b/components/problem-content-md-view.tsx @@ -0,0 +1,39 @@ +/** + * 문제 본문(contentMd) 표시 — 사용자 시험 화면(problem-section)과 동일한 스타일 + */ +export const PROBLEM_CONTENT_MD_CLASS = + "text-[#4B5563] text-sm leading-relaxed whitespace-pre-wrap" + +type ProblemContentMdViewProps = { + contentMd: string | null | undefined + className?: string + emptyLabel?: string + /** 모달 등 긴 본문용 내부 스크롤 */ + scrollable?: boolean + maxHeight?: string +} + +export function ProblemContentMdView({ + contentMd, + className = "", + emptyLabel = "등록된 문제 본문이 없습니다.", + scrollable = false, + maxHeight, +}: ProblemContentMdViewProps) { + const text = contentMd?.trim() + + if (!text) { + return

{emptyLabel}

+ } + + return ( +
+ {text} +
+ ) +} diff --git a/components/problem-content.tsx b/components/problem-content.tsx index c7b885b..d8622a7 100644 --- a/components/problem-content.tsx +++ b/components/problem-content.tsx @@ -1,268 +1,201 @@ "use client" -import { useState } from "react" +import { useCallback, useEffect, useMemo, useState } from "react" import { Search, Eye } from "lucide-react" import { Input } from "@/components/ui/input" import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog" +import { AdminPageHeader } from "@/components/admin-page-header" +import { ProblemContentMdView } from "@/components/problem-content-md-view" +import { getProblems, getProblemDetail, type AdminProblem } from "@/lib/api/admin" +import { + buildMasterProblemDetailFromApi, + filterMasterProblems, + mapAdminProblemToMasterListItem, + type MasterProblemDetail, + type MasterProblemListItem, + type ProblemDifficultyKo, +} from "@/lib/master-problems" -const initialProblems = [ - { - id: 1, - title: "문제 1. 문자열 압축하기", - createdBy: "John Smith", - lastUpdated: "2일 전", - usedInSessions: 12, - description: - "주어진 문자열에서 연속으로 반복되는 문자를 압축하여 표현하세요. 연속으로 반복되는 문자는 해당 문자와 반복 횟수로 표현합니다. 반복 횟수가 1인 경우에는 숫자를 생략합니다.", - example: "aabbaccc → 2a2ba3c", - inputExample: "aabbaccc", - outputExample: "2a2ba3c", - }, - { - id: 2, - title: "문제 2. 이진 탐색 구현", - createdBy: "Sarah Johnson", - lastUpdated: "5일 전", - usedInSessions: 8, - description: - "정렬된 배열에서 특정 값의 위치를 이진 탐색 알고리즘을 사용하여 찾으세요. 값이 존재하면 해당 인덱스를, 존재하지 않으면 -1을 반환합니다.", - example: "[1, 3, 5, 7, 9], target=5 → 2", - inputExample: "[1, 3, 5, 7, 9]\ntarget = 5", - outputExample: "2", - }, - { - id: 3, - title: "문제 3. 연결 리스트 뒤집기", - createdBy: "Mike Davis", - lastUpdated: "1주 전", - usedInSessions: 15, - description: - "단일 연결 리스트가 주어졌을 때, 리스트의 순서를 뒤집어서 반환하세요. 리스트의 각 노드는 정수 값을 가지고 있습니다.", - example: "1 → 2 → 3 → 4 → 5 를 5 → 4 → 3 → 2 → 1 로 변환", - inputExample: "1 → 2 → 3 → 4 → 5", - outputExample: "5 → 4 → 3 → 2 → 1", - }, - { - id: 4, - title: "문제 4. 배낭 문제 (동적 프로그래밍)", - createdBy: "John Smith", - lastUpdated: "3일 전", - usedInSessions: 6, - description: - "무게 제한이 있는 배낭에 최대 가치를 담을 수 있도록 물건을 선택하세요. 각 물건은 무게와 가치를 가지며, 같은 물건을 여러 번 선택할 수 없습니다.", - example: "배낭 용량 10, 물건들: [(5, 10), (4, 40), (6, 30), (3, 50)] → 최대 가치: 90", - inputExample: "capacity = 10\nitems = [(5,10), (4,40), (6,30), (3,50)]", - outputExample: "90", - }, -] - -type Problem = { - id: number - title: string - createdBy: string - lastUpdated: string - usedInSessions: number - description: string - example: string - inputExample: string - outputExample: string +function DifficultyBadge({ difficulty }: { difficulty: ProblemDifficultyKo }) { + const styles = { + 쉬움: "bg-[#D1FAE5] text-[#059669]", + 중간: "bg-[#FEF3C7] text-[#D97706]", + 어려움: "bg-[#FEE2E2] text-[#DC2626]", + } + return ( + + {difficulty} + + ) } export function ProblemContent() { - const [problems] = useState(initialProblems) + const [problems, setProblems] = useState([]) + const [isLoading, setIsLoading] = useState(true) + const [loadError, setLoadError] = useState(false) const [searchQuery, setSearchQuery] = useState("") - const [selectedProblem, setSelectedProblem] = useState(null) + const [selectedProblem, setSelectedProblem] = useState(null) const [isModalOpen, setIsModalOpen] = useState(false) + const [detailLoading, setDetailLoading] = useState(false) + const [detailError, setDetailError] = useState(false) + const [modalTitle, setModalTitle] = useState("문제 상세 정보") + + const fetchProblems = useCallback(async () => { + setIsLoading(true) + setLoadError(false) + try { + const adminProblems = await getProblems() + const mapped = adminProblems.map((p: AdminProblem) => mapAdminProblemToMasterListItem(p)) + setProblems(mapped) + } catch (e) { + console.error("[MasterProblem] Failed to fetch problems:", e) + setProblems([]) + setLoadError(true) + } finally { + setIsLoading(false) + } + }, []) - const filteredProblems = problems.filter( - (problem) => - problem.title.toLowerCase().includes(searchQuery.toLowerCase()) || - problem.createdBy.toLowerCase().includes(searchQuery.toLowerCase()), + useEffect(() => { + void fetchProblems() + }, [fetchProblems]) + + const filteredProblems = useMemo( + () => filterMasterProblems(problems, searchQuery), + [problems, searchQuery] ) - const handleViewDetail = (problem: Problem) => { - setSelectedProblem(problem) + const handleViewDetail = async (problem: MasterProblemListItem) => { + setModalTitle(problem.title) setIsModalOpen(true) + setDetailLoading(true) + setDetailError(false) + setSelectedProblem(null) + + try { + const detail = await getProblemDetail(problem.id) + setSelectedProblem(buildMasterProblemDetailFromApi(problem, detail)) + } catch (e) { + console.error("[MasterProblem] Failed to load detail:", e) + setDetailError(true) + } finally { + setDetailLoading(false) + } } - const handleCloseModal = () => { - setIsModalOpen(false) - setSelectedProblem(null) + const handleCloseModal = (open: boolean) => { + setIsModalOpen(open) + if (!open) { + setSelectedProblem(null) + setDetailError(false) + setDetailLoading(false) + } } return ( -
- {/* Page Header */} -
-

- 문제 관리 -

-

- 플랫폼에서 사용되는 모든 문제를 검토하고 관리합니다. -

-
+
+ - {/* Search Bar */} -
- - setSearchQuery(e.target.value)} - className="pl-10 h-11 rounded-lg border-[#E5E5E5] bg-white" - style={{ - fontSize: "14px", - fontWeight: 400, - }} - /> -
+
+
+ + setSearchQuery(e.target.value)} + className="h-11 rounded-lg border-[#E5E5E5] bg-white pl-10" + style={{ fontSize: "14px", fontWeight: 400 }} + disabled={isLoading && problems.length === 0} + /> +
- {/* Card List */} -
- {filteredProblems.map((problem) => ( -
handleViewDetail(problem)} - className="flex items-center justify-between bg-white border border-[#E5E5E5] rounded-xl p-5 cursor-pointer transition-all duration-200 hover:shadow-md hover:scale-[1.01]" - style={{ - borderRadius: "12px", - }} - > - {/* Left Side - Problem Info */} -
- {/* Problem Title */} -
-

- {problem.title} -

-
+ {isLoading ? ( +

문제를 불러오는 중…

+ ) : loadError ? ( +

문제 목록을 불러오지 못했습니다.

+ ) : problems.length === 0 ? ( +

등록된 문제가 없습니다.

+ ) : ( +
+ {filteredProblems.map((problem) => ( +
void handleViewDetail(problem)} + > +
+
+
+

+ {problem.title} +

+ {problem.versionLabel} + +
+ {problem.tags.length > 0 && ( +
+ {problem.tags.map((tag) => ( + + {tag} + + ))} +
+ )} +
- {/* Created By */} -
- - 생성자 - - - {problem.createdBy} - -
+
+ + 마지막 업데이트 + + + {problem.lastUpdatedLabel} + +
+
- {/* Last Updated */} -
- { + e.stopPropagation() + void handleViewDetail(problem) }} + className="flex shrink-0 items-center gap-2 rounded-lg px-4 py-2 text-blue-600 transition-colors hover:bg-blue-50" + style={{ fontSize: "14px", fontWeight: 500 }} > - 마지막 업데이트 - - - {problem.lastUpdated} - + + 상세 보기 +
+ ))} - {/* Used In Sessions */} -
- - 사용된 세션 - - - {problem.usedInSessions}개 - + {filteredProblems.length === 0 && ( +
+

검색 결과가 없습니다.

-
- - {/* Right Side - View Detail Button */} - -
- ))} - - {/* Empty State */} - {filteredProblems.length === 0 && ( -
-

검색 결과가 없습니다.

+ )}
)} -
+
- + - {selectedProblem && ( -
- {/* Title Area */} - - - {selectedProblem.title} - -

- 생성자: {selectedProblem.createdBy} · 마지막 업데이트: {selectedProblem.lastUpdated} -

-
+ + {modalTitle} 상세 정보 + - {/* Problem Description Box */} -
-

- 문제 설명 -

-

- {selectedProblem.description} -

-
- 예: - {selectedProblem.example} -
-
+ {detailLoading && ( +

상세 정보를 불러오는 중…

+ )} - {/* Example Input/Output Section */} -
- {/* Input Example */} -
-

- 입력 예시 -

-
- {selectedProblem.inputExample} + {detailError && !detailLoading && ( +

문제 상세를 불러오지 못했습니다.

+ )} + + {selectedProblem && !detailLoading && ( +
+
+ +
+

+ {selectedProblem.title} +

+ {selectedProblem.versionLabel} +
-
+ {selectedProblem.tags.length > 0 && ( +
+ {selectedProblem.tags.map((tag) => ( + + {tag} + + ))} +
+ )} +

+ 마지막 업데이트: {selectedProblem.lastUpdatedLabel} + {selectedProblem.usable ? " · 사용 가능" : " · 사용 불가"} +

+ +
- {/* Output Example */} -
-

- 출력 예시 -

+
+
- {selectedProblem.outputExample} +

+ 문제 설명 +

+
+ + {selectedProblem.restrictionsInfo !== "정보 없음" && ( +
+

+ 제한 정보 +

+

+ {selectedProblem.restrictionsInfo} +

+
+ )}
diff --git a/components/problem-section.tsx b/components/problem-section.tsx index 5db2496..b06ddae 100644 --- a/components/problem-section.tsx +++ b/components/problem-section.tsx @@ -1,6 +1,7 @@ "use client" import { useState, useEffect } from "react" +import { ProblemContentMdView } from "@/components/problem-content-md-view" import { getAssignment, AssignmentResponse } from "@/lib/api/exams" interface ProblemSectionProps { @@ -10,12 +11,71 @@ interface ProblemSectionProps { export function ProblemSection({ examId }: ProblemSectionProps) { const [assignment, setAssignment] = useState(null) const [loading, setLoading] = useState(true) + const [errorMessage, setErrorMessage] = useState(null) useEffect(() => { - getAssignment(examId) - .then(setAssignment) - .catch(() => {/* 로드 실패 시 null 유지 */}) - .finally(() => setLoading(false)) + let cancelled = false + + const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)) + const isRetryableNoAssignment = (err: any) => { + const status = err?.status + const code = err?.code + const msg = String(err?.apiMessage || err?.message || "") + return ( + status === 400 || + code === "PROBLEM005" || + msg.includes("배정된 문제가 없습니다") + ) + } + + const load = async () => { + setLoading(true) + setErrorMessage(null) + + const maxAttempts = 6 + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + const res = await getAssignment(examId) + if (cancelled) return + setAssignment(res) + setLoading(false) + return + } catch (err: any) { + if (cancelled) return + + // 인증 실패는 재시도 대신 별도 안내(자동 리다이렉트 금지) + if (err?.status === 401) { + setAssignment(null) + setErrorMessage("인증이 필요합니다. 다시 입장해주세요.") + setLoading(false) + return + } + + // 배정 지연(PROBLEM005)만 짧게 재시도 + if (isRetryableNoAssignment(err) && attempt < maxAttempts) { + if (process.env.NODE_ENV === "development") { + console.warn(`[ProblemSection] assignment not ready (attempt ${attempt}/${maxAttempts}), retrying...`, err) + } + await sleep(1000) + if (cancelled) return + continue + } + + if (process.env.NODE_ENV === "development") { + console.warn("[ProblemSection] getAssignment failed:", err) + } + setAssignment(null) + setErrorMessage("문제를 불러올 수 없습니다.") + setLoading(false) + return + } + } + } + + void load() + return () => { + cancelled = true + } }, [examId]) const problem = assignment?.problem @@ -23,14 +83,16 @@ export function ProblemSection({ examId }: ProblemSectionProps) { return (

- {loading ? "문제 로딩 중..." : problem ? `문제. ${problem.title}` : "문제를 불러올 수 없습니다."} + {loading + ? "문제 배정을 확인하는 중입니다..." + : problem + ? `문제. ${problem.title}` + : (errorMessage ?? "문제를 불러올 수 없습니다.")}

{problem && ( <> -
- {problem.contentMd} -
+
{problem.tags.map((tag) => ( diff --git a/components/results-content.tsx b/components/results-content.tsx index 687d4c9..5076622 100644 --- a/components/results-content.tsx +++ b/components/results-content.tsx @@ -2,8 +2,13 @@ import { useState, useEffect } from "react" import Link from "next/link" -import { Search, Download, Eye, X, CheckCircle, ChevronLeft, ChevronRight } from "lucide-react" -import { getExams, type Exam } from "@/lib/api/admin" +import { Search, Download, Eye, X, CheckCircle, ChevronLeft, ChevronRight, Loader2 } from "lucide-react" +import { getExams, getBoard, type Exam } from "@/lib/api/admin" +import { + buildBoardParticipantsCsvBody, + downloadUtf8Csv, + sanitizeCsvFilenameSegment, +} from "@/lib/admin-board-csv-export" interface ResultEntry { id: string @@ -23,6 +28,7 @@ export function ResultsContent() { const [isLoading, setIsLoading] = useState(true) const [searchQuery, setSearchQuery] = useState("") const [toasts, setToasts] = useState([]) + const [downloadingExamId, setDownloadingExamId] = useState(null) const [currentPage, setCurrentPage] = useState(1) const pageSize = 10 @@ -40,7 +46,8 @@ export function ResultsContent() { const exams = await getExams() const mapped: ResultEntry[] = exams.map((exam: Exam) => ({ id: String(exam.id), - entryCode: exam.title, + // BE ExamResponse에 entryCode가 없을 수 있음 — 목록 표시·상세 URL은 title과 동기화 + entryCode: exam.entryCode?.trim() || exam.title, total: exam.participantCount, completed: exam.completedCount, })) @@ -60,11 +67,32 @@ export function ResultsContent() { setToasts((prev) => prev.filter((t) => t.id !== id)) } - const handleDownload = (entryCode: string) => { - showToast( - "CSV 다운로드 준비 중", - "현재 해당 기능을 서버에서 준비 중입니다. 조만간 업데이트될 예정입니다.", - ) + const handleDownload = async (result: ResultEntry) => { + const examId = Number.parseInt(result.id, 10) + if (Number.isNaN(examId)) { + showToast("다운로드 실패", "유효하지 않은 시험 ID입니다.") + return + } + + setDownloadingExamId(result.id) + try { + const board = await getBoard(examId) + const csvBody = buildBoardParticipantsCsvBody( + board.map((entry) => ({ entry, examLabel: result.entryCode })), + { includeScores: true } + ) + const filename = `results-${sanitizeCsvFilenameSegment(result.entryCode)}.csv` + downloadUtf8Csv(filename, csvBody) + showToast("다운로드 완료", `${result.entryCode} 세션 결과가 CSV로 저장되었습니다.`) + } catch (error) { + console.error(`[Results] CSV download failed for examId=${examId}`, error) + showToast( + "다운로드 실패", + "참가자 결과를 불러오지 못했습니다. 잠시 후 다시 시도해 주세요." + ) + } finally { + setDownloadingExamId(null) + } } const filteredResults = results.filter((result) => result.entryCode.toLowerCase().includes(searchQuery.toLowerCase())) @@ -210,15 +238,21 @@ export function ResultsContent() { {/* Right Side - Action Buttons */}
= { + api: Server, + database: Database, + ai: Cpu, +} -const metricsData = [ - { id: 1, label: "CPU 사용량", value: "34%", icon: Activity }, - { id: 2, label: "메모리 사용량", value: "2.4 GB / 8 GB", icon: HardDrive }, - { id: 3, label: "활성화된 연결 수", value: "4", icon: Users }, +const FALLBACK_SERVICES: SystemStatusServiceItem[] = [ + { key: "api", name: "API 서버", status: "DOWN", latencyMs: null }, + { key: "database", name: "데이터베이스", status: "DOWN", latencyMs: null }, + { key: "ai", name: "AI 게이트웨이", status: "DOWN", latencyMs: null }, ] +function formatLatency(latencyMs: number | null | undefined, isLoading: boolean): string { + if (isLoading) return "–" + if (latencyMs === null || latencyMs === undefined || Number.isNaN(Number(latencyMs))) { + return "–" + } + return `${Math.round(Number(latencyMs))}ms` +} + +function formatStatusLabel(status: string | undefined, isLoading: boolean): string { + if (isLoading) return "–" + if (status === "UP") return "정상 운영 중" + return "점검 필요" +} + +function statusBadgeClass(status: string | undefined, isLoading: boolean): string { + if (isLoading) { + return "px-3 py-1 text-xs font-medium text-[#6B7280] bg-[#F3F4F6] border border-[#E5E7EB] rounded-full" + } + if (status === "UP") { + return "px-3 py-1 text-xs font-medium text-[#059669] bg-[#ECFDF5] border border-[#A7F3D0] rounded-full" + } + return "px-3 py-1 text-xs font-medium text-[#B91C1C] bg-[#FEF2F2] border border-[#FECACA] rounded-full" +} + export function ServerStatusContent() { + const [services, setServices] = useState([]) + const [isLoading, setIsLoading] = useState(true) + const [loadError, setLoadError] = useState(false) + + useEffect(() => { + let cancelled = false + + async function load() { + setIsLoading(true) + setLoadError(false) + try { + const data = await getSystemStatus() + if (!cancelled) { + setServices(data.services?.length ? data.services : FALLBACK_SERVICES) + } + } catch (e) { + console.error("[ServerStatus] Failed to load system status", e) + if (!cancelled) { + setLoadError(true) + setServices(FALLBACK_SERVICES) + } + } finally { + if (!cancelled) setIsLoading(false) + } + } + + load() + return () => { + cancelled = true + } + }, []) + + const displayServices = services.length > 0 ? services : FALLBACK_SERVICES + return ( -
- {/* Header Section */} -
+
+

서버 상태

-

시스템 상태 및 성능

+

핵심 서비스 연결 상태

- {/* Main Content Section */} -
-
- {/* Services Section */} -
-

서비스

-
- {servicesData.map((service) => { - const IconComponent = service.icon - return ( -
- {/* Left: Icon + Name */} -
- - {service.name} -
- - {/* Right: Latency + Status */} -
- {service.latency} - - {service.status} - -
-
- ) - })} +
+
+ {loadError && ( +
+

+ 시스템 상태를 불러오지 못했습니다. 아래는 기본 표시입니다. +

-
+ )} - {/* System Metrics Section */} -
-

시스템 지표

-
- {metricsData.map((metric) => { - const IconComponent = metric.icon - return ( -
- {/* Left: Icon + Label */} -
- - {metric.label} -
+

서비스

+
+ {displayServices.map((service) => { + const IconComponent = SERVICE_ICONS[service.key] ?? Server + return ( +
+
+ + {service.name} +
- {/* Right: Value */} - {metric.value} +
+ {service.key !== "api" && ( + + {formatLatency(service.latencyMs, isLoading)} + + )} + + {formatStatusLabel(service.status, isLoading)} +
- ) - })} -
+
+ ) + })}
diff --git a/components/settings-content.tsx b/components/settings-content.tsx index 223c2fc..913c794 100644 --- a/components/settings-content.tsx +++ b/components/settings-content.tsx @@ -14,7 +14,15 @@ import { import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" -import { logoutAdmin, getMe, changeAdminPassword, LoginFailedError, NetworkError } from "@/lib/api/admin" +import { + logoutAdmin, + getMe, + changeAdminPassword, + LoginFailedError, + NetworkError, + resolveAdminDisplayNameFromMe, + resolveAdminNumberFromMe, +} from "@/lib/api/admin" import { useToast } from "@/hooks/use-toast" import { Lock } from "lucide-react" @@ -47,12 +55,10 @@ export function SettingsContent() { setIsLoading(true); try { const response = await getMe(); - // ADMIN의 경우: participant.name = adminNumber, participant.phone = email - // 이름은 백엔드에서 제공하지 않으므로 더미 데이터 사용 setAdminProfile({ - name: "Admin", // 더미 데이터 (백엔드에서 제공되지 않음) - email: response.participant.phone || "", // email - adminNumber: response.participant.name || "", // adminNumber + name: resolveAdminDisplayNameFromMe(response), + email: response.participant.phone || "", + adminNumber: resolveAdminNumberFromMe(response), }); } catch (error) { if (error instanceof LoginFailedError) { @@ -237,7 +243,7 @@ export function SettingsContent() { {isLoading ? (
- +
- + diff --git a/components/test-session-details-content.tsx b/components/test-session-details-content.tsx index b7b4f00..5d0e9de 100644 --- a/components/test-session-details-content.tsx +++ b/components/test-session-details-content.tsx @@ -1,113 +1,206 @@ "use client" -import { useEffect, useState } from "react" -import { useRouter } from "next/navigation" +import { useCallback, useEffect, useState } from "react" import { ArrowLeft, ChevronLeft, ChevronRight } from "lucide-react" import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" import { Badge } from "@/components/ui/badge" import { Button } from "@/components/ui/button" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table" -import Link from "next/link"; -import { getBoard } from "@/lib/api/admin"; +import Link from "next/link" +import { getBoard, getExams, formatBoardSubmissionLabelKo, type Exam } from "@/lib/api/admin" +import { masterParticipantEvaluationHref } from "@/lib/paths/master-participant-evaluation" +import { AdminPageHeader } from "@/components/admin-page-header" +import { + getExamDisplayDate, + getMasterSessionStatusLabel, + mapExamToTestSession, + mapMasterParticipantExamStatus, +} from "@/lib/master-test-sessions" -// Participant type type Participant = { id: number name: string phoneNumber: string - connectionStatus: string - submissionStatus: string + examStatus: string + hasSubmission: boolean + submissionStatusLabel: string tokenUsage: number } interface TestSessionDetailsContentProps { - session: { - id: number - sessionId: string - createdBy: string - createdAt: string - status: string - participants: number - } + examId: number | null onBack: () => void } -export default function TestSessionDetailsContent({ session, onBack }: TestSessionDetailsContentProps) { - const router = useRouter() +export default function TestSessionDetailsContent({ examId, onBack }: TestSessionDetailsContentProps) { + const [exam, setExam] = useState(null) + const [examLoading, setExamLoading] = useState(true) + const [examError, setExamError] = useState(false) const [participants, setParticipants] = useState([]) - const [isLoading, setIsLoading] = useState(true) + const [participantsLoading, setParticipantsLoading] = useState(false) + const [participantsError, setParticipantsError] = useState(false) const [currentPage, setCurrentPage] = useState(1) const itemsPerPage = 10 - const fetchParticipants = async () => { - setIsLoading(true); + const loadExam = useCallback(async () => { + if (examId == null) { + setExam(null) + setExamLoading(false) + setExamError(false) + return + } + + setExamLoading(true) + setExamError(false) + try { + const exams = await getExams() + const found = exams.find((e) => e.id === examId) ?? null + setExam(found) + if (!found) setExamError(true) + } catch (e) { + console.error("[TestSessionDetails] Failed to load exam:", e) + setExam(null) + setExamError(true) + } finally { + setExamLoading(false) + } + }, [examId]) + + const loadParticipants = useCallback(async () => { + if (examId == null || !Number.isFinite(examId) || examId <= 0) { + setParticipants([]) + return + } + + setParticipantsLoading(true) + setParticipantsError(false) try { - const board = await getBoard(session.id); - const mapped: Participant[] = board.map((p) => ({ - id: p.examParticipantId, - name: p.name, - phoneNumber: p.phoneMasked, - connectionStatus: p.state === "ENTRANCE" ? "Connected" : "Pending", - submissionStatus: p.submitted - ? "Submitted" - : p.state === "ENTRANCE" - ? "In Progress" - : "Not Started", - tokenUsage: p.tokenUsed || 0, - })); - setParticipants(mapped); - } catch (error) { - console.error("Failed to fetch participants:", error); + const board = await getBoard(examId) + const examState = exam?.state + const mapped: Participant[] = board.map((p) => { + const submissionStatusLabel = formatBoardSubmissionLabelKo(p) + return { + id: p.examParticipantId, + name: p.name || "-", + phoneNumber: p.phoneMasked || "-", + examStatus: mapMasterParticipantExamStatus(examState, { + submitted: p.submitted, + submissionStatus: p.submissionStatus, + submissionStatusLabel, + state: p.state, + }), + hasSubmission: p.submitted === true, + submissionStatusLabel, + tokenUsage: p.tokenUsed ?? 0, + } + }) + setParticipants(mapped) + } catch (e) { + console.error("[TestSessionDetails] Failed to fetch board:", e) + setParticipants([]) + setParticipantsError(true) } finally { - setIsLoading(false); + setParticipantsLoading(false) } - }; + }, [examId, exam?.state]) useEffect(() => { - fetchParticipants(); - // 30초마다 자동 갱신 (실시간성 확보) - const timer = setInterval(fetchParticipants, 30000); - return () => clearInterval(timer); - }, [session.id]); + void loadExam() + }, [loadExam]) - // Pagination calculations - const totalPages = participants.length > 0 ? Math.ceil(participants.length / itemsPerPage) : 1 - const startIndex = (currentPage - 1) * itemsPerPage - const endIndex = startIndex + itemsPerPage - const currentParticipants = participants.slice(startIndex, endIndex) + useEffect(() => { + if (exam && examId != null) { + void loadParticipants() + const timer = setInterval(() => { + void loadParticipants() + }, 30000) + return () => clearInterval(timer) + } + return undefined + }, [exam, examId, loadParticipants]) + + if (examId == null) { + return ( +
+ +
+

세션을 찾을 수 없습니다.

+
+
+ ) + } - // Calculate summary stats - const submissions = participants.filter((p) => p.submissionStatus === "Submitted").length + const sessionMeta = exam ? mapExamToTestSession(exam) : null + const statusLabel = exam ? getMasterSessionStatusLabel(exam.state) : "-" + const displaySessionId = sessionMeta?.sessionId ?? "-" + const displayCreator = sessionMeta?.createdBy ?? "알 수 없음" + const displayCreatedAt = exam ? getExamDisplayDate(exam) : "-" + const participantTotal = exam?.participantCount ?? participants.length + const submissions = participants.filter((p) => p.hasSubmission).length const avgTokenUsage = participants.length > 0 ? Math.round(participants.reduce((sum, p) => sum + p.tokenUsage, 0) / participants.length) : 0 - const getStatusBadge = (status: string) => { - if (status === "Active") { + const totalPages = participants.length > 0 ? Math.ceil(participants.length / itemsPerPage) : 1 + const startIndex = (currentPage - 1) * itemsPerPage + const endIndex = startIndex + itemsPerPage + const currentParticipants = participants.slice(startIndex, endIndex) + + const getStatusBadge = (label: string) => { + if (label === "진행 중") { return 진행 중 } - return 완료 + if (label === "대기 중") { + return 대기 중 + } + if (label === "완료") { + return 완료 + } + return {label} } - const getConnectionBadge = (status: string) => { - if (status === "Connected") { - return 연결됨 + const getExamStatusBadge = (status: string) => { + if (status === "종료됨") { + return 종료됨 + } + if (status === "응시 완료") { + return 응시 완료 + } + if (status === "응시 중") { + return 응시 중 } - return 대기 중 + if (status === "대기 중") { + return 대기 중 + } + return {status} } - const getSubmissionBadge = (status: string) => { - if (status === "Submitted") { - return 제출됨 + const getSubmissionBadge = (label: string) => { + if (label === "시작 안 함") { + return 시작 안 함 } - if (status === "In Progress") { + if (label === "진행 중") { return 진행 중 } - return 시작 안 함 + if (label === "제출 실패") { + return 제출 실패 + } + if (label.startsWith("채점 완료")) { + return {label} + } + if (label === "제출·채점 중") { + return {label} + } + if (label === "제출됨") { + return 제출됨 + } + return {label} } - // Generate page numbers for pagination const getPageNumbers = () => { const pages: number[] = [] for (let i = 1; i <= totalPages; i++) { @@ -117,225 +210,219 @@ export default function TestSessionDetailsContent({ session, onBack }: TestSessi } return ( -
- {/* Page Header */} -
- {/* Back Button */} +
+ + +
- {/* Title and Subtitle */} -
-

- 테스트 세션 상세 정보 -

-

- 이 테스트 세션의 전체 정보와 실시간 진행 상황을 확인하세요. -

-
-
- - {/* Session Overview Card */} - - - - 세션 개요 - - - - {/* Row 1 */} -
-
-

세션 ID

-

{session.sessionId}

-
-
-

생성자

-

{session.createdBy}

-
-
-

생성일

-

{session.createdAt}

-
-
-

상태

-
{getStatusBadge(session.status)}
-
-
- - {/* Row 2 */} -
-
-

참가자

-

{session.participants}명

-
-
-

제출

-

- {submissions}/{session.participants} -

-
-
-

평균 토큰 사용량

-

{avgTokenUsage.toLocaleString()} 토큰

-
-
-
-
-
+ {examLoading ? ( +

세션 정보를 불러오는 중…

+ ) : examError || !exam ? ( +

세션을 찾을 수 없습니다.

+ ) : ( + <> + + + + 세션 개요 + + + +
+
+

세션 ID

+

{displaySessionId}

+
+
+

생성자

+

{displayCreator}

+
+
+

생성일

+

{displayCreatedAt}

+
+
+

상태

+
{getStatusBadge(statusLabel)}
+
+
+
+
+

참가자

+

{participantTotal}명

+
+
+

제출

+

+ {participantsError ? "–" : `${submissions}/${participantTotal}`} +

+
+
+

평균 토큰 사용량

+

+ {participantsError ? "–" : `${avgTokenUsage.toLocaleString()} 토큰`} +

+
+
+
+ + - {/* Participants Card */} - - -
- - 참가자 - -

이 테스트 세션에 등록된 모든 참가자입니다.

-
-
- - {/* Participants Table */} -
- - - - 이름 - 전화번호 - - 연결 상태 - - - 제출 상태 - - - 토큰 사용량 - - - 작업 - - - - - {currentParticipants.map((participant) => ( - - - {participant.name} - - - {participant.phoneNumber} - - - {getConnectionBadge(participant.connectionStatus)} - - - {getSubmissionBadge(participant.submissionStatus)} - - - {participant.tokenUsage.toLocaleString()} - - - - - - - - ))} - -
-
+ + +
+ + 참가자 + +

+ 이 테스트 세션에 등록된 모든 참가자입니다. +

+
+
+ + {participantsError ? ( +

+ 참가자 정보를 불러오지 못했습니다. +

+ ) : participantsLoading && participants.length === 0 ? ( +

+ 참가자 목록을 불러오는 중… +

+ ) : participants.length === 0 ? ( +

+ 등록된 참가자가 없습니다. +

+ ) : ( + <> +
+ + + + 이름 + 전화번호 + + 응시 상태 + + + 제출 상태 + + + 토큰 사용량 + + + 작업 + + + + + {currentParticipants.map((participant) => ( + + + {participant.name} + + + {participant.phoneNumber} + + + {getExamStatusBadge(participant.examStatus)} + + + {getSubmissionBadge(participant.submissionStatusLabel)} + + + {participant.tokenUsage.toLocaleString()} + + + + + + + + ))} + +
+
- {/* Pagination */} - {totalPages > 1 && ( -
-

- 총 {participants.length}명의 참가자 중 {startIndex + 1}–{Math.min(endIndex, participants.length)} 표시 -

-
- - {getPageNumbers().map((page) => ( - - ))} - -
-
- )} -
-
+ {totalPages > 1 && ( +
+

+ 총 {participants.length}명의 참가자 중 {startIndex + 1}– + {Math.min(endIndex, participants.length)} 표시 +

+
+ + {getPageNumbers().map((page) => ( + + ))} + +
+
+ )} + + )} +
+
+ + )} +
) } diff --git a/components/test-sessions-content.tsx b/components/test-sessions-content.tsx index 695a45f..fe75f0a 100644 --- a/components/test-sessions-content.tsx +++ b/components/test-sessions-content.tsx @@ -18,23 +18,44 @@ import { import { ScrollArea } from "@/components/ui/scroll-area" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet" -import { deleteExam, getBoard, getExams, type Exam, type ExamineeBoardEntry } from "@/lib/api/admin"; +import { deleteExam, getBoard, getExams, type ExamineeBoardEntry, formatBoardSubmissionLabelKo } from "@/lib/api/admin"; +import { AdminPageHeader } from "@/components/admin-page-header" +import { + mapBoardConnectionStatus, + mapExamsToTestSessions, + type TestSessionListItem, +} from "@/lib/master-test-sessions" -export interface TestSession { - id: number - sessionId: string // BE의 title을 sessionId로 매핑 (필요시) - createdBy: string - createdAt: string - status: string - participants: number +function submissionBadgeClassName(label: string): string { + if (label === "시작 안 함") return "bg-gray-100 text-gray-700 hover:bg-gray-100" + if (label === "진행 중") return "bg-yellow-100 text-yellow-700 hover:bg-yellow-100" + if (label === "제출 실패") return "bg-red-100 text-red-700 hover:bg-red-100" + if (label.startsWith("채점 완료")) return "bg-green-100 text-green-700 hover:bg-green-100" + if (label === "제출·채점 중") return "bg-amber-100 text-amber-800 hover:bg-amber-100" + if (label === "제출됨") return "bg-blue-100 text-blue-700 hover:bg-blue-100" + return "bg-gray-100 text-gray-700 hover:bg-gray-100" +} + +/** statusLabel 우선, 없으면 Active/Completed 매핑, 그 외 status 원문 */ +function formatSessionStatusDisplay(session: Pick): string { + const label = session.statusLabel?.trim() + if (label) return label + if (session.status === "Active") return "진행 중" + if (session.status === "Completed") return "완료" + return session.status } +export type TestSession = TestSessionListItem + interface Participant { id: number name: string phoneNumber: string connectionStatus: string - submissionStatus: string + /** 제출 레코드 존재 */ + hasSubmission: boolean + /** 표시용 한글 상태 */ + submissionStatusLabel: string tokenUsage: number } @@ -63,15 +84,7 @@ export function TestSessionsContent({ onViewDetails }: TestSessionsContentProps) setIsLoading(true) try { const exams = await getExams() - const mapped: TestSession[] = exams.map((exam: Exam) => ({ - id: exam.id, - sessionId: exam.title, - createdBy: "Admin", - createdAt: exam.startsAt ? exam.startsAt.split("T")[0] : "-", - status: ["RUNNING", "IN_PROGRESS"].includes(exam.state) ? "Active" : "Completed", - participants: exam.participantCount, - })) - setTestSessions(mapped) + setTestSessions(mapExamsToTestSessions(exams)) } catch (error) { console.error("Failed to fetch exams:", error) } finally { @@ -81,6 +94,7 @@ export function TestSessionsContent({ onViewDetails }: TestSessionsContentProps) // 2. 특정 시험의 참가자 현황 조회 (Board) const fetchParticipants = async (examId: number) => { + if (!Number.isFinite(examId) || examId <= 0) return setIsParticipantsLoading(true) try { const board = await getBoard(examId) @@ -88,12 +102,9 @@ export function TestSessionsContent({ onViewDetails }: TestSessionsContentProps) id: participant.examParticipantId, name: participant.name, phoneNumber: participant.phoneMasked, - connectionStatus: participant.state === "ENTRANCE" ? "Connected" : "Disconnected", - submissionStatus: participant.submitted - ? "Submitted" - : participant.state === "ENTRANCE" - ? "In Progress" - : "Not Started", + connectionStatus: mapBoardConnectionStatus(participant.state), + hasSubmission: participant.submitted, + submissionStatusLabel: formatBoardSubmissionLabelKo(participant), tokenUsage: participant.tokenUsed || 0, })) setParticipants(mapped) @@ -142,13 +153,14 @@ export function TestSessionsContent({ onViewDetails }: TestSessionsContentProps) } const handleViewDetailsAction = (session: TestSession) => { - setDetailsSession(session); - setIsDetailsOpen(true); - fetchParticipants(session.id); if (onViewDetails) { - onViewDetails(session); + onViewDetails(session) + return } - }; + setDetailsSession(session) + setIsDetailsOpen(true) + fetchParticipants(session.id) + } const totalParticipants = participants.length const totalParticipantPages = Math.ceil(totalParticipants / participantPageSize) @@ -156,7 +168,7 @@ export function TestSessionsContent({ onViewDetails }: TestSessionsContentProps) const participantEndIndex = Math.min(participantStartIndex + participantPageSize, totalParticipants) const paginatedParticipants = participants.slice(participantStartIndex, participantEndIndex) - const submittedCount = participants.filter((p) => p.submissionStatus === "Submitted").length + const submittedCount = participants.filter((p) => p.hasSubmission).length const avgTokenUsage = participants.length > 0 ? Math.round(participants.reduce((sum, p) => sum + p.tokenUsage, 0) / participants.length) @@ -179,30 +191,13 @@ export function TestSessionsContent({ onViewDetails }: TestSessionsContentProps) } return ( -
- {/* Page Header */} -
-

- 테스트 세션 -

-

- 플랫폼의 모든 테스트 세션을 관리하고 모니터링합니다. -

-
+
+ +
{/* Main Card */} @@ -352,7 +347,7 @@ export function TestSessionsContent({ onViewDetails }: TestSessionsContentProps) fontFamily: "Inter, system-ui, -apple-system, sans-serif", }} > - {session.status === "Active" ? "진행 중" : session.status === "Completed" ? "완료" : session.status} + {formatSessionStatusDisplay(session)} - {detailsSession?.status === "Active" ? "진행 중" : detailsSession?.status === "Completed" ? "완료" : detailsSession?.status} + {detailsSession ? formatSessionStatusDisplay(detailsSession) : "–"}
@@ -680,16 +675,10 @@ export function TestSessionsContent({ onViewDetails }: TestSessionsContentProps) - {participant.submissionStatus === "Submitted" ? "제출됨" : participant.submissionStatus === "In Progress" ? "진행 중" : "시작 안 함"} + {participant.submissionStatusLabel} @@ -758,6 +747,7 @@ export function TestSessionsContent({ onViewDetails }: TestSessionsContentProps)
+
) } diff --git a/components/user-test-screen.tsx b/components/user-test-screen.tsx index 736cf0d..210a0d4 100644 --- a/components/user-test-screen.tsx +++ b/components/user-test-screen.tsx @@ -5,7 +5,7 @@ import { Clock, Coins } from "lucide-react" import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button" import { ProblemSection } from "@/components/problem-section" -import { CodeEditorSection } from "@/components/code-editor-section" +import { CodeEditorSection, type CodeEditorSectionHandle } from "@/components/code-editor-section" import { AiAssistantSidebar } from "@/components/ai-assistant-sidebar" import { useRouter } from "next/navigation"; import { CheckCircle2 } from "lucide-react"; @@ -85,6 +85,10 @@ export default function UserTestScreen() { const [isSidebarOpen, setIsSidebarOpen] = useState(false) const [isSubmitModalOpen, setIsSubmitModalOpen] = useState(false) + /** 헤더 제출 확인 모달에서 POST 제출 중 */ + const [isModalSubmitting, setIsModalSubmitting] = useState(false) + + const codeEditorRef = useRef(null) // ── 초기 토큰 사용량 로드 (getChatHistory.totalTokens) ────────────────────── useEffect(() => { @@ -141,6 +145,7 @@ export default function UserTestScreen() { const handleCodeSubmitted = (submissionId: number) => { // 이전 SSE 연결 취소 sseCleanupRef.current?.(); + sseCleanupRef.current = null; setIsScoring(true); setCaseResultCount(0); @@ -178,6 +183,7 @@ export default function UserTestScreen() { useEffect(() => { return () => { sseCleanupRef.current?.(); + sseCleanupRef.current = null; }; }, []); @@ -220,6 +226,8 @@ export default function UserTestScreen() { }, [examId, isExamEnded, showEndModal]); const handleGoHome = () => { + sseCleanupRef.current?.(); + sseCleanupRef.current = null; router.push("/"); }; @@ -307,6 +315,7 @@ export default function UserTestScreen() { {/* Code Editor Section */}
@@ -444,7 +462,7 @@ export default function UserTestScreen() {
diff --git a/components/users-content.tsx b/components/users-content.tsx index 9e4c6b9..cc3218b 100644 --- a/components/users-content.tsx +++ b/components/users-content.tsx @@ -1,228 +1,346 @@ "use client" -import { useState } from "react" -import { ChevronLeft, ChevronRight } from "lucide-react" - -type ConnectionStatus = "연결됨" | "대기 중" -type SubmissionStatus = "시작 전" | "진행 중" | "제출 완료" +import { useCallback, useEffect, useMemo, useState } from "react" +import { ChevronDown, ChevronLeft, ChevronRight, Search } from "lucide-react" +import { + getBoard, + getExams, + type Exam, + type ExamineeBoardEntry, +} from "@/lib/api/admin" +import { + isAdminUsersSubmissionCountedComplete, + resolveAdminUsersConnectionStatus, + resolveAdminUsersSubmissionStatus, + type AdminUsersConnectionStatus, + type AdminUsersSubmissionStatus, +} from "@/lib/admin-users-participant-status" interface Participant { id: string name: string + examLabel: string phone: string - connectionStatus: ConnectionStatus - submissionStatus: SubmissionStatus + connectionStatus: AdminUsersConnectionStatus + submissionStatus: AdminUsersSubmissionStatus tokenUsage: number } -const initialParticipants: Participant[] = [ - { - id: "1", - name: "Rajesh Kumar", - phone: "+91 98765 43210", - connectionStatus: "연결됨", - submissionStatus: "제출 완료", - tokenUsage: 1250, - }, - { - id: "2", - name: "Rajesh Kumar", - phone: "+91 98765 43210", - connectionStatus: "연결됨", - submissionStatus: "진행 중", - tokenUsage: 890, - }, - { - id: "3", - name: "Rajesh Kumar", - phone: "+91 98765 43210", - connectionStatus: "대기 중", - submissionStatus: "시작 전", - tokenUsage: 0, - }, - { - id: "4", - name: "Rajesh Kumar", - phone: "+91 98765 43210", - connectionStatus: "연결됨", - submissionStatus: "진행 중", - tokenUsage: 1450, - }, - { - id: "5", - name: "Rajesh Kumar", - phone: "+91 98765 43210", - connectionStatus: "연결됨", - submissionStatus: "시작 전", - tokenUsage: 0, - }, - { - id: "6", - name: "Rajesh Kumar", - phone: "+91 98765 43210", - connectionStatus: "대기 중", - submissionStatus: "시작 전", - tokenUsage: 0, - }, - { - id: "7", - name: "Rajesh Kumar", - phone: "+91 98765 43210", - connectionStatus: "연결됨", - submissionStatus: "제출 완료", - tokenUsage: 1120, - }, - { - id: "8", - name: "Rajesh Kumar", - phone: "+91 98765 43210", - connectionStatus: "연결됨", - submissionStatus: "진행 중", - tokenUsage: 760, - }, - { - id: "9", - name: "Rajesh Kumar", - phone: "+91 98765 43210", - connectionStatus: "대기 중", - submissionStatus: "시작 전", - tokenUsage: 0, - }, - { - id: "10", - name: "Rajesh Kumar", - phone: "+91 98765 43210", - connectionStatus: "연결됨", - submissionStatus: "제출 완료", - tokenUsage: 1340, - }, - { - id: "11", - name: "Rajesh Kumar", - phone: "+91 98765 43210", - connectionStatus: "대기 중", - submissionStatus: "시작 전", - tokenUsage: 0, - }, - { - id: "12", - name: "Rajesh Kumar", - phone: "+91 98765 43210", - connectionStatus: "연결됨", - submissionStatus: "진행 중", - tokenUsage: 815, - }, - { - id: "13", - name: "Rajesh Kumar", - phone: "+91 98765 43210", - connectionStatus: "연결됨", - submissionStatus: "제출 완료", - tokenUsage: 980, - }, - { - id: "14", - name: "Rajesh Kumar", - phone: "+91 98765 43210", - connectionStatus: "연결됨", - submissionStatus: "제출 완료", - tokenUsage: 1025, - }, -] - -function ConnectionBadge({ status }: { status: ConnectionStatus }) { - const isConnected = status === "연결됨" +function resolveExamDisplayLabel(exam: Exam): string { + const code = exam.entryCode?.trim() + if (code) return code + return exam.title?.trim() || String(exam.id) +} + +function mapBoardEntry(entry: ExamineeBoardEntry, exam: Exam): Participant { + const connectionStatus = resolveAdminUsersConnectionStatus(entry, exam) + return { + id: `${exam.id}-${entry.examParticipantId}`, + name: entry.name || "–", + examLabel: resolveExamDisplayLabel(exam), + phone: entry.phoneMasked || "–", + connectionStatus, + submissionStatus: resolveAdminUsersSubmissionStatus(entry, exam, connectionStatus), + tokenUsage: entry.tokenUsed ?? 0, + } +} + +function ConnectionBadge({ status }: { status: AdminUsersConnectionStatus }) { + const styles: Record = { + "응시 완료": "border-[#16A34A] bg-[#DCFCE7] text-[#16A34A]", + "응시 중": "border-[#3B82F6] bg-white text-[#3B82F6]", + "대기 중": "border-[#6B7280] bg-white text-[#6B7280]", + "종료됨": "border-[#9CA3AF] bg-[#F3F4F6] text-[#6B7280]", + } return ( - + {status} ) } -function SubmissionBadge({ status }: { status: SubmissionStatus }) { - const styles = { +function SubmissionBadge({ status }: { status: AdminUsersSubmissionStatus }) { + const styles: Record = { "시작 전": "bg-[#F3F4F6] text-[#6B7280]", "진행 중": "bg-[#E0EDFF] text-[#3B82F6]", + "채점 중": "bg-[#FEF3C7] text-[#D97706]", "제출 완료": "bg-[#DCFCE7] text-[#16A34A]", + "채점 완료": "bg-[#DCFCE7] text-[#16A34A]", + "미제출": "bg-[#F3F4F6] text-[#6B7280]", + "제출 실패": "bg-[#FEE2E2] text-[#DC2626]", } return {status} } +/** 참가자 목록 그리드: 좌측(이름·시험) / 중앙(전화·상태) / 우측(토큰) */ +const PARTICIPANT_LIST_GRID_COLS = + "grid-cols-[1.2fr_1fr_1fr_minmax(5.5rem,1fr)_minmax(5.5rem,1fr)_minmax(4.5rem,0.95fr)]" + export function UsersContent() { - const [participants] = useState(initialParticipants) + const [exams, setExams] = useState([]) + const [participants, setParticipants] = useState([]) + const [isLoadingExams, setIsLoadingExams] = useState(true) + const [isLoadingBoard, setIsLoadingBoard] = useState(false) + const [error, setError] = useState(null) + const [selectedExamId, setSelectedExamId] = useState("all") + const [searchQuery, setSearchQuery] = useState("") const [currentPage, setCurrentPage] = useState(1) const pageSize = 12 - const totalPages = Math.ceil(participants.length / pageSize) + useEffect(() => { + let cancelled = false + async function loadExams() { + setIsLoadingExams(true) + try { + const data = await getExams() + if (!cancelled) setExams(data) + } catch (e) { + console.error("[Users] Failed to load exams", e) + if (!cancelled) { + setExams([]) + setError("시험 세션 목록을 불러오는 데 실패했습니다.") + } + } finally { + if (!cancelled) setIsLoadingExams(false) + } + } + loadExams() + return () => { + cancelled = true + } + }, []) + + const loadParticipants = useCallback(async () => { + if (isLoadingExams) return + + setIsLoadingBoard(true) + setError(null) + try { + if (exams.length === 0) { + setParticipants([]) + setCurrentPage(1) + return + } + + let mapped: Participant[] = [] + + if (selectedExamId === "all") { + const boards = await Promise.all( + exams.map(async (exam) => { + try { + const entries = await getBoard(exam.id) + return entries.map((entry) => mapBoardEntry(entry, exam)) + } catch (e) { + console.error(`[Users] getBoard failed for examId=${exam.id}`, e) + return [] as Participant[] + } + }) + ) + mapped = boards.flat() + } else { + const examId = Number.parseInt(selectedExamId, 10) + const exam = exams.find((e) => e.id === examId) + if (!exam || Number.isNaN(examId)) { + setParticipants([]) + setCurrentPage(1) + return + } + const board = await getBoard(examId) + mapped = board.map((entry) => mapBoardEntry(entry, exam)) + } + + setParticipants(mapped) + setCurrentPage(1) + } catch (e) { + console.error("[Users] Failed to load participants", e) + setParticipants([]) + setError("참가자 목록을 불러오는 데 실패했습니다.") + } finally { + setIsLoadingBoard(false) + } + }, [exams, isLoadingExams, selectedExamId]) + + useEffect(() => { + void loadParticipants() + }, [loadParticipants]) + + const filteredParticipants = useMemo(() => { + const q = searchQuery.trim().toLowerCase() + if (!q) return participants + return participants.filter((p) => { + const name = p.name.toLowerCase() + const exam = p.examLabel.toLowerCase() + return name.includes(q) || exam.includes(q) + }) + }, [participants, searchQuery]) + + const totalPages = Math.max(1, Math.ceil(filteredParticipants.length / pageSize)) const startIndex = (currentPage - 1) * pageSize const endIndex = currentPage * pageSize - const visibleParticipants = participants.slice(startIndex, endIndex) + const visibleParticipants = filteredParticipants.slice(startIndex, endIndex) - const displayStart = participants.length === 0 ? 0 : startIndex + 1 - const displayEnd = Math.min(endIndex, participants.length) + const displayStart = filteredParticipants.length === 0 ? 0 : startIndex + 1 + const displayEnd = Math.min(endIndex, filteredParticipants.length) + + const completedCount = useMemo( + () => + filteredParticipants.filter((p) => + isAdminUsersSubmissionCountedComplete(p.submissionStatus) + ).length, + [filteredParticipants] + ) + + const isLoading = isLoadingExams || isLoadingBoard + + useEffect(() => { + setCurrentPage(1) + }, [searchQuery, selectedExamId]) return (
- {/* Top Header Bar */}

참가자 목록

-

실시간 참가자 모니터링

+

+ 모든 시험 세션의 참가자를 조회하고 제출 상태를 확인합니다. +

- {/* Main Content Panel */}
- {/* Table Container */} +
+
+ + +
+ +
+ + setSearchQuery(e.target.value)} + className="w-full rounded-lg border border-[#E5E5E5] bg-white py-2 pl-10 pr-4 text-sm text-[#1A1A1A] placeholder-[#9CA3AF] outline-none transition-colors focus:border-[#3B82F6] focus:ring-1 focus:ring-[#3B82F6]" + /> +
+
+ + {error && ( +
+

{error}

+
+ )} +
- {/* Table Header */} -
- 이름 - 전화번호 - 연결 상태 - 제출 상태 - 토큰 사용량 +
+ + 이름 + + + 시험 + +
+ + 전화번호 + +
+
+ + 응시 상태 + +
+
+ + 제출 상태 + +
+
+ + 토큰 사용량 + +
- {/* Table Body */}
- {visibleParticipants.map((participant, index) => ( -
- {participant.name} - {participant.phone} -
- -
-
- -
- - {participant.tokenUsage.toLocaleString()} - + {isLoading ? ( +
+

불러오는 중...

+
+ ) : visibleParticipants.length === 0 ? ( +
+

표시할 참가자가 없습니다.

+ {!error && filteredParticipants.length === 0 && participants.length > 0 && ( +

검색 조건에 맞는 참가자가 없습니다.

+ )} + {!error && participants.length === 0 && ( +

선택한 세션에 참가자가 없습니다.

+ )}
- ))} + ) : ( + visibleParticipants.map((participant, index) => ( +
+ + {participant.name} + + + {participant.examLabel} + +
+ + {participant.phone} + +
+
+ +
+
+ +
+
+ + {participant.tokenUsage.toLocaleString()} + +
+
+ )) + )}
- {/* Pagination */} - {participants.length > 0 && ( + {!isLoading && filteredParticipants.length > 0 && (
- 총 {participants.length}명 중 {displayStart}–{displayEnd}명 보여주는 중 + 총 {filteredParticipants.length}명 중 {displayStart}–{displayEnd}명 표시 + {completedCount > 0 && ` · 제출 완료 ${completedCount}명`}