From 6230072958355e580e7c155e63870c3c5a80afae Mon Sep 17 00:00:00 2001 From: ChanWook Lee Date: Mon, 4 May 2026 19:10:43 +0900 Subject: [PATCH 01/16] fix: remove duplicate entry-code API call --- components/entry-codes-content.tsx | 34 +++--------------------------- 1 file changed, 3 insertions(+), 31 deletions(-) diff --git a/components/entry-codes-content.tsx b/components/entry-codes-content.tsx index 7fce029..f6ec8a6 100644 --- a/components/entry-codes-content.tsx +++ b/components/entry-codes-content.tsx @@ -13,7 +13,7 @@ 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 { useToast } from "@/hooks/use-toast" @@ -213,40 +213,12 @@ export function EntryCodesContent() { const createdExam = await createExam(payload) console.log("Exam created:", createdExam) - // 시험 생성 후 자동으로 입장 코드 생성 - let entryCodeValue: string | undefined = undefined - 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) - } catch (entryCodeError) { - console.error("Failed to create entry code", entryCodeError) - // 입장 코드 생성 실패해도 시험 생성은 성공으로 처리 - toast({ - title: "입장 코드 생성 실패", - description: "시험은 생성되었지만 입장 코드 생성에 실패했습니다. 나중에 수동으로 생성해주세요.", - variant: "destructive", - }) - } - - // 입장 코드가 포함된 시험 객체 생성 - const examWithEntryCode: Exam = { - ...createdExam, - entryCode: entryCodeValue, - } - // 시험 목록에 새로 생성된 시험 추가 setExams((prev) => { if (prev === null) { - return [examWithEntryCode] + return [createdExam] } - return [examWithEntryCode, ...prev] + return [createdExam, ...prev] }) // 모달 닫기 From 3a465eed8f711ad9803cd40c2c86ce2582cac289 Mon Sep 17 00:00:00 2001 From: ChanWook Lee Date: Sat, 9 May 2026 00:51:33 +0900 Subject: [PATCH 02/16] fix: gitignore fixed --- .gitignore | 3 ++- next-env.d.ts | 6 ------ 2 files changed, 2 insertions(+), 7 deletions(-) delete mode 100644 next-env.d.ts diff --git a/.gitignore b/.gitignore index e4e35fc..fa18c9c 100644 --- a/.gitignore +++ b/.gitignore @@ -48,4 +48,5 @@ Thumbs.db # CLAUDE .claude/ -.env.local \ No newline at end of file +.env.local +next-env.d.ts \ No newline at end of file diff --git a/next-env.d.ts b/next-env.d.ts deleted file mode 100644 index 9edff1c..0000000 --- a/next-env.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/// -/// -import "./.next/types/routes.d.ts"; - -// NOTE: This file should not be edited -// see https://nextjs.org/docs/app/api-reference/config/typescript for more information. From 4534659a1b329d69ed2826e5274f284daa3e4447 Mon Sep 17 00:00:00 2001 From: ChanWook Lee Date: Sat, 9 May 2026 05:00:48 +0900 Subject: [PATCH 03/16] fix: restore exam session after refresh --- app/test/page.tsx | 59 ++++++++++++++++++++++++++++++ components/entry-codes-content.tsx | 46 ++++++++++++++++++++--- hooks/use-chat-socket.tsx | 22 +---------- lib/api/exams.ts | 57 +++++++++++++++++++++++++++++ 4 files changed, 157 insertions(+), 27 deletions(-) diff --git a/app/test/page.tsx b/app/test/page.tsx index da684f8..e37a1e6 100644 --- a/app/test/page.tsx +++ b/app/test/page.tsx @@ -1,7 +1,66 @@ "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 } 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; + + const restoreSession = async () => { + try { + const activeSession = await getActiveSession(); + if (cancelled) return; + + if (!activeSession) { + setRestoreError("활성 시험 세션이 없습니다. 다시 입장해주세요."); + setTimeout(() => router.replace("/"), 1200); + return; + } + + useExamSessionStore.setState({ + examId: activeSession.examId, + participantId: activeSession.examParticipantId, + tokenLimit: activeSession.tokenLimit, + }); + } catch (error) { + if (cancelled) return; + console.error("[TestPage] active session restore failed:", error); + setRestoreError("세션 복구에 실패했습니다. 다시 입장해주세요."); + setTimeout(() => router.replace("/"), 1200); + } finally { + if (!cancelled) { + setIsRestoring(false); + } + } + }; + + restoreSession(); + return () => { + cancelled = true; + }; + }, [router]); + + if (isRestoring || !examId || !participantId) { + return ( +
+
+

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

+
+
+ ); + } + return } diff --git a/components/entry-codes-content.tsx b/components/entry-codes-content.tsx index f6ec8a6..633e6ab 100644 --- a/components/entry-codes-content.tsx +++ b/components/entry-codes-content.tsx @@ -49,6 +49,22 @@ 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 +} + export function EntryCodesContent() { // 시험 생성 모달 상태 @@ -120,14 +136,14 @@ 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), } } }) @@ -211,14 +227,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, + } + + // 생성 직후 entry-codes API에서 실제 활성 코드를 한번 더 조회해 반영 + try { + const createdExamEntryCodes = await getEntryCodes(createdExam.id) + const activeEntryCode = createdExamEntryCodes.find((ec) => ec.isActive) || createdExamEntryCodes[0] + createdExamWithEntryCode = { + ...createdExam, + entryCode: activeEntryCode?.code || responseEntryCode, + } + } catch (entryCodeError) { + console.warn(`Failed to fetch entry codes right after exam creation (examId=${createdExam.id}):`, entryCodeError) + } + + console.log("Exam created:", createdExamWithEntryCode) // 시험 목록에 새로 생성된 시험 추가 setExams((prev) => { if (prev === null) { - return [createdExam] + return [createdExamWithEntryCode] } - return [createdExam, ...prev] + return [createdExamWithEntryCode, ...prev] }) // 모달 닫기 @@ -232,7 +266,7 @@ export function EntryCodesContent() { // 성공 토스트 표시 toast({ title: "시험 생성 성공", - description: `"${createdExam.title}" 시험이 성공적으로 생성되었습니다.`, + description: `"${createdExamWithEntryCode.title}" 시험이 성공적으로 생성되었습니다.`, }) } catch (error) { console.error("Failed to create exam", error) diff --git a/hooks/use-chat-socket.tsx b/hooks/use-chat-socket.tsx index 5a1e713..19c9081 100644 --- a/hooks/use-chat-socket.tsx +++ b/hooks/use-chat-socket.tsx @@ -21,16 +21,6 @@ interface SendMessageResponse { const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8080'; -/** JWT 만료 여부 확인 (클라이언트 사이드) */ -function isTokenExpired(token: string): boolean { - try { - const payload = JSON.parse(atob(token.split('.')[1])); - return payload.exp * 1000 < Date.now(); - } catch { - return true; - } -} - export function useChatSocket( examId: number, participantId: number, @@ -39,7 +29,7 @@ export function useChatSocket( ) { const [isConnected, setIsConnected] = useState(false); const stompClientRef = useRef(null); - // 셀렉터로 구독: accessToken 변경 시 effect 재실행 → 로그인 후 소켓 연결 보장 + // accessToken은 있으면 Authorization 헤더로 전달하고, 없으면 쿠키 기반 인증으로 연결 const accessToken = useExamSessionStore((state) => state.accessToken); // 콜백을 ref로 관리: 최신 함수 참조를 유지하면서 STOMP 재연결을 방지 @@ -49,18 +39,8 @@ export function useChatSocket( useEffect(() => { onErrorRef.current = onError; }, [onError]); useEffect(() => { - // STOMP CONNECT 시 JWT를 헤더로 전달해 서버 Principal(userId) 설정을 가능하게 함 - // BE의 StompPrincipalInterceptor가 이 토큰을 파싱해 participantId를 Principal로 등록 - // → convertAndSendToUser(participantId, "/queue/chat", response) 라우팅이 정상 동작 const token = accessToken; - // 만료된 토큰으로 연결 시 Principal이 설정되지 않아 convertAndSendToUser가 무음 실패함 - if (!token || isTokenExpired(token)) { - console.warn('[STOMP Chat] JWT 토큰이 없거나 만료됨 - 재로그인 필요'); - onErrorRef.current?.('세션이 만료되었습니다. 다시 로그인해주세요.'); - return; - } - const socket = new SockJS(`${API_BASE_URL}/ws`); const client = new Client({ webSocketFactory: () => socket, diff --git a/lib/api/exams.ts b/lib/api/exams.ts index 47c813e..86253d8 100644 --- a/lib/api/exams.ts +++ b/lib/api/exams.ts @@ -169,6 +169,63 @@ export interface ParticipantSessionResponse { assignedProblemId: number | null; } +// 활성 시험 세션 복구 응답 타입 +export interface ActiveSessionResponse { + examId: number; + examParticipantId: number; + assignedProblemId: number | null; + specId: number | null; + examState: ExamState; + startsAt: string; + endsAt: string; + serverTime: string; + tokenLimit: number; + tokenUsed: number; +} + +/** + * 현재 로그인한 참가자의 활성 시험 세션 조회 + * GET /api/exams/active-session + */ +export async function getActiveSession(): Promise { + const apiBaseUrl = getApiBaseUrl(); + const url = `${apiBaseUrl}/api/exams/active-session`; + const isDev = process.env.NODE_ENV === 'development'; + + if (isDev) { + console.log('[Get Active Session] API 호출:', url); + } + + const response = await fetch(url, { + method: 'GET', + headers: getUserAuthHeaders(), + credentials: 'include', + }); + + let data: BaseResponse; + try { + data = await response.json(); + } catch { + throw new Error('활성 세션 응답을 파싱할 수 없습니다.'); + } + + if (!response.ok) { + // 활성 세션이 없는 경우(null)로 처리 + if (response.status === 404 || data.code === 'EXAM404_5') { + return null; + } + const err: any = new Error(data.message || '활성 세션 조회에 실패했습니다.'); + err.status = response.status; + throw err; + } + + if (data.code !== 'COMMON200' || !data.result) { + return null; + } + + return data.result; +} + /** * 현재 참가자의 세션 정보 조회 (대기→시험 전환 시 최신 tokenLimit 갱신용) * GET /api/exams/{examId}/participants/me From 08fe26a3c95e6d8898cfed64b0ab56acd349ca18 Mon Sep 17 00:00:00 2001 From: ChanWook Lee Date: Sun, 10 May 2026 06:21:17 +0900 Subject: [PATCH 04/16] fix: improve assignment loading display --- components/problem-section.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/components/problem-section.tsx b/components/problem-section.tsx index 5db2496..f6cee1f 100644 --- a/components/problem-section.tsx +++ b/components/problem-section.tsx @@ -14,7 +14,11 @@ export function ProblemSection({ examId }: ProblemSectionProps) { useEffect(() => { getAssignment(examId) .then(setAssignment) - .catch(() => {/* 로드 실패 시 null 유지 */}) + .catch((err) => { + if (process.env.NODE_ENV === "development") { + console.warn("[ProblemSection] getAssignment failed:", err) + } + }) .finally(() => setLoading(false)) }, [examId]) From 00a64435969249a14133a070db4fdaaa33f044dc Mon Sep 17 00:00:00 2001 From: ChanWook Lee Date: Mon, 11 May 2026 16:55:35 +0900 Subject: [PATCH 05/16] fix: improve active-session and assignment recovery handling --- app/test/page.tsx | 73 +++++++++++++++++++++++----------- components/problem-section.tsx | 70 ++++++++++++++++++++++++++++---- lib/api/exams.ts | 41 ++++++++++++++++++- 3 files changed, 152 insertions(+), 32 deletions(-) diff --git a/app/test/page.tsx b/app/test/page.tsx index e37a1e6..e37e962 100644 --- a/app/test/page.tsx +++ b/app/test/page.tsx @@ -4,7 +4,7 @@ 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 } from "@/lib/api/exams"; +import { getActiveSession, getActiveSessionByExam } from "@/lib/api/exams"; export default function TestPage() { const router = useRouter(); @@ -17,34 +17,61 @@ export default function TestPage() { let cancelled = false; const restoreSession = async () => { - try { - const activeSession = await getActiveSession(); - if (cancelled) return; + const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); - if (!activeSession) { - setRestoreError("활성 시험 세션이 없습니다. 다시 입장해주세요."); - setTimeout(() => router.replace("/"), 1200); - return; - } + // 시험 시작 직후(관리자 start 직후)에는 서버가 아직 "RUNNING/active-session"으로 + // 판단되기 전에 FE가 먼저 조회할 수 있어 404(NO_ACTIVE_SESSION)가 일시적으로 발생할 수 있다. + // 이 경우 즉시 entry로 튕기지 말고 짧게 재시도 후 실패 시에만 리다이렉트한다. + const maxAttempts = 6; // 총 5~6초 내 재시도 + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + const currentExamId = useExamSessionStore.getState().examId; + const activeSession = currentExamId + ? await getActiveSessionByExam(currentExamId) + : await getActiveSession(); + if (cancelled) return; + + if (activeSession) { + useExamSessionStore.setState({ + examId: activeSession.examId, + participantId: activeSession.examParticipantId, + tokenLimit: activeSession.tokenLimit, + }); + return; + } + + if (attempt === maxAttempts) { + setRestoreError("활성 시험 세션이 없습니다. 다시 입장해주세요."); + setTimeout(() => router.replace("/"), 1200); + return; + } + + await sleep(300 + attempt * 250); + } catch (error: any) { + if (cancelled) return; + // 인증 실패(쿠키 누락/만료)는 재시도해도 의미 없으므로 즉시 리다이렉트 + if (error?.status === 401) { + setRestoreError("인증이 필요합니다. 다시 입장해주세요."); + setTimeout(() => router.replace("/"), 1200); + return; + } + + console.error("[TestPage] active session restore failed:", error); + + if (attempt === maxAttempts) { + setRestoreError("세션 복구에 실패했습니다. 다시 입장해주세요."); + setTimeout(() => router.replace("/"), 1200); + return; + } - useExamSessionStore.setState({ - examId: activeSession.examId, - participantId: activeSession.examParticipantId, - tokenLimit: activeSession.tokenLimit, - }); - } catch (error) { - if (cancelled) return; - console.error("[TestPage] active session restore failed:", error); - setRestoreError("세션 복구에 실패했습니다. 다시 입장해주세요."); - setTimeout(() => router.replace("/"), 1200); - } finally { - if (!cancelled) { - setIsRestoring(false); + await sleep(300 + attempt * 250); } } }; - restoreSession(); + void restoreSession().finally(() => { + if (!cancelled) setIsRestoring(false); + }); return () => { cancelled = true; }; diff --git a/components/problem-section.tsx b/components/problem-section.tsx index f6cee1f..6d77b6b 100644 --- a/components/problem-section.tsx +++ b/components/problem-section.tsx @@ -10,16 +10,66 @@ 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((err) => { - if (process.env.NODE_ENV === "development") { - console.warn("[ProblemSection] getAssignment failed:", err) + 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) + continue + } + + if (process.env.NODE_ENV === "development") { + console.warn("[ProblemSection] getAssignment failed:", err) + } + setAssignment(null) + setErrorMessage("문제를 불러올 수 없습니다.") + setLoading(false) + return } - }) - .finally(() => setLoading(false)) + } + } + + void load() + return () => { + cancelled = true + } }, [examId]) const problem = assignment?.problem @@ -27,7 +77,11 @@ export function ProblemSection({ examId }: ProblemSectionProps) { return (

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

{problem && ( diff --git a/lib/api/exams.ts b/lib/api/exams.ts index 86253d8..1b98034 100644 --- a/lib/api/exams.ts +++ b/lib/api/exams.ts @@ -226,6 +226,43 @@ export async function getActiveSession(): Promise return data.result; } +/** + * 특정 시험(examId) 기준 활성 시험 세션 조회 + * GET /api/exams/{examId}/active-session + */ +export async function getActiveSessionByExam(examId: number): Promise { + const apiBaseUrl = getApiBaseUrl(); + const url = `${apiBaseUrl}/api/exams/${examId}/active-session`; + + const response = await fetch(url, { + method: 'GET', + headers: getUserAuthHeaders(), + credentials: 'include', + }); + + let data: BaseResponse; + try { + data = await response.json(); + } catch { + throw new Error('활성 세션 응답을 파싱할 수 없습니다.'); + } + + if (!response.ok) { + if (response.status === 404 || data.code === 'EXAM404_5') { + return null; + } + const err: any = new Error(data.message || '활성 세션 조회에 실패했습니다.'); + err.status = response.status; + throw err; + } + + if (data.code !== 'COMMON200' || !data.result) { + return null; + } + + return data.result; +} + /** * 현재 참가자의 세션 정보 조회 (대기→시험 전환 시 최신 tokenLimit 갱신용) * GET /api/exams/{examId}/participants/me @@ -265,8 +302,10 @@ export async function getAssignment(examId: number): Promise const data: BaseResponse = await response.json(); if (!response.ok || data.code !== 'COMMON200' || !data.result) { - const err: any = new Error(data.message || '문제 조회에 실패했습니다.'); + const err: any = new Error(data?.message || '문제 조회에 실패했습니다.'); err.status = response.status; + err.code = data?.code; + err.apiMessage = data?.message; throw err; } return data.result; From f0c6cd5e02b4461164552e0508cf577c3a797976 Mon Sep 17 00:00:00 2001 From: ChanWook Lee Date: Thu, 14 May 2026 12:19:35 +0900 Subject: [PATCH 06/16] =?UTF-8?q?=EA=B4=80=EB=A6=AC=EC=9E=90=20=ED=8F=89?= =?UTF-8?q?=EA=B0=80=20=EC=83=81=EC=84=B8=20=ED=99=94=EB=A9=B4=20API=20?= =?UTF-8?q?=EC=97=B0=EB=8F=99=20=EB=B0=8F=20Mock=20=EC=A0=9C=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/admin/results/[entryCode]/page.tsx | 18 +- components/analytics-content.tsx | 6 +- components/code-editor-section.tsx | 40 +- components/dashboard-content.tsx | 6 +- components/participant-evaluation-content.tsx | 627 +++++++++--------- components/participant-list-content.tsx | 29 +- components/results-content.tsx | 3 +- components/test-session-details-content.tsx | 42 +- components/test-sessions-content.tsx | 36 +- components/user-test-screen.tsx | 24 +- lib/api/admin.ts | 35 + 11 files changed, 475 insertions(+), 391 deletions(-) diff --git a/app/admin/results/[entryCode]/page.tsx b/app/admin/results/[entryCode]/page.tsx index d3509ac..691018c 100644 --- a/app/admin/results/[entryCode]/page.tsx +++ b/app/admin/results/[entryCode]/page.tsx @@ -1,24 +1,18 @@ // 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 ?? ""; - - // 혹시 인코딩 되어 있을 수 있으니 decode - const decodedEntryCode = decodeURIComponent(rawEntryCode); + const { entryCode: rawEntryCode } = await params; + const safe = rawEntryCode ?? ""; + const decodedEntryCode = decodeURIComponent(safe); return ; } diff --git a/components/analytics-content.tsx b/components/analytics-content.tsx index 3116c36..516afaa 100644 --- a/components/analytics-content.tsx +++ b/components/analytics-content.tsx @@ -34,11 +34,15 @@ function mapBoardToParticipant(entry: ExamineeBoardEntry, examTitle: string): Pa const tokenRatio = entry.tokenLimit > 0 ? Math.min(100, Math.round((entry.tokenUsed / entry.tokenLimit) * 100)) : 0 + const total = + entry.totalScore != null && entry.totalScore !== undefined ? Number(entry.totalScore) : null + const avgScore = total != null && !Number.isNaN(total) ? total : 0 + return { id: entry.examParticipantId.toString(), name: entry.name, entryCode: examTitle, - avgScore: 0, // 채점 API 미연동 — 채점 완료 후 집계 예정 + avgScore, status: submitted ? "완료" : "진행 중", trend: "보통", sparklineData: [0, tokenRatio], // 토큰 사용 추이 diff --git a/components/code-editor-section.tsx b/components/code-editor-section.tsx index 29fd62c..050e69d 100644 --- a/components/code-editor-section.tsx +++ b/components/code-editor-section.tsx @@ -2,7 +2,7 @@ import type React from "react" -import { useState, useRef } from "react" +import { useState, useRef, useCallback, useImperativeHandle, forwardRef } from "react" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" import { submitCode, SubmissionStatus } from "@/lib/api/submissions" @@ -77,11 +77,20 @@ interface CodeEditorSectionProps { onSubmitted?: (submissionId: number) => void; } -export function CodeEditorSection({ +/** 부모(헤더 제출 확인 모달 등)에서 POST 제출을 트리거할 때 사용 */ +export type CodeEditorSectionHandle = { + /** POST /api/exams/{examId}/submissions — 성공 시 true */ + submit: () => Promise; +}; + +export const CodeEditorSection = forwardRef(function CodeEditorSection( + { isReadOnly = false, examId, onSubmitted, -}: CodeEditorSectionProps) { +}: CodeEditorSectionProps, + ref +) { const [language, setLanguage] = useState("python") const [languageCodes, setLanguageCodes] = useState>({ python: defaultCodeTemplates.python, @@ -128,15 +137,15 @@ export function CodeEditorSection({ } }; - /** 코드 제출 핸들러 */ - const handleSubmit = async () => { + /** 코드 제출 — 에디터 버튼·부모 ref 동시 사용 */ + const handleSubmit = useCallback(async (): Promise => { if (!examId) { setSubmitError("시험 정보가 없습니다.") - return + return false } if (!code.trim()) { setSubmitError("코드를 작성해주세요.") - return + return false } setIsSubmitting(true) @@ -147,13 +156,23 @@ export function CodeEditorSection({ const result = await submitCode(examId, { lang: language, code }) setSubmitStatus(result.status) onSubmitted?.(result.submissionId) + return true } catch (err: any) { setSubmitError(err.message || "코드 제출에 실패했습니다.") setSubmitStatus(null) + return false } finally { setIsSubmitting(false) } - } + }, [examId, language, code, onSubmitted]) + + useImperativeHandle( + ref, + () => ({ + submit: () => handleSubmit(), + }), + [handleSubmit] + ) const MIN_LINES = 15; const actualLineCount = code.split("\n").length || 1; @@ -181,7 +200,8 @@ export function CodeEditorSection({ {/* 제출 버튼 — isReadOnly일 때 숨김 */} {!isReadOnly && examId && (
) -} +}) diff --git a/components/dashboard-content.tsx b/components/dashboard-content.tsx index 8700277..e986c7a 100644 --- a/components/dashboard-content.tsx +++ b/components/dashboard-content.tsx @@ -107,13 +107,13 @@ export function DashboardContent() {
- 평가 완료 수 + 코드 제출 완료 수

{displayValue(completedCount)}

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

diff --git a/components/participant-evaluation-content.tsx b/components/participant-evaluation-content.tsx index c1dd0dc..30b7611 100644 --- a/components/participant-evaluation-content.tsx +++ b/components/participant-evaluation-content.tsx @@ -1,16 +1,23 @@ "use client" -import { useState, useEffect } from "react" -import Link from "next/link" +import { useState, useEffect, useMemo } 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, + formatBoardSubmissionLabelKo, + type Exam, + type ExamineeBoardEntry, +} from "@/lib/api/admin" +import { getSubmission, type SubmissionDetailResponse } from "@/lib/api/submissions" interface ParticipantEvaluationContentProps { entryCode: string - participantName?: string // 선택적 — URL query 또는 board에서 로드 + participantName?: string + /** URL 세그먼트 — 목록·보드와 동일하게 `exam_participants.id` (examParticipantId) */ participantId: string - onBack?: () => void; + onBack?: () => void } interface ToastItem { @@ -19,147 +26,33 @@ 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": "시작 안 함", + 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 {statusText[status]} + + return undefined +} + +function trendFromBoard(entry: ExamineeBoardEntry | null): "High" | "Average" | "Low" { + if (!entry) return "Low" + if (entry.submitted) return "High" + if (entry.state === "ENTRANCE") return "Average" + return "Low" } function TrendBadge({ trend }: { trend: "High" | "Average" | "Low" }) { @@ -180,87 +73,122 @@ function LanguageBadge({ language }: { language: string }) { return {language} } -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 formatScore(n: number | null | undefined): string { + if (n === null || n === undefined || Number.isNaN(Number(n))) return "–" + return `${Number(n).toFixed(1)}` } -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 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) -} - -export function ParticipantEvaluationContent({ entryCode, participantName: participantNameProp, participantId, onBack }: ParticipantEvaluationContentProps) { +export function ParticipantEvaluationContent({ + entryCode, + participantName: participantNameProp, + participantId, + onBack, +}: 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(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) + setExamId(null) try { const exams = await getExams() - const matched = exams.find((e) => e.entryCode === entryCode) + const matched = findExamByResultsSegment(exams, entryCode) if (!matched) { - setIsLoadingBoard(false) + 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 entry = board.find((p) => String(p.examParticipantId) === String(participantId)) + if (!cancelled) { + setExamId(matched.id) + 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() + loadBoard() + return () => { + cancelled = true + } }, [entryCode, participantId]) - // 이름 우선순위: prop > board > fallback - const displayName = participantNameProp || boardParticipantName || participantData.name + const submissionId = boardEntry?.submissionId ?? null + + useEffect(() => { + if (!submissionId) { + setSubmissionDetail(null) + setSubmissionDetailError(null) + return + } + let cancelled = false + async function loadSubmission() { + setIsLoadingSubmission(true) + setSubmissionDetailError(null) + try { + const detail = await getSubmission(submissionId) + if (!cancelled) setSubmissionDetail(detail) + } catch (e: unknown) { + console.error("getSubmission 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 trend = useMemo(() => trendFromBoard(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 showToast = (title: string, description: string) => { const id = crypto.randomUUID() @@ -275,37 +203,52 @@ export function ParticipantEvaluationContent({ entryCode, participantName: parti } const handleExport = () => { - downloadCSV() - showToast("Participant results exported successfully.", "File: participants.csv") + const header = "Field,Value" + const rows = [ + `Name,${displayName}`, + `EntryCodeSegment,${entryCode}`, + `ExamParticipantId,${participantId}`, + `ExamId,${examId ?? ""}`, + `SubmissionId,${submissionId ?? ""}`, + `BoardStatus,${submissionStatusLabel ?? ""}`, + `PromptScore,${scoreFromDetail?.prompt ?? ""}`, + `PerfScore,${scoreFromDetail?.perf ?? ""}`, + `CorrectnessScore,${scoreFromDetail?.correctness ?? ""}`, + `TotalScore,${scoreFromDetail?.total ?? boardEntry?.totalScore ?? ""}`, + ] + const csvContent = [header, ...rows].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 = "participant-evaluation.csv" + document.body.appendChild(link) + link.click() + document.body.removeChild(link) + URL.revokeObjectURL(url) + showToast("보내기 완료", "participant-evaluation.csv") } + const handleBackClick = (e: React.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에서 불러온 데이터입니다. 미제공 필드는 안내 문구로 표시됩니다.

- {/* Main Content Panel - Scrollable */}
- {/* Back Link */}
- {/* Summary Cards - Row 1 */} + {boardError && ( +
+ {boardError} +
+ )} +
참가자 @@ -326,71 +274,119 @@ export function ParticipantEvaluationContent({ entryCode, participantName: parti
- {isLoadingBoard ? "..." : displayName} + {isLoadingBoard ? "…" : displayName}
- 입장 코드 + 시험 구분 (URL)

{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}

+ )}
- 성과 수준 + 성과 수준 (보드 기준)
- +
- 제출 상태 + 제출·채점 상태
{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) : "–"} +

프롬프트 점수

-

이해 및 문제 해석 능력

+

GET /api/submissions/… 의 score.prompt

-

{participantData.performanceScore}%

+

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

성능 점수

-

실행 효율 및 최적화

+

GET /api/submissions/… 의 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 */}

제출한 코드

@@ -398,120 +394,98 @@ export function ParticipantEvaluationContent({ entryCode, participantName: parti
- 코드 구현 + 코드
- +
-
-                  {dummyCode}
-                
+

+ 현재 GET /api/submissions/{"{id}"} 응답에 + 제출 소스 코드 필드가 포함되어 있지 않습니다. 백엔드에 코드 필드가 추가되면 여기에 표시할 수 있습니다. +

- AI 피드백 요약 + 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} -
  • - ))} -
-
+

+ Spring 관리자 API에는 prompt_evaluations 본문이 + 아직 노출되지 않습니다. AI 평가 텍스트는 별도 내부/분석 API가 마련되면 연결할 수 있습니다. +

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

테스트 케이스 결과

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

채점·테스트 요약

+
+ {!submissionDetail && !isLoadingSubmission && ( +

+ 제출이 없거나 제출 상세를 불러오지 못했습니다. 개별 테스트 케이스 입·출력은 현재 API에 없습니다. +

+ )} + {submissionDetail && ( +
+

+ 제출 상태(상세):{" "} + {submissionDetail.status} +

+ {submissionDetail.metrics && ( +

+ 시간 중앙값: {submissionDetail.metrics.timeMsMedian ?? "–"} ms · 메모리 peak:{" "} + {submissionDetail.metrics.memKbPeak ?? "–"} KB · LOC: {submissionDetail.metrics.loc ?? "–"} +

+ )} + {submissionDetail.tc?.groups && submissionDetail.tc.groups.length > 0 ? ( +
+

채점 그룹별 통과 (submission_runs 집계)

+
+ + + + + + + + + + {submissionDetail.tc.groups.map((g, i) => ( + + + + + + ))} + +
그룹통과전체
{String(g.name)}{g.pass}{g.total}
+
+ {submissionDetail.tc.passRateWeighted != null && ( +

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

+ )}
- {testCase.execTime} - {testCase.memory} - {testCase.tokens} -
- ))} -
+ ) : ( +

그룹별 채점 요약 데이터가 없습니다.

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

diff --git a/lib/api/admin.ts b/lib/api/admin.ts index db67b4c..1c27888 100644 --- a/lib/api/admin.ts +++ b/lib/api/admin.ts @@ -1728,6 +1728,41 @@ export interface ExamineeBoardEntry { tokenLimit: number; tokenUsed: number; submitted: boolean; + /** 최신 제출 ID (submissions.id) */ + submissionId?: number | null; + /** QUEUED | RUNNING | DONE | FAILED */ + submissionStatus?: string | null; + /** scores.total_score (없으면 null) */ + totalScore?: number | null; + /** 제출 생성 시각 (ISO 문자열) */ + submittedAt?: string | null; + /** 점수 행 기준 갱신 시각 (ISO 문자열) */ + evaluatedAt?: string | null; +} + +/** + * 관리자 보드 한 행의 제출·채점 상태를 한글 짧은 라벨로 변환합니다. + */ +export function formatBoardSubmissionLabelKo(entry: ExamineeBoardEntry): string { + if (!entry.submitted) { + return entry.state === "ENTRANCE" ? "진행 중" : "시작 안 함"; + } + if (entry.submissionStatus === "FAILED") { + return "제출 실패"; + } + if (entry.totalScore != null && entry.totalScore !== undefined) { + const n = Number(entry.totalScore); + if (!Number.isNaN(n)) { + return `채점 완료 (${n.toFixed(1)}점)`; + } + } + if (entry.submissionStatus === "DONE") { + return "채점 완료"; + } + if (entry.submissionStatus === "RUNNING" || entry.submissionStatus === "QUEUED") { + return "제출·채점 중"; + } + return "제출됨"; } export interface AdminMetrics { From a713b2a121c7ea00c6ca414792009e042d256b39 Mon Sep 17 00:00:00 2001 From: ChanWook Lee Date: Thu, 14 May 2026 13:09:36 +0900 Subject: [PATCH 07/16] =?UTF-8?q?=EA=B4=80=EB=A6=AC=EC=9E=90=20=ED=8F=89?= =?UTF-8?q?=EA=B0=80=20=EC=83=81=EC=84=B8=20=ED=99=94=EB=A9=B4=20=EC=A0=9C?= =?UTF-8?q?=EC=B6=9C=20=EC=BD=94=EB=93=9C=20=EB=B0=8F=20=EB=A3=A8=EB=B8=8C?= =?UTF-8?q?=EB=A6=AD=20=ED=91=9C=EC=8B=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- components/participant-evaluation-content.tsx | 66 ++++++++++++++----- lib/api/admin.ts | 65 ++++++++++++++++++ 2 files changed, 113 insertions(+), 18 deletions(-) diff --git a/components/participant-evaluation-content.tsx b/components/participant-evaluation-content.tsx index 30b7611..a74f73e 100644 --- a/components/participant-evaluation-content.tsx +++ b/components/participant-evaluation-content.tsx @@ -6,11 +6,12 @@ import { useRouter } from "next/navigation" import { getExams, getBoard, + getAdminSubmissionDetail, formatBoardSubmissionLabelKo, type Exam, type ExamineeBoardEntry, + type AdminSubmissionDetailResponse, } from "@/lib/api/admin" -import { getSubmission, type SubmissionDetailResponse } from "@/lib/api/submissions" interface ParticipantEvaluationContentProps { entryCode: string @@ -78,6 +79,16 @@ function formatScore(n: number | null | undefined): string { return `${Number(n).toFixed(1)}` } +function formatRubricDisplay(raw: string): string { + const trimmed = raw.trim() + if (!trimmed) return "" + try { + return JSON.stringify(JSON.parse(trimmed), null, 2) + } catch { + return trimmed + } +} + export function ParticipantEvaluationContent({ entryCode, participantName: participantNameProp, @@ -92,7 +103,7 @@ export function ParticipantEvaluationContent({ const [boardError, setBoardError] = useState(null) const [isLoadingBoard, setIsLoadingBoard] = useState(true) - const [submissionDetail, setSubmissionDetail] = useState(null) + const [submissionDetail, setSubmissionDetail] = useState(null) const [submissionDetailError, setSubmissionDetailError] = useState(null) const [isLoadingSubmission, setIsLoadingSubmission] = useState(false) @@ -133,20 +144,21 @@ export function ParticipantEvaluationContent({ const submissionId = boardEntry?.submissionId ?? null useEffect(() => { - if (!submissionId) { + 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 getSubmission(submissionId) + const detail = await getAdminSubmissionDetail(submissionIdNum) if (!cancelled) setSubmissionDetail(detail) } catch (e: unknown) { - console.error("getSubmission failed", e) + console.error("getAdminSubmissionDetail failed", e) if (!cancelled) { setSubmissionDetail(null) setSubmissionDetailError( @@ -210,6 +222,8 @@ export function ParticipantEvaluationContent({ `ExamParticipantId,${participantId}`, `ExamId,${examId ?? ""}`, `SubmissionId,${submissionId ?? ""}`, + `HasSubmissionCode,${submissionDetail?.codeInline?.trim() ? "yes" : "no"}`, + `HasRubricJson,${submissionDetail?.rubricJson?.trim() ? "yes" : "no"}`, `BoardStatus,${submissionStatusLabel ?? ""}`, `PromptScore,${scoreFromDetail?.prompt ?? ""}`, `PerfScore,${scoreFromDetail?.perf ?? ""}`, @@ -243,7 +257,7 @@ export function ParticipantEvaluationContent({

참가자 평가 상세

- 보드·제출 API에서 불러온 데이터입니다. 미제공 필드는 안내 문구로 표시됩니다. + 보드 API와 관리자 전용 제출 상세 API에서 불러온 데이터입니다. 미제공 필드는 안내 문구로 표시됩니다.

@@ -349,14 +363,14 @@ export function ParticipantEvaluationContent({ {detailScoresMeaningful ? formatScore(scoreFromDetail?.prompt ?? null) : "–"}

프롬프트 점수

-

GET /api/submissions/… 의 score.prompt

+

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

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

성능 점수

-

GET /api/submissions/… 의 score.perf

+

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

@@ -365,7 +379,7 @@ export function ParticipantEvaluationContent({

정답률 점수

{detailScoresMeaningful - ? "상세 API score.correctness" + ? "관리자 제출 상세 API score.correctness" : showBoardTotalOnly ? "항목별 값 없음 — 아래 총점만 보드 참고" : "데이터 없음"} @@ -374,7 +388,7 @@ export function ParticipantEvaluationContent({

{detailScoresMeaningful && (

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

)} {!detailScoresMeaningful && showBoardTotalOnly && ( @@ -399,10 +413,17 @@ export function ParticipantEvaluationContent({
-

- 현재 GET /api/submissions/{"{id}"} 응답에 - 제출 소스 코드 필드가 포함되어 있지 않습니다. 백엔드에 코드 필드가 추가되면 여기에 표시할 수 있습니다. -

+ {isLoadingSubmission ? ( +

불러오는 중…

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

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

+ ) : ( +

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

+ )}
@@ -410,10 +431,19 @@ export function ParticipantEvaluationContent({ AI 피드백 (루브릭·턴 평가)
-

- Spring 관리자 API에는 prompt_evaluations 본문이 - 아직 노출되지 않습니다. AI 평가 텍스트는 별도 내부/분석 API가 마련되면 연결할 수 있습니다. -

+ {isLoadingSubmission ? ( +

불러오는 중…

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

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

+ ) : ( +

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

+ )}
diff --git a/lib/api/admin.ts b/lib/api/admin.ts index 1c27888..4adce37 100644 --- a/lib/api/admin.ts +++ b/lib/api/admin.ts @@ -1891,6 +1891,71 @@ export async function getBoard(examId: number): Promise { return data.result ?? []; } +/** 관리자 제출 상세 API와 동일한 상태 값 (백엔드 SubmissionStatus) */ +export type AdminSubmissionStatusDto = 'QUEUED' | 'RUNNING' | 'DONE' | 'FAILED'; + +export interface AdminSubmissionScoreInfo { + prompt: number | null; + perf: number | null; + correctness: number | null; + total: number | null; +} + +export interface AdminSubmissionMetricsInfo { + timeMsMedian: number | null; + memKbPeak: number | null; + loc: number | null; +} + +export interface AdminSubmissionGroupInfo { + name: string; + pass: number; + total: number; + weight: number; +} + +export interface AdminSubmissionTestCaseInfo { + passRateWeighted: number | null; + groups: AdminSubmissionGroupInfo[]; +} + +/** + * GET /api/admin/submissions/{submissionId} 응답 (코드·루브릭 포함, ADMIN/MASTER 전용) + */ +export interface AdminSubmissionDetailResponse { + submissionId: number; + status: AdminSubmissionStatusDto; + lang: string; + codeInline: string | null; + metrics: AdminSubmissionMetricsInfo | null; + tc: AdminSubmissionTestCaseInfo | null; + score: AdminSubmissionScoreInfo | null; + rubricJson: string | null; +} + +/** + * 관리자 전용 제출 상세 조회 (제출 코드·rubricJson 포함) + * GET /api/admin/submissions/{submissionId} + */ +export async function getAdminSubmissionDetail( + submissionId: number +): Promise { + const apiBaseUrl = getApiBaseUrl(); + const url = `${apiBaseUrl}/api/admin/submissions/${submissionId}`; + + const response = await fetchAdminWithRetry(url, { + method: 'GET', + headers: getAuthHeaders(), + credentials: 'include', + }); + + const data: BaseResponse = await response.json(); + if (!response.ok || data.code !== 'COMMON200' || !data.result) { + throw new LoginFailedError(data.message || '제출 상세(관리자) 조회에 실패했습니다.', response.status); + } + return data.result; +} + // ─── SSE 채점 결과 스트리밍 ──────────────────────────────────────────────────── // streamScoringResult는 lib/api/submissions.ts 에서 정의·export됩니다. // 이전에 이 파일에 존재하던 구버전 구현은 submissions.ts 의 콜백 기반 버전으로 통합되었습니다. From 812f8384c626d7d3adb4c56210576b81f6ba8c95 Mon Sep 17 00:00:00 2001 From: ChanWook Lee Date: Thu, 14 May 2026 15:07:23 +0900 Subject: [PATCH 08/16] =?UTF-8?q?=EC=9D=91=EC=8B=9C=EC=9E=90=20=EC=A0=9C?= =?UTF-8?q?=EC=B6=9C=20=EC=8A=A4=ED=8A=B8=EB=A6=BC=20=EC=97=B0=EA=B2=B0=20?= =?UTF-8?q?=EB=B0=8F=20SSE=20cleanup=20=EA=B0=9C=EC=84=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- components/user-test-screen.tsx | 6 +++++- lib/api/submissions.ts | 8 ++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/components/user-test-screen.tsx b/components/user-test-screen.tsx index 1bdffcc..210a0d4 100644 --- a/components/user-test-screen.tsx +++ b/components/user-test-screen.tsx @@ -145,6 +145,7 @@ export default function UserTestScreen() { const handleCodeSubmitted = (submissionId: number) => { // 이전 SSE 연결 취소 sseCleanupRef.current?.(); + sseCleanupRef.current = null; setIsScoring(true); setCaseResultCount(0); @@ -182,6 +183,7 @@ export default function UserTestScreen() { useEffect(() => { return () => { sseCleanupRef.current?.(); + sseCleanupRef.current = null; }; }, []); @@ -224,6 +226,8 @@ export default function UserTestScreen() { }, [examId, isExamEnded, showEndModal]); const handleGoHome = () => { + sseCleanupRef.current?.(); + sseCleanupRef.current = null; router.push("/"); }; @@ -458,7 +462,7 @@ export default function UserTestScreen() {
diff --git a/lib/api/submissions.ts b/lib/api/submissions.ts index 18cfd22..8339292 100644 --- a/lib/api/submissions.ts +++ b/lib/api/submissions.ts @@ -118,7 +118,7 @@ export async function getSubmission(submissionId: number): Promise void { const controller = new AbortController(); const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8080'; - const url = `${apiBaseUrl}/api/admin/submissions/${submissionId}/stream`; + const url = `${apiBaseUrl}/api/submissions/${submissionId}/stream`; async function connect() { try { From f2b6bf3bffdae3ec62380926922f0098342231df Mon Sep 17 00:00:00 2001 From: ChanWook Lee Date: Sun, 17 May 2026 16:09:13 +0900 Subject: [PATCH 09/16] =?UTF-8?q?=EA=B4=80=EB=A6=AC=EC=9E=90=20=EC=B0=B8?= =?UTF-8?q?=EA=B0=80=EC=9E=90=20=ED=8F=89=EA=B0=80=20=EC=83=81=EC=84=B8=20?= =?UTF-8?q?=ED=99=94=EB=A9=B4=20=EA=B0=9C=EC=84=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../[entryCode]/[participantId]/page.tsx | 14 +- components/analytics-content.tsx | 11 +- components/participant-evaluation-content.tsx | 196 ++---- .../participant-evaluation-rubric-report.tsx | 655 ++++++++++++++++++ .../participant-evaluation-test-summary.tsx | 262 +++++++ components/participant-list-content.tsx | 15 +- components/test-session-details-content.tsx | 15 +- lib/api/admin.ts | 13 + lib/api/submissions.ts | 30 +- lib/api/user-client.ts | 36 + lib/code-quality-metrics-labels.ts | 83 +++ lib/paths/admin-participant-evaluation.ts | 34 + lib/performance-level.ts | 43 ++ lib/rubric-json.ts | 219 ++++++ 14 files changed, 1451 insertions(+), 175 deletions(-) create mode 100644 components/participant-evaluation-rubric-report.tsx create mode 100644 components/participant-evaluation-test-summary.tsx create mode 100644 lib/api/user-client.ts create mode 100644 lib/code-quality-metrics-labels.ts create mode 100644 lib/paths/admin-participant-evaluation.ts create mode 100644 lib/performance-level.ts create mode 100644 lib/rubric-json.ts 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/components/analytics-content.tsx b/components/analytics-content.tsx index 516afaa..5fd2c97 100644 --- a/components/analytics-content.tsx +++ b/components/analytics-content.tsx @@ -4,6 +4,7 @@ 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" +import { adminParticipantEvaluationHref } from "@/lib/paths/admin-participant-evaluation" type Trend = "높음" | "보통" | "낮음" type Status = "완료" | "진행 중" @@ -150,10 +151,12 @@ function ParticipantCard({ participant }: { participant: Participant }) {
상세 보기 → diff --git a/components/participant-evaluation-content.tsx b/components/participant-evaluation-content.tsx index a74f73e..045a745 100644 --- a/components/participant-evaluation-content.tsx +++ b/components/participant-evaluation-content.tsx @@ -12,6 +12,9 @@ import { type ExamineeBoardEntry, type AdminSubmissionDetailResponse, } from "@/lib/api/admin" +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 @@ -49,25 +52,9 @@ function findExamByResultsSegment(exams: Exam[], segment: string) { return undefined } -function trendFromBoard(entry: ExamineeBoardEntry | null): "High" | "Average" | "Low" { - if (!entry) return "Low" - if (entry.submitted) return "High" - if (entry.state === "ENTRANCE") return "Average" - return "Low" -} - -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]", - } - const trendText: Record = { - High: "높음", - Average: "보통", - Low: "낮음", - } - return {trendText[trend]} +function PerformanceLevelBadge({ totalScore }: { totalScore: number | null | undefined }) { + const { label, badgeClass } = resolveBoardPerformanceLevel(totalScore) + return {label} } function LanguageBadge({ language }: { language: string }) { @@ -79,16 +66,6 @@ function formatScore(n: number | null | undefined): string { return `${Number(n).toFixed(1)}` } -function formatRubricDisplay(raw: string): string { - const trimmed = raw.trim() - if (!trimmed) return "" - try { - return JSON.stringify(JSON.parse(trimmed), null, 2) - } catch { - return trimmed - } -} - export function ParticipantEvaluationContent({ entryCode, participantName: participantNameProp, @@ -186,8 +163,6 @@ export function ParticipantEvaluationContent({ return formatBoardSubmissionLabelKo(boardEntry) }, [boardEntry]) - const trend = useMemo(() => trendFromBoard(boardEntry), [boardEntry]) - const scoreFromDetail = submissionDetail?.score /** BE는 Score 행이 없어도 0으로 채워 보냄 → 전부 0이면 ‘실제 점수 없음’으로 간주 */ const detailScoresMeaningful = @@ -202,6 +177,18 @@ export function ParticipantEvaluationContent({ !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() setToasts((prev) => [...prev, { id, title, description }]) @@ -262,8 +249,8 @@ export function ParticipantEvaluationContent({
-
-
+
+
+ {open &&
{children}
} + + ) +} + +function MetricCell({ + label, + value, + description, +}: { + label: string + value: string + description?: string +}) { + return ( +
+
+

{label}

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

{value}

+
+ ) +} + +function TextBlock({ text }: { text: string }) { + return ( +

{text}

+ ) +} + +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 showHint = title === R4_CONTEXT_SECTION_TITLE + return ( +
+

{title}

+ {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 ? ( +

{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) => ( +
  • + {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(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 cfc93ef..92af3fa 100644 --- a/components/participant-list-content.tsx +++ b/components/participant-list-content.tsx @@ -4,6 +4,7 @@ import { useState, useEffect, useMemo } from "react" import Link from "next/link" import { ArrowLeft, Eye, ChevronLeft, ChevronRight } from "lucide-react" import { getExams, getBoard, ExamineeBoardEntry, type Exam } from "@/lib/api/admin" +import { adminParticipantEvaluationHref } from "@/lib/paths/admin-participant-evaluation" type TrendLevel = "High" | "Average" | "Low" @@ -222,14 +223,12 @@ export function ParticipantListContent({ entryCode }: ParticipantListContentProp
diff --git a/components/test-session-details-content.tsx b/components/test-session-details-content.tsx index e012121..32d40b3 100644 --- a/components/test-session-details-content.tsx +++ b/components/test-session-details-content.tsx @@ -9,6 +9,7 @@ import { Button } from "@/components/ui/button" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table" import Link from "next/link"; import { getBoard, formatBoardSubmissionLabelKo, type ExamineeBoardEntry } from "@/lib/api/admin"; +import { adminParticipantEvaluationHref } from "@/lib/paths/admin-participant-evaluation"; // Participant type type Participant = { @@ -279,13 +280,13 @@ export default function TestSessionDetailsContent({ session, onBack }: TestSessi - )}
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/lib/api/auth.ts b/lib/api/auth.ts index ea06a94..75ed586 100644 --- a/lib/api/auth.ts +++ b/lib/api/auth.ts @@ -57,9 +57,7 @@ export interface ExamInfoResponse { } export interface SessionInfoResponse { - id: number; - examId: number; - participantId: number; + examParticipantId: number; tokenLimit: number; tokenUsed: number; } diff --git a/lib/api/exams.ts b/lib/api/exams.ts index 1b98034..895126c 100644 --- a/lib/api/exams.ts +++ b/lib/api/exams.ts @@ -173,6 +173,8 @@ export interface ParticipantSessionResponse { export interface ActiveSessionResponse { examId: number; examParticipantId: number; + /** users.id */ + participantId: number; assignedProblemId: number | null; specId: number | null; examState: ExamState; diff --git a/lib/stores/exam-session-store.ts b/lib/stores/exam-session-store.ts index 39c20bd..e90415b 100644 --- a/lib/stores/exam-session-store.ts +++ b/lib/stores/exam-session-store.ts @@ -2,7 +2,10 @@ import { create } from "zustand"; interface ExamSessionState { examId: number | null; + /** users.id — 채팅 STOMP·JWT·assignment/draft와 동일 */ participantId: number | null; + /** exam_participants.id (PK) */ + examParticipantId: number | null; tokenLimit: number; accessToken: string | null; setSession: (examId: number, participantId: number, tokenLimit?: number) => void; @@ -13,10 +16,17 @@ interface ExamSessionState { export const useExamSessionStore = create((set) => ({ examId: null, participantId: null, + examParticipantId: null, tokenLimit: 20000, accessToken: null, setSession: (examId, participantId, tokenLimit = 20000) => set({ examId, participantId, tokenLimit }), setAccessToken: (token) => set({ accessToken: token }), - clearSession: () => set({ examId: null, participantId: null, tokenLimit: 20000, accessToken: null }), + clearSession: () => + set({ + examId: null, + participantId: null, + examParticipantId: null, + tokenLimit: 20000, + accessToken: null, + }), })); - From 9d899d2eb726ae69440b6cf3663bdec99854315c Mon Sep 17 00:00:00 2001 From: ChanWook Lee Date: Tue, 19 May 2026 06:41:50 +0900 Subject: [PATCH 13/16] =?UTF-8?q?=EA=B4=80=EB=A6=AC=EC=9E=90=20=EB=B6=84?= =?UTF-8?q?=EC=84=9D=20=EB=B0=8F=20=EC=B0=B8=EA=B0=80=EC=9E=90=20=EA=B4=80?= =?UTF-8?q?=EB=A6=AC=20UI=20=EA=B0=9C=EC=84=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- components/analytics-content.tsx | 392 +++++++------- components/dashboard-content.tsx | 12 +- components/participant-evaluation-content.tsx | 83 +-- .../participant-evaluation-rubric-report.tsx | 21 +- components/results-content.tsx | 55 +- components/server-status-content.tsx | 173 ++++--- components/users-content.tsx | 485 ++++++++++++------ lib/admin-board-analytics.ts | 111 ++++ lib/admin-board-csv-export.ts | 113 ++++ lib/api/admin.ts | 38 ++ lib/utils/cleanup-ai-feedback.ts | 43 ++ 11 files changed, 1055 insertions(+), 471 deletions(-) create mode 100644 lib/admin-board-analytics.ts create mode 100644 lib/admin-board-csv-export.ts create mode 100644 lib/utils/cleanup-ai-feedback.ts diff --git a/components/analytics-content.tsx b/components/analytics-content.tsx index 5fd2c97..96f0779 100644 --- a/components/analytics-content.tsx +++ b/components/analytics-content.tsx @@ -2,25 +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" +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" -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 +interface BoardRow { + entry: ExamineeBoardEntry + examId: number + examTitle: string + examResultsSegment: string } interface Toast { @@ -29,133 +34,76 @@ 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 - - const total = - entry.totalScore != null && entry.totalScore !== undefined ? Number(entry.totalScore) : null - const avgScore = total != null && !Number.isNaN(total) ? total : 0 - - return { - id: entry.examParticipantId.toString(), - name: entry.name, - entryCode: examTitle, - avgScore, - 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}

@@ -166,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() @@ -235,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 (
@@ -265,7 +258,7 @@ export function AnalyticsContent() {

통계 분석

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

@@ -292,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) => ( + ))}
@@ -369,6 +382,7 @@ export function AnalyticsContent() {

{toast.description}

-
+
= { + 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/users-content.tsx b/components/users-content.tsx index 9e4c6b9..fc2f8dd 100644 --- a/components/users-content.tsx +++ b/components/users-content.tsx @@ -1,152 +1,146 @@ "use client" -import { useState } from "react" -import { ChevronLeft, ChevronRight } from "lucide-react" +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" -type ConnectionStatus = "연결됨" | "대기 중" -type SubmissionStatus = "시작 전" | "진행 중" | "제출 완료" +type ConnectionStatus = "응시 완료" | "응시 중" | "대기 중" | "종료됨" + +const EXAM_ENDED_STATES = new Set(["ENDED", "COMPLETED", "FINISHED", "CLOSED"]) +type SubmissionStatus = "시작 전" | "진행 중" | "채점 중" | "제출 완료" interface Participant { id: string name: string + examLabel: string phone: string connectionStatus: ConnectionStatus submissionStatus: SubmissionStatus 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, - }, -] +const PARTICIPANT_WAITING_STATES = new Set(["WAITING", "PENDING", "IDLE"]) + +const PARTICIPANT_EXAMINING_STATES = new Set([ + "ACTIVE", + "RUNNING", + "IN_PROGRESS", + "ENTRANCE", + "STARTED", + "JOINED", +]) + +function normalizeParticipantState(state: string | null | undefined): string { + return (state ?? "").trim().toUpperCase() +} + +function isWaitingParticipant(entry: ExamineeBoardEntry): boolean { + const state = normalizeParticipantState(entry.state) + if (PARTICIPANT_WAITING_STATES.has(state)) return true + if (!state && (entry.tokenUsed ?? 0) === 0 && !entry.submitted) return true + return false +} + +function isExamineeInProgress(entry: ExamineeBoardEntry): boolean { + if (entry.submitted) return false + const state = normalizeParticipantState(entry.state) + if (PARTICIPANT_EXAMINING_STATES.has(state)) return true + if ((entry.tokenUsed ?? 0) > 0) return true + if ( + entry.submissionStatus === "QUEUED" || + entry.submissionStatus === "RUNNING" + ) { + return true + } + return false +} + +function normalizeSubmissionStatus(status: string | null | undefined): string { + return (status ?? "").trim().toUpperCase() +} + +function isGradingComplete(entry: ExamineeBoardEntry): boolean { + if (!entry.submitted) return false + const status = normalizeSubmissionStatus(entry.submissionStatus) + if (status === "FAILED") return true + + if (entry.evaluatedAt) return true + if (entry.totalScore != null && entry.totalScore !== undefined) { + const n = Number(entry.totalScore) + if (!Number.isNaN(n)) return true + } + return false +} + +function isExamEnded(exam: Exam): boolean { + const state = (exam.state ?? "").trim().toUpperCase() + if (EXAM_ENDED_STATES.has(state)) return true + if (exam.endsAt) { + const endMs = new Date(exam.endsAt).getTime() + if (!Number.isNaN(endMs) && endMs <= Date.now()) return true + } + return false +} + +function mapConnectionStatus(entry: ExamineeBoardEntry, exam: Exam): ConnectionStatus { + if (isExamEnded(exam)) return "종료됨" + if (entry.submitted) return "응시 완료" + if (isWaitingParticipant(entry)) return "대기 중" + if (isExamineeInProgress(entry)) return "응시 중" + return "대기 중" +} + +function mapSubmissionStatus(entry: ExamineeBoardEntry): SubmissionStatus { + if (!entry.submitted) { + if (isExamineeInProgress(entry)) return "진행 중" + return "시작 전" + } + if (isGradingComplete(entry)) return "제출 완료" + return "채점 중" +} + +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 { + return { + id: `${exam.id}-${entry.examParticipantId}`, + name: entry.name || "–", + examLabel: resolveExamDisplayLabel(exam), + phone: entry.phoneMasked || "–", + connectionStatus: mapConnectionStatus(entry, exam), + submissionStatus: mapSubmissionStatus(entry), + tokenUsage: entry.tokenUsed ?? 0, + } +} function ConnectionBadge({ status }: { status: ConnectionStatus }) { - const isConnected = status === "연결됨" + 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 = { + const styles: Record = { "시작 전": "bg-[#F3F4F6] text-[#6B7280]", "진행 중": "bg-[#E0EDFF] text-[#3B82F6]", + "채점 중": "bg-[#FEF3C7] text-[#D97706]", "제출 완료": "bg-[#DCFCE7] text-[#16A34A]", } @@ -154,75 +148,240 @@ function SubmissionBadge({ status }: { status: SubmissionStatus }) { } 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) => 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}명`}
+ {listError && !isLoading && ( +

+ {listError} +

+ )} @@ -578,12 +494,14 @@ 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 ( @@ -658,7 +576,7 @@ export function AdminAccountsContent() { color: "#6B7280", }} > - {user.lastLogin} + {displayValue(user.lastLogin)} @@ -686,23 +604,18 @@ export function AdminAccountsContent() { 상태 변경 !isSystemMaster && handleOpenResetPassword(user)} + disabled={isSystemMaster || user.role === "MASTER"} + onClick={() => + !isSystemMaster && + user.role !== "MASTER" && + handleOpenResetPassword(user) + } > 비밀번호 재설정 - !isSystemMaster && handleOpenReissueKey(user)} - > - - 시크릿 키 재발급 - - 관리자의 다음 로그인을 위해 임시 비밀번호가 생성됩니다. + 해당 관리자의 비밀번호를 임시 비밀번호로 재설정하시겠습니까?

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

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

All access for this admin will be removed immediately.

+

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

-
@@ -1183,6 +1052,12 @@ export function AdminAccountsContent() { +
+

이름

+

+ {displayValue(selectedAdmin?.displayName)} +

+

이메일

@@ -1207,13 +1082,13 @@ export function AdminAccountsContent() {

마지막 로그인

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

생성일

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

@@ -1224,54 +1099,11 @@ export function AdminAccountsContent() { {/* Security Settings Section */}

보안 설정

-
-
-

비밀번호 상태

-

- 비밀번호 설정됨 -

-
-
-

시크릿 키

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

마지막 시크릿 키 발급일

-

- {selectedAdmin?.lastKeyIssued} -

-
+
+

비밀번호 상태

+

+ {selectedAdmin?.passwordStatus ?? "-"} +

@@ -1304,18 +1136,6 @@ export function AdminAccountsContent() { > 비밀번호 재설정 - -
+ ) } 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 f6aa05d..6f6f560 100644 --- a/components/participant-evaluation-content.tsx +++ b/components/participant-evaluation-content.tsx @@ -23,11 +23,16 @@ import { ParticipantEvaluationTestSummary } from "@/components/participant-evalu import { ParticipantEvaluationRubricReport } from "@/components/participant-evaluation-rubric-report" interface ParticipantEvaluationContentProps { - entryCode: string + /** Admin: entryCode / title / exam id 문자열. Master: 생략 가능(examId 사용) */ + entryCode?: string + /** Master 전용 — 지정 시 entryCode 조회 없이 직접 보드 로드 */ + examId?: number participantName?: string /** URL 세그먼트 — 목록·보드와 동일하게 `exam_participants.id` (examParticipantId) */ participantId: string onBack?: () => void + /** 뒤로가기 버튼 문구 (기본: 이전 페이지로 돌아가기) */ + backLabel?: string } interface ToastItem { @@ -73,15 +78,18 @@ function formatScore(n: number | null | undefined): string { } export function ParticipantEvaluationContent({ - entryCode, + entryCode = "", + examId: examIdProp, participantName: participantNameProp, participantId, onBack, + backLabel = "이전 페이지로 돌아가기", }: ParticipantEvaluationContentProps) { const router = useRouter() const [toasts, setToasts] = useState([]) - const [examId, setExamId] = 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) @@ -96,18 +104,40 @@ export function ParticipantEvaluationContent({ setIsLoadingBoard(true) setBoardError(null) setBoardEntry(null) - setExamId(null) + setExamTitle(null) + + const directExamId = + examIdProp != null && Number.isFinite(examIdProp) && examIdProp > 0 ? examIdProp : null + try { - const exams = await getExams() - const matched = findExamByResultsSegment(exams, entryCode) - if (!matched) { - if (!cancelled) setBoardError("해당 입장 코드·시험명에 맞는 시험을 찾을 수 없습니다.") + 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 board = await getBoard(resolvedExamId) const entry = board.find((p) => String(p.examParticipantId) === String(participantId)) if (!cancelled) { - setExamId(matched.id) + setExamId(resolvedExamId) + setExamTitle(resolvedTitle) if (entry) setBoardEntry(entry) else setBoardError("참가자를 보드에서 찾을 수 없습니다. (ID가 examParticipantId와 일치하는지 확인하세요)") } @@ -122,7 +152,7 @@ export function ParticipantEvaluationContent({ return () => { cancelled = true } - }, [entryCode, participantId]) + }, [entryCode, examIdProp, participantId]) const submissionId = boardEntry?.submissionId ?? null @@ -209,7 +239,7 @@ export function ParticipantEvaluationContent({ const handleExport = () => { try { - const examLabel = entryCode.trim() || "session" + const examLabel = (examTitle ?? entryCode).trim() || "session" const csvBody = buildKeyValueCsvBody([ { label: "이름", value: displayName }, { label: "시험", value: examLabel, excelTextValue: true }, @@ -280,7 +310,7 @@ export function ParticipantEvaluationContent({ className="inline-flex items-center gap-1.5 text-sm text-[#6B7280] transition-colors hover:text-[#4B5563]" > - 이전 페이지로 돌아가기 + {backLabel}
@@ -303,8 +333,12 @@ export function ParticipantEvaluationContent({
- 시험 구분 (URL) -

{entryCode}

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

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

{examId != null &&

examId: {examId}

}
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 bdde756..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 { @@ -91,9 +92,7 @@ export function ProblemSection({ examId }: ProblemSectionProps) { {problem && ( <> -
- {problem.contentMd} -
+
{problem.tags.map((tag) => ( diff --git a/components/settings-content.tsx b/components/settings-content.tsx index 223c2fc..52e1910 100644 --- a/components/settings-content.tsx +++ b/components/settings-content.tsx @@ -14,7 +14,14 @@ 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, +} from "@/lib/api/admin" import { useToast } from "@/hooks/use-toast" import { Lock } from "lucide-react" @@ -47,12 +54,14 @@ export function SettingsContent() { setIsLoading(true); try { const response = await getMe(); - // ADMIN의 경우: participant.name = adminNumber, participant.phone = email - // 이름은 백엔드에서 제공하지 않으므로 더미 데이터 사용 + const adminNumber = + response.participant.adminNumber?.trim() || + response.participant.name?.trim() || + ""; setAdminProfile({ - name: "Admin", // 더미 데이터 (백엔드에서 제공되지 않음) - email: response.participant.phone || "", // email - adminNumber: response.participant.name || "", // adminNumber + name: resolveAdminDisplayNameFromMe(response), + email: response.participant.phone || "", + adminNumber, }); } catch (error) { if (error instanceof LoginFailedError) { @@ -237,7 +246,7 @@ export function SettingsContent() { {isLoading ? (
- +
- + diff --git a/components/test-session-details-content.tsx b/components/test-session-details-content.tsx index 32d40b3..172d941 100644 --- a/components/test-session-details-content.tsx +++ b/components/test-session-details-content.tsx @@ -1,101 +1,181 @@ "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, formatBoardSubmissionLabelKo, type ExamineeBoardEntry } from "@/lib/api/admin"; -import { adminParticipantEvaluationHref } from "@/lib/paths/admin-participant-evaluation"; +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 - /** 제출 레코드 존재 여부 (요약 통계용) */ + 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: ExamineeBoardEntry) => ({ - id: p.examParticipantId, - name: p.name, - phoneNumber: p.phoneMasked, - connectionStatus: p.state === "ENTRANCE" ? "Connected" : "Pending", - hasSubmission: p.submitted, - submissionStatusLabel: formatBoardSubmissionLabelKo(p), - 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 sessionMeta = exam ? mapExamToTestSession(exam) : null + const statusLabel = exam ? getMasterSessionStatusLabel(exam.state) : "-" + const displaySessionId = sessionMeta?.sessionId ?? "-" + 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 응시 중 + } + if (status === "대기 중") { + return 대기 중 } - return 대기 중 + return {status} } const getSubmissionBadge = (label: string) => { @@ -120,7 +200,6 @@ export default function TestSessionDetailsContent({ session, onBack }: TestSessi return {label} } - // Generate page numbers for pagination const getPageNumbers = () => { const pages: number[] = [] for (let i = 1; i <= totalPages; i++) { @@ -130,225 +209,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}

+
+
+

생성자

+

Admin

+
+
+

생성일

+

{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.submissionStatusLabel)} - - - {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 eb20c61..c1027f0 100644 --- a/components/test-sessions-content.tsx +++ b/components/test-sessions-content.tsx @@ -18,7 +18,13 @@ 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, formatBoardSubmissionLabelKo } 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" function submissionBadgeClassName(label: string): string { if (label === "시작 안 함") return "bg-gray-100 text-gray-700 hover:bg-gray-100" @@ -30,14 +36,7 @@ function submissionBadgeClassName(label: string): string { return "bg-gray-100 text-gray-700 hover:bg-gray-100" } -export interface TestSession { - id: number - sessionId: string // BE의 title을 sessionId로 매핑 (필요시) - createdBy: string - createdAt: string - status: string - participants: number -} +export type TestSession = TestSessionListItem interface Participant { id: number @@ -76,15 +75,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 { @@ -94,6 +85,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) @@ -101,7 +93,7 @@ export function TestSessionsContent({ onViewDetails }: TestSessionsContentProps) id: participant.examParticipantId, name: participant.name, phoneNumber: participant.phoneMasked, - connectionStatus: participant.state === "ENTRANCE" ? "Connected" : "Disconnected", + connectionStatus: mapBoardConnectionStatus(participant.state), hasSubmission: participant.submitted, submissionStatusLabel: formatBoardSubmissionLabelKo(participant), tokenUsage: participant.tokenUsed || 0, @@ -152,13 +144,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) @@ -189,30 +182,13 @@ export function TestSessionsContent({ onViewDetails }: TestSessionsContentProps) } return ( -
- {/* Page Header */} -
-

- 테스트 세션 -

-

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

-
+
+ +
{/* Main Card */} @@ -362,7 +338,7 @@ export function TestSessionsContent({ onViewDetails }: TestSessionsContentProps) fontFamily: "Inter, system-ui, -apple-system, sans-serif", }} > - {session.status === "Active" ? "진행 중" : session.status === "Completed" ? "완료" : session.status} + {session.status === "Active" ? "진행 중" : session.status === "Completed" ? "완료" : session.statusLabel} +
) } diff --git a/lib/api/admin.ts b/lib/api/admin.ts index 2ad1e70..5247e9b 100644 --- a/lib/api/admin.ts +++ b/lib/api/admin.ts @@ -107,6 +107,7 @@ export interface AdminLoginResponse { // AdminSignupRequest export interface AdminSignupRequest { adminNumber: string; + displayName: string; email: string; password: string; } @@ -116,13 +117,28 @@ export interface MeResponse { role: string; participant: { id: number; - name: string; // ADMIN의 경우 adminNumber가 들어감 - phone: string; // ADMIN의 경우 email이 들어감 + name: string; // ADMIN: displayName(또는 fallback), USER: 참가자 이름 + phone: string; // ADMIN: email, USER: 전화번호 + adminNumber?: string | null; // ADMIN 전용 }; exam?: null; session?: null; } +/** GET /api/auth/me 응답에서 관리자 표시 이름 해석 (displayName → adminNumber → "관리자") */ +export function resolveAdminDisplayNameFromMe(response: MeResponse): string { + const participant = response.participant; + const adminNumber = + participant.adminNumber?.trim() || + participant.name?.trim() || + ""; + return ( + participant.name?.trim() || + adminNumber || + "관리자" + ); +} + // AdminInfo (AdminListResponse에서 사용) export interface AdminInfo { id: number; @@ -130,6 +146,11 @@ export interface AdminInfo { email: string; role: 'ADMIN' | 'MASTER'; is2faEnabled: boolean; + isActive?: boolean; + displayName?: string | null; + createdAt?: string | null; + adminNumberIssuedAt?: string | null; + lastLoginAt?: string | null; } // AdminListResponse @@ -171,6 +192,11 @@ export interface ChangeAdminPasswordRequest { newPassword: string; } +/** MASTER가 타 관리자 임시 비밀번호 재설정 응답 */ +export interface ResetAdminPasswordByMasterResponse { + temporaryPassword: string; +} + export interface AdminProblem { id: number; title: string; @@ -178,6 +204,43 @@ export interface AdminProblem { tags: string | string[] | null; status: string; createdAt: string; + updatedAt?: string | null; + version?: number | string | null; + usedSessionCount?: number | null; + usedInSessions?: number | null; + sessionCount?: number | null; +} + +export interface ProblemSpecResponse { + specId: number; + version: number; + changelogMd: string | null; + publishedAt: string | null; +} + +export interface AdminProblemDetail { + id: number; + title: string; + difficulty: 'EASY' | 'MEDIUM' | 'HARD'; + tags: string[]; + version: number; + contentMd: string; + limits: { + timeMs: number; + memoryMb: number; + }; + restrictions: { + allowedLangs: string[]; + forbiddenApis: string[]; + }; + checker: { + type: string; + }; + createdAt: string; + updatedAt: string | null; + publishedAt: string | null; + status: string; + usable: boolean; } /** @@ -296,6 +359,74 @@ export async function getProblems(): Promise { } } +/** + * 문제 스펙(버전) 목록 조회 — GET /api/admin/problems/{problemId}/specs + */ +export async function getProblemSpecs(problemId: number): Promise { + const apiBaseUrl = getApiBaseUrl(); + const url = `${apiBaseUrl}/api/admin/problems/${problemId}/specs`; + + try { + const response = await fetch(url, { + method: 'GET', + headers: getAuthHeaders(), + credentials: 'include', + }); + + const data: BaseResponse = await response.json(); + + if (!response.ok || data.code !== 'COMMON200' || !data.result) { + throw new LoginFailedError(data.message || '문제 스펙 조회에 실패했습니다.', response.status, data.code); + } + + return data.result; + } catch (error) { + if (error instanceof LoginFailedError) { + throw error; + } + + if (error instanceof TypeError && error.message.includes('fetch')) { + throw new NetworkError('서버에 연결할 수 없습니다. 네트워크 연결을 확인해주세요.'); + } + + throw new NetworkError('문제 스펙 조회 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.'); + } +} + +/** + * 문제 상세 조회 — GET /api/admin/problems/{problemId}/detail + */ +export async function getProblemDetail(problemId: number): Promise { + const apiBaseUrl = getApiBaseUrl(); + const url = `${apiBaseUrl}/api/admin/problems/${problemId}/detail`; + + try { + const response = await fetch(url, { + method: 'GET', + headers: getAuthHeaders(), + credentials: 'include', + }); + + const data: BaseResponse = await response.json(); + + if (!response.ok || data.code !== 'COMMON200' || !data.result) { + throw new LoginFailedError(data.message || '문제 상세 조회에 실패했습니다.', response.status, data.code); + } + + return data.result; + } catch (error) { + if (error instanceof LoginFailedError) { + throw error; + } + + if (error instanceof TypeError && error.message.includes('fetch')) { + throw new NetworkError('서버에 연결할 수 없습니다. 네트워크 연결을 확인해주세요.'); + } + + throw new NetworkError('문제 상세 조회 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.'); + } +} + /** * 모든 관리자 조회 API 호출 (마스터 전용) */ @@ -507,6 +638,75 @@ export async function updateAdminNumber( } } +/** + * MASTER가 타 관리자 임시 비밀번호 재설정 API 호출 + */ +export async function resetAdminPasswordByMaster( + adminNumber: string +): Promise { + const apiBaseUrl = getApiBaseUrl(); + const url = `${apiBaseUrl}/api/admin/admin-numbers/${encodeURIComponent(adminNumber)}/password/reset`; + const isDev = process.env.NODE_ENV === 'development'; + + if (isDev) { + console.log('[Reset Admin Password By Master] API 호출:', url); + } + + try { + const response = await fetch(url, { + method: 'PATCH', + headers: getAuthHeaders(), + credentials: 'include', + }); + + if (!response.ok) { + let errorMessage = '비밀번호 재설정에 실패했습니다.'; + + if (response.status === 401) { + errorMessage = '인증이 필요합니다. 다시 로그인해주세요.'; + } else if (response.status === 403) { + errorMessage = '마스터 계정만 비밀번호를 재설정할 수 있습니다.'; + } + + try { + const errorText = await response.text(); + if (errorText) { + try { + const errorData = JSON.parse(errorText); + if (errorData.message) { + errorMessage = errorData.message; + } + } catch { + // ignore + } + } + } catch { + // ignore + } + + throw new LoginFailedError(errorMessage, response.status); + } + + const data: BaseResponse = await response.json(); + + if (data.code !== 'COMMON200' || !data.result?.temporaryPassword) { + throw new LoginFailedError(data.message || '비밀번호 재설정에 실패했습니다.'); + } + + return data.result; + } catch (error) { + if (error instanceof LoginFailedError) { + throw error; + } + + if (error instanceof TypeError && error.message.includes('fetch')) { + throw new NetworkError('서버에 연결할 수 없습니다. 네트워크 연결을 확인해주세요.'); + } + + throw new NetworkError('비밀번호 재설정 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.'); + } +} + /** * 관리자 번호 발급 API 호출 (마스터 전용) */ diff --git a/lib/api/master-admin-accounts.ts b/lib/api/master-admin-accounts.ts new file mode 100644 index 0000000..73904f3 --- /dev/null +++ b/lib/api/master-admin-accounts.ts @@ -0,0 +1,168 @@ +/** + * Master 관리자 계정 관리 API (/master/admin-accounts) + */ + +import { + getAllAdmins, + issueAdminNumber, + updateAdminNumber, + resetAdminPasswordByMaster, + LoginFailedError, + NetworkError, + type AdminInfo, + type AdminListResponse, + type AdminNumberIssueRequest, + type AdminNumberResponse, +} from '@/lib/api/admin'; +import { formatSessionDateTime } from '@/lib/master-test-sessions'; + +export { LoginFailedError, NetworkError }; + +/** API 원본 관리자 정보 (GET /api/admin/admin-numbers/admins) */ +export type MasterAdminApiRecord = AdminInfo & { + isActive?: boolean; + createdAt?: string | null; + adminNumberIssuedAt?: string | null; + lastLoginAt?: string | null; +}; + +/** 화면 표시용 관리자 계정 */ +export type MasterAdminAccount = { + id: number; + adminNumber: string; + displayName: string; + email: string; + role: 'ADMIN' | 'MASTER'; + is2faEnabled: boolean; + isActive: boolean; + status: '활성화' | '비활성화'; + lastLogin: string | null; + createdAt: string | null; + passwordStatus: string; +}; + +export type MasterAdminAccountsListResult = { + admins: MasterAdminAccount[]; +}; + +function formatDisplayDate(value: string | null | undefined): string | null { + if (!value) return null; + const date = new Date(value); + if (Number.isNaN(date.getTime())) return value; + return date.toLocaleString('ko-KR', { + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + }); +} + +function mapActiveToStatus(isActive: boolean): '활성화' | '비활성화' { + return isActive ? '활성화' : '비활성화'; +} + +export function mapAdminApiRecordToAccount(record: MasterAdminApiRecord): MasterAdminAccount { + const isActive = record.isActive !== false; + return { + id: record.id, + adminNumber: record.adminNumber, + displayName: record.displayName?.trim() || record.adminNumber, + email: record.email, + role: record.role, + is2faEnabled: record.is2faEnabled, + isActive, + status: mapActiveToStatus(isActive), + lastLogin: record.lastLoginAt + ? formatSessionDateTime(record.lastLoginAt) + : null, + createdAt: formatDisplayDate(record.createdAt ?? null), + passwordStatus: '비밀번호 설정됨', + }; +} + +export function mapAdminListResponse(response: AdminListResponse): MasterAdminAccountsListResult { + const admins = (response.admins as MasterAdminApiRecord[]).map(mapAdminApiRecordToAccount); + return { admins: sortMasterAdminAccounts(admins) }; +} + +/** + * MASTER를 최상단에 두고, MASTER끼리는 adminNumber(숫자 인식) → createdAt 순으로 정렬. + * ADMIN은 API에서 내려온 상대 순서를 유지한다. + */ +export function sortMasterAdminAccounts( + accounts: readonly MasterAdminAccount[] +): MasterAdminAccount[] { + const masters: MasterAdminAccount[] = []; + const admins: MasterAdminAccount[] = []; + + for (const account of accounts) { + if (account.role === 'MASTER') { + masters.push(account); + } else { + admins.push(account); + } + } + + masters.sort((a, b) => { + const byNumber = a.adminNumber.localeCompare(b.adminNumber, undefined, { + numeric: true, + sensitivity: 'base', + }); + if (byNumber !== 0) return byNumber; + + const aCreated = a.createdAt ?? ''; + const bCreated = b.createdAt ?? ''; + return aCreated.localeCompare(bCreated, undefined, { numeric: true }); + }); + + return [...masters, ...admins]; +} + +/** 관리자 목록 조회 */ +export async function fetchMasterAdminAccounts(): Promise { + const response = await getAllAdmins(); + return mapAdminListResponse(response); +} + +/** 관리자 활성/비활성 상태 변경 */ +export async function updateMasterAdminAccountStatus( + account: MasterAdminAccount +): Promise { + const nextActive = !account.isActive; + await updateAdminNumber(account.adminNumber, { + active: nextActive, + }); + return { + ...account, + isActive: nextActive, + status: mapActiveToStatus(nextActive), + }; +} + +/** 신규 관리자 번호 발급 (가입용) */ +export async function issueMasterAdminNumber( + request: AdminNumberIssueRequest = {} +): Promise { + return issueAdminNumber(request); +} + +/** MASTER가 타 관리자 임시 비밀번호 재설정 */ +export async function resetMasterAdminPassword( + account: MasterAdminAccount +): Promise<{ temporaryPassword: string }> { + const result = await resetAdminPasswordByMaster(account.adminNumber); + return { temporaryPassword: result.temporaryPassword }; +} + +/** + * TODO(BE): 관리자 계정 삭제 API 미구현 + */ +export async function deleteMasterAdminAccount( + _account: MasterAdminAccount +): Promise { + throw new LoginFailedError( + '관리자 삭제 API가 아직 제공되지 않습니다. 백엔드 연동 후 호출해 주세요.', + 501 + ); +} diff --git a/lib/master-dashboard-kpi.ts b/lib/master-dashboard-kpi.ts new file mode 100644 index 0000000..c38219b --- /dev/null +++ b/lib/master-dashboard-kpi.ts @@ -0,0 +1,147 @@ +import type { Exam, ExamineeBoardEntry, SystemStatusServiceItem } from "@/lib/api/admin" + +/** 진행 중으로 집계할 시험 상태 (Admin dashboard / test-sessions 와 동일) */ +export const ACTIVE_EXAM_STATES = new Set(["RUNNING", "IN_PROGRESS", "ACTIVE"]) + +/** 오늘 참여로 볼 참가자 상태 */ +const PARTICIPANT_PARTICIPATED_STATES = new Set([ + "ENTRANCE", + "ACTIVE", + "RUNNING", + "IN_PROGRESS", + "STARTED", + "JOINED", +]) + +export type MasterSystemStatusTone = "success" | "warning" | "danger" | "connectionFailed" + +export type MasterSystemStatusSource = + | { type: "fetch_failed" } + | { type: "services"; services: SystemStatusServiceItem[] } + +export type MasterSystemStatusDisplay = { + label: string + valueColor: string + iconColor: string + iconBg: string +} + +export function isActiveExam(exam: Exam): boolean { + return ACTIVE_EXAM_STATES.has((exam.state ?? "").trim().toUpperCase()) +} + +export function countActiveExamSessions(exams: Exam[]): number { + return exams.filter(isActiveExam).length +} + +export function isSameLocalCalendarDay( + iso: string | null | undefined, + ref: Date = new Date() +): boolean { + if (!iso) return false + const d = new Date(iso) + if (Number.isNaN(d.getTime())) return false + return ( + d.getFullYear() === ref.getFullYear() && + d.getMonth() === ref.getMonth() && + d.getDate() === ref.getDate() + ) +} + +/** + * 오늘 참가자 수 — board API 기준 + * - 오늘 제출/채점 활동(submittedAt, evaluatedAt) + * - 진행 중 시험 또는 오늘 시작된 시험에서 입장·응시 중인 참가자 + */ +export function countTodayParticipants( + exams: Exam[], + boards: ExamineeBoardEntry[][] +): number { + const seen = new Set() + + exams.forEach((exam, index) => { + const entries = boards[index] ?? [] + const examActive = isActiveExam(exam) + const examStartsToday = isSameLocalCalendarDay(exam.startsAt) + + for (const entry of entries) { + if ( + isSameLocalCalendarDay(entry.submittedAt) || + isSameLocalCalendarDay(entry.evaluatedAt) + ) { + seen.add(entry.examParticipantId) + continue + } + + if (!examActive && !examStartsToday) continue + + const state = (entry.state ?? "").trim().toUpperCase() + if (PARTICIPANT_PARTICIPATED_STATES.has(state)) { + seen.add(entry.examParticipantId) + continue + } + + if ((entry.tokenUsed ?? 0) > 0) { + seen.add(entry.examParticipantId) + } + } + }) + + return seen.size +} + +const SYSTEM_STATUS_STYLES: Record = { + success: { + label: "운영 중", + valueColor: "#22C55E", + iconColor: "#22C55E", + iconBg: "#F0FDF4", + }, + warning: { + label: "부분 장애", + valueColor: "#D97706", + iconColor: "#D97706", + iconBg: "#FFFBEB", + }, + danger: { + label: "점검 중", + valueColor: "#DC2626", + iconColor: "#DC2626", + iconBg: "#FEF2F2", + }, + connectionFailed: { + label: "연결 실패", + valueColor: "#6B7280", + iconColor: "#6B7280", + iconBg: "#F3F4F6", + }, +} + +/** + * server-status API 결과 → Master KPI 카드 문구 + * - fetch_failed: getSystemStatus() 요청 자체 실패 + * - services: 응답 수신 후 api / database / ai 상태 집계 + */ +export function deriveMasterSystemStatusDisplay( + source: MasterSystemStatusSource +): MasterSystemStatusDisplay { + if (source.type === "fetch_failed") { + return SYSTEM_STATUS_STYLES.connectionFailed + } + + const services = source.services + if (!services.length) { + return SYSTEM_STATUS_STYLES.danger + } + + const statuses = services.map((s) => (s.status ?? "").trim().toUpperCase()) + const upCount = statuses.filter((s) => s === "UP").length + + if (upCount === statuses.length) { + return SYSTEM_STATUS_STYLES.success + } + if (upCount === 0) { + return SYSTEM_STATUS_STYLES.danger + } + return SYSTEM_STATUS_STYLES.warning +} diff --git a/lib/master-problems.ts b/lib/master-problems.ts new file mode 100644 index 0000000..5e37d17 --- /dev/null +++ b/lib/master-problems.ts @@ -0,0 +1,181 @@ +import type { AdminProblem, AdminProblemDetail } from "@/lib/api/admin" + +export type ProblemDifficultyKo = "쉬움" | "중간" | "어려움" + +export type MasterProblemListItem = { + id: number + title: string + titleWithVersion: string + versionLabel: string + difficulty: ProblemDifficultyKo + difficultyRaw: string + tags: string[] + lastUpdatedLabel: string + lastUpdatedIso: string | null + status: string + createdAt: string + searchText: string +} + +export type MasterProblemDetail = MasterProblemListItem & { + contentMd: string + restrictionsInfo: string + usable: boolean +} + +export function mapDifficultyToKo( + difficulty: AdminProblem["difficulty"] | string | null | undefined +): ProblemDifficultyKo { + const normalized = String(difficulty ?? "").toUpperCase() + if (normalized === "MEDIUM") return "중간" + if (normalized === "HARD") return "어려움" + return "쉬움" +} + +export function parseProblemTags(tags: AdminProblem["tags"] | string[] | null | undefined): string[] { + if (tags == null) return [] + if (Array.isArray(tags)) { + return tags.map((t) => String(t).trim()).filter(Boolean) + } + const raw = String(tags).trim() + if (!raw) return [] + try { + const parsed = JSON.parse(raw) as unknown + if (Array.isArray(parsed)) { + return parsed.map((t) => String(t).trim()).filter(Boolean) + } + } catch { + if (raw.includes(",")) { + return raw.split(",").map((t) => t.trim()).filter(Boolean) + } + } + return [raw] +} + +/** 1 → v1.0, "1.0" → v1.0, 이미 v1.0이면 유지 */ +export function formatProblemVersionLabel( + version: number | string | null | undefined +): string { + if (version == null || String(version).trim() === "") return "v1.0" + + const s = String(version).trim() + const numericPart = s.startsWith("v") || s.startsWith("V") ? s.slice(1) : s + const n = Number(numericPart) + + if (Number.isFinite(n)) { + return `v${n.toFixed(1)}` + } + + return s.startsWith("v") || s.startsWith("V") ? s : `v${s}` +} + +export function formatProblemLastUpdated( + updatedAt: string | null | undefined, + createdAt: string | null | undefined +): { label: string; iso: string | null } { + const iso = updatedAt?.trim() || createdAt?.trim() || null + if (!iso) return { label: "-", iso: null } + + const d = new Date(iso) + if (Number.isNaN(d.getTime())) return { label: iso.split("T")[0] ?? "-", iso } + + const now = new Date() + const diffMs = now.getTime() - d.getTime() + const days = Math.floor(diffMs / (1000 * 60 * 60 * 24)) + + if (days < 1) return { label: "오늘", iso } + if (days === 1) return { label: "1일 전", iso } + if (days < 7) return { label: `${days}일 전`, iso } + if (days < 30) { + const weeks = Math.floor(days / 7) + return { label: `${weeks}주 전`, iso } + } + + const y = d.getFullYear() + const m = String(d.getMonth() + 1).padStart(2, "0") + const day = String(d.getDate()).padStart(2, "0") + return { label: `${y}-${m}-${day}`, iso } +} + +function buildRestrictionsInfo(detail: AdminProblemDetail): string { + const parts: string[] = [] + if (detail.limits) { + parts.push(`시간 제한 ${detail.limits.timeMs}ms · 메모리 ${detail.limits.memoryMb}MB`) + } + if (detail.restrictions?.allowedLangs?.length) { + parts.push(`허용 언어: ${detail.restrictions.allowedLangs.join(", ")}`) + } + if (detail.restrictions?.forbiddenApis?.length) { + parts.push(`금지 API: ${detail.restrictions.forbiddenApis.join(", ")}`) + } + if (detail.checker?.type) { + parts.push(`채점 방식: ${detail.checker.type}`) + } + return parts.length > 0 ? parts.join("\n") : "정보 없음" +} + +export function mapAdminProblemToMasterListItem(problem: AdminProblem): MasterProblemListItem { + const tags = parseProblemTags(problem.tags) + const difficulty = mapDifficultyToKo(problem.difficulty) + const versionLabel = formatProblemVersionLabel(problem.version ?? 1) + const { label: lastUpdatedLabel, iso: lastUpdatedIso } = formatProblemLastUpdated( + problem.updatedAt, + problem.createdAt + ) + const searchText = [problem.title, versionLabel, difficulty, ...tags, problem.status] + .join(" ") + .toLowerCase() + + return { + id: problem.id, + title: problem.title, + titleWithVersion: `${problem.title} ${versionLabel}`, + versionLabel, + difficulty, + difficultyRaw: problem.difficulty, + tags, + lastUpdatedLabel, + lastUpdatedIso, + status: problem.status, + createdAt: problem.createdAt, + searchText, + } +} + +export function buildMasterProblemDetailFromApi( + listItem: MasterProblemListItem, + detail: AdminProblemDetail +): MasterProblemDetail { + const versionLabel = formatProblemVersionLabel(detail.version) + const { label: lastUpdatedLabel, iso: lastUpdatedIso } = formatProblemLastUpdated( + detail.updatedAt ?? detail.publishedAt, + detail.createdAt + ) + const tags = parseProblemTags(detail.tags) + + return { + ...listItem, + id: detail.id, + title: detail.title, + titleWithVersion: `${detail.title} ${versionLabel}`, + versionLabel, + difficulty: mapDifficultyToKo(detail.difficulty), + difficultyRaw: detail.difficulty, + tags, + lastUpdatedLabel, + lastUpdatedIso, + status: detail.status, + contentMd: detail.contentMd?.trim() ?? "", + restrictionsInfo: buildRestrictionsInfo(detail), + usable: detail.usable, + } +} + +export function filterMasterProblems( + problems: MasterProblemListItem[], + query: string +): MasterProblemListItem[] { + const q = query.trim().toLowerCase() + if (!q) return problems + return problems.filter((p) => p.searchText.includes(q)) +} diff --git a/lib/master-test-sessions.ts b/lib/master-test-sessions.ts new file mode 100644 index 0000000..993ce67 --- /dev/null +++ b/lib/master-test-sessions.ts @@ -0,0 +1,234 @@ +import type { Exam, ExamineeBoardEntry } from "@/lib/api/admin" + +/** Test Sessions 목록 행 */ +export type TestSessionListItem = { + id: number + sessionId: string + createdBy: string + createdAt: string + /** 필터용: Active | Completed */ + status: string + /** UI 표시용 한글 */ + statusLabel: string + participants: number + sortKey: number + rawState: string + startsAt: string +} + +/** Master Dashboard · Test Sessions 목록 공통 표시 모델 */ +export type MasterRecentSession = { + id: number + sessionId: string + createdAt: string + participants: number + status: string + sortKey: number +} + +export const RECENT_SESSIONS_DISPLAY_LIMIT = 4 + +type ExamWithOptionalCreatedAt = Exam & { createdAt?: string | null } + +/** URL params → examId (유효하지 않으면 null) */ +export function parseExamIdParam(raw: string | undefined | null): number | null { + if (raw == null || String(raw).trim() === "") return null + const n = Number(raw) + if (!Number.isFinite(n) || n <= 0) return null + return Math.floor(n) +} + +/** 정렬: createdAt 우선, 없으면 startsAt */ +export function getExamSortTimestamp(exam: Exam): number { + const extended = exam as ExamWithOptionalCreatedAt + const iso = extended.createdAt?.trim() || exam.startsAt?.trim() || "" + if (!iso) return 0 + const t = new Date(iso).getTime() + return Number.isNaN(t) ? 0 : t +} + +export function sortExamsByCreatedAtDesc(exams: Exam[]): Exam[] { + return [...exams].sort((a, b) => getExamSortTimestamp(b) - getExamSortTimestamp(a)) +} + +export function formatSessionCreatedAt(iso: string | null | undefined): string { + if (!iso) return "-" + const d = new Date(iso) + if (Number.isNaN(d.getTime())) { + return iso.split("T")[0] ?? "-" + } + return `${d.getFullYear()}년 ${d.getMonth() + 1}월 ${d.getDate()}일` +} + +/** 상세 화면용 날짜·시간 */ +export function formatSessionDateTime(iso: string | null | undefined): string { + if (!iso) return "-" + const d = new Date(iso) + if (Number.isNaN(d.getTime())) return iso.replace("T", " ").slice(0, 16) + const y = d.getFullYear() + const m = String(d.getMonth() + 1).padStart(2, "0") + const day = String(d.getDate()).padStart(2, "0") + const h = String(d.getHours()).padStart(2, "0") + const min = String(d.getMinutes()).padStart(2, "0") + return `${y}-${m}-${day} ${h}:${min}` +} + +export function getExamDisplayDate(exam: Exam): string { + const extended = exam as ExamWithOptionalCreatedAt + const iso = extended.createdAt?.trim() || exam.startsAt?.trim() + return formatSessionDateTime(iso) +} + +/** 목록 필터용 Active / Completed */ +export function getTestSessionFilterStatus(state: string | null | undefined): string { + const normalized = (state ?? "").trim().toUpperCase() + if (["RUNNING", "IN_PROGRESS", "ACTIVE"].includes(normalized)) return "Active" + return "Completed" +} + +export function mapExamToTestSession(exam: Exam): TestSessionListItem { + const title = (exam.title ?? "").trim() + return { + id: exam.id, + sessionId: title || `시험 #${exam.id}`, + createdBy: "Admin", + createdAt: formatSessionCreatedAt( + (exam as ExamWithOptionalCreatedAt).createdAt ?? exam.startsAt + ), + status: getTestSessionFilterStatus(exam.state), + statusLabel: getMasterSessionStatusLabel(exam.state), + participants: exam.participantCount ?? 0, + sortKey: getExamSortTimestamp(exam), + rawState: exam.state ?? "", + startsAt: exam.startsAt ?? "", + } +} + +export function mapExamsToTestSessions(exams: Exam[]): TestSessionListItem[] { + return sortExamsByCreatedAtDesc(exams).map(mapExamToTestSession) +} + +/** 세션 종료 여부 (completed / ended / finished 계열) */ +export function isExamSessionEnded(state: string | null | undefined): boolean { + const normalized = (state ?? "").trim().toUpperCase() + return ["ENDED", "COMPLETED", "FINISHED", "CLOSED", "DONE"].includes(normalized) +} + +/** 세션 진행 중 여부 (active / running / in_progress 계열) */ +export function isExamSessionActive(state: string | null | undefined): boolean { + const normalized = (state ?? "").trim().toUpperCase() + return ["RUNNING", "IN_PROGRESS", "ACTIVE"].includes(normalized) +} + +export type ParticipantExamStatusInput = { + submitted?: boolean + submissionStatus?: string | null + submissionStatusLabel?: string + state?: string | null +} + +function isParticipantSubmissionComplete(input: ParticipantExamStatusInput): boolean { + if (input.submitted === true) return true + const label = (input.submissionStatusLabel ?? "").trim() + if (label === "제출됨" || label.startsWith("채점 완료")) return true + const st = (input.submissionStatus ?? "").trim().toUpperCase() + return st === "DONE" +} + +function isParticipantInProgress(input: ParticipantExamStatusInput): boolean { + const label = (input.submissionStatusLabel ?? "").trim() + if (label === "진행 중" || label === "제출·채점 중") return true + const st = (input.state ?? "").trim().toUpperCase() + return st === "ENTRANCE" +} + +/** Master 테스트 세션 상세 — 참가자 응시 상태 */ +export function mapMasterParticipantExamStatus( + examState: string | null | undefined, + input: ParticipantExamStatusInput +): string { + if (isExamSessionEnded(examState)) { + return "종료됨" + } + + if (isExamSessionActive(examState)) { + if (isParticipantSubmissionComplete(input)) return "응시 완료" + if (isParticipantInProgress(input)) return "응시 중" + return "대기 중" + } + + if (isParticipantSubmissionComplete(input)) return "응시 완료" + if (isParticipantInProgress(input)) return "응시 중" + + const sessionLabel = getMasterSessionStatusLabel(examState) + if (sessionLabel === "대기 중") return "대기 중" + + return "-" +} + +export function mapBoardConnectionStatus(state: string | null | undefined): string { + const normalized = (state ?? "").trim().toUpperCase() + if (["ENTRANCE", "ACTIVE", "RUNNING", "IN_PROGRESS", "CONNECTED", "ONLINE", "JOINED", "STARTED"].includes(normalized)) { + return "Connected" + } + if (["PENDING", "WAITING", "IDLE"].includes(normalized)) { + return "Pending" + } + return "Disconnected" +} + +export function mapBoardParticipant(entry: ExamineeBoardEntry) { + return { + id: entry.examParticipantId, + name: entry.name || "-", + phoneNumber: entry.phoneMasked || "-", + connectionStatus: mapBoardConnectionStatus(entry.state), + hasSubmission: entry.submitted === true, + submissionStatusLabel: entry.submitted ? "submitted" : "not_started", + tokenUsage: entry.tokenUsed ?? 0, + } +} + +/** Dashboard / Test Sessions 상태 한글 라벨 */ +export function getMasterSessionStatusLabel(state: string | null | undefined): string { + const normalized = (state ?? "").trim().toUpperCase() + if (["RUNNING", "IN_PROGRESS", "ACTIVE"].includes(normalized)) { + return "진행 중" + } + if (["ENDED", "COMPLETED", "FINISHED", "CLOSED"].includes(normalized)) { + return "완료" + } + if (["WAITING", "PENDING", "SCHEDULED", "DRAFT"].includes(normalized)) { + return "대기 중" + } + return state?.trim() || "-" +} + +export function isMasterSessionInProgress(statusLabel: string): boolean { + return statusLabel === "진행 중" +} + +export function mapExamToMasterRecentSession(exam: Exam): MasterRecentSession { + const item = mapExamToTestSession(exam) + return { + id: item.id, + sessionId: item.sessionId, + createdAt: item.createdAt, + participants: item.participants, + status: item.statusLabel, + sortKey: item.sortKey, + } +} + +export function sortMasterSessionsByCreatedAtDesc( + sessions: MasterRecentSession[] +): MasterRecentSession[] { + return [...sessions].sort((a, b) => b.sortKey - a.sortKey) +} + +export function pickRecentSessions( + exams: Exam[], + limit = RECENT_SESSIONS_DISPLAY_LIMIT +): MasterRecentSession[] { + return sortMasterSessionsByCreatedAtDesc(exams.map(mapExamToMasterRecentSession)).slice(0, limit) +} diff --git a/lib/paths/master-participant-evaluation.ts b/lib/paths/master-participant-evaluation.ts new file mode 100644 index 0000000..efd4818 --- /dev/null +++ b/lib/paths/master-participant-evaluation.ts @@ -0,0 +1,19 @@ +/** + * Master 테스트 세션 — 참가자 평가 상세 URL + * 라우트: app/master/test-sessions/[ID]/participants/[participantId]/page.tsx + */ +export function masterParticipantEvaluationHref(opts: { + examId: string | number + participantId: string | number + participantName?: string +}): string { + const examSeg = String(opts.examId).trim() + const pid = String(opts.participantId).trim() + const path = `/master/test-sessions/${encodeURIComponent(examSeg)}/participants/${encodeURIComponent(pid)}` + if (opts.participantName != null && String(opts.participantName).trim() !== "") { + const q = new URLSearchParams() + q.set("participantName", String(opts.participantName).trim()) + return `${path}?${q.toString()}` + } + return path +} diff --git a/lib/problem-content-md.ts b/lib/problem-content-md.ts new file mode 100644 index 0000000..4755410 --- /dev/null +++ b/lib/problem-content-md.ts @@ -0,0 +1,91 @@ +/** 응시 화면 contentMd(마크다운) → 상세 모달 필드 분리 */ + +export type ParsedProblemContentMd = { + description: string + inputExample: string + outputExample: string + constraints: string +} + +const EMPTY_INPUT = "등록된 예시가 없습니다." +const EMPTY_OUTPUT = "등록된 예시가 없습니다." +const EMPTY_DESCRIPTION = "등록된 설명이 없습니다." + +function extractFirstCodeBlockAfterHeading(contentMd: string, headingRe: RegExp): string { + const headingMatch = headingRe.exec(contentMd) + if (!headingMatch) return "" + + const after = contentMd.slice(headingMatch.index + headingMatch[0].length) + const fenceMatch = after.match(/```[^\n]*\n([\s\S]*?)```/) + return fenceMatch?.[1]?.trim() ?? "" +} + +function extractSectionText(contentMd: string, headingRe: RegExp): string { + const headingMatch = headingRe.exec(contentMd) + if (!headingMatch) return "" + + const start = headingMatch.index + headingMatch[0].length + const rest = contentMd.slice(start) + const nextHeading = rest.search(/\n##\s+/) + const sectionBody = nextHeading >= 0 ? rest.slice(0, nextHeading) : rest + return sectionBody.replace(/```[\s\S]*?```/g, "").trim() +} + +/** + * BOJ/프로젝트 초기 데이터 형식(## 문제, ## 입력, ## 출력, ## 예제 입력 N) 기준 파싱 + */ +export function parseProblemContentMd(contentMd: string | null | undefined): ParsedProblemContentMd { + const raw = (contentMd ?? "").trim() + if (!raw) { + return { + description: EMPTY_DESCRIPTION, + inputExample: EMPTY_INPUT, + outputExample: EMPTY_OUTPUT, + constraints: "정보 없음", + } + } + + const inputExample = + extractFirstCodeBlockAfterHeading(raw, /##\s*예제\s*입력\s*\d*/i) || + extractFirstCodeBlockAfterHeading(raw, /##\s*입력\s*예시/i) || + extractFirstCodeBlockAfterHeading(raw, /##\s*입력\s*예제/i) || + EMPTY_INPUT + + const outputExample = + extractFirstCodeBlockAfterHeading(raw, /##\s*예제\s*출력\s*\d*/i) || + extractFirstCodeBlockAfterHeading(raw, /##\s*출력\s*예시/i) || + extractFirstCodeBlockAfterHeading(raw, /##\s*출력\s*예제/i) || + EMPTY_OUTPUT + + const problemSection = extractSectionText(raw, /##\s*문제\b/i) + const firstSectionEnd = raw.search(/\n##\s+/) + const leading = + firstSectionEnd >= 0 && !/^##\s*문제\b/m.test(raw.slice(0, 20)) + ? raw.slice(0, firstSectionEnd).trim() + : "" + + const description = + problemSection || + leading || + raw.split(/\n##\s+(?:입력|출력|예제)/)[0]?.trim() || + EMPTY_DESCRIPTION + + const inputRules = extractSectionText(raw, /##\s*입력\b/i) + const outputRules = extractSectionText(raw, /##\s*출력\b/i) + const constraintParts = [inputRules, outputRules].filter(Boolean) + const constraints = constraintParts.length > 0 ? constraintParts.join("\n\n") : "정보 없음" + + return { + description, + inputExample: inputExample || EMPTY_INPUT, + outputExample: outputExample || EMPTY_OUTPUT, + constraints, + } +} + +export function formatAssignmentLimits( + limits: { timeMs: number; memoryMb: number } | undefined +): string { + if (!limits) return "" + return `시간 제한 ${limits.timeMs}ms · 메모리 ${limits.memoryMb}MB` +} From f5cbe534adf4f7946322660aa4f14bfaa08d8b3a Mon Sep 17 00:00:00 2001 From: ChanWook Lee Date: Thu, 21 May 2026 17:29:05 +0900 Subject: [PATCH 15/16] =?UTF-8?q?=EB=A7=88=EC=8A=A4=ED=84=B0=20=ED=85=8C?= =?UTF-8?q?=EC=8A=A4=ED=8A=B8=20=EC=84=B8=EC=85=98=20=EB=B0=8F=20=EA=B4=80?= =?UTF-8?q?=EB=A6=AC=EC=9E=90=20=ED=91=9C=EC=8B=9C=20=EB=A1=9C=EC=A7=81=20?= =?UTF-8?q?=EA=B0=9C=EC=84=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- components/admin-sidebar.tsx | 2 +- components/settings-content.tsx | 9 +- components/test-session-details-content.tsx | 3 +- components/users-content.tsx | 117 +++------------ lib/admin-users-participant-status.ts | 150 ++++++++++++++++++++ lib/api/admin.ts | 63 ++++++-- lib/api/master-admin-accounts.ts | 6 +- lib/master-test-sessions.ts | 11 +- 8 files changed, 246 insertions(+), 115 deletions(-) create mode 100644 lib/admin-users-participant-status.ts diff --git a/components/admin-sidebar.tsx b/components/admin-sidebar.tsx index 55aa97b..a85e0cd 100644 --- a/components/admin-sidebar.tsx +++ b/components/admin-sidebar.tsx @@ -74,7 +74,7 @@ export function AdminSidebar() { const router = useRouter() const [showLogoutModal, setShowLogoutModal] = useState(false) const [isLoggingOut, setIsLoggingOut] = useState(false) - const [displayName, setDisplayName] = useState("관리자") + const [displayName, setDisplayName] = useState("알 수 없음") useEffect(() => { let cancelled = false diff --git a/components/settings-content.tsx b/components/settings-content.tsx index 52e1910..913c794 100644 --- a/components/settings-content.tsx +++ b/components/settings-content.tsx @@ -21,6 +21,7 @@ import { LoginFailedError, NetworkError, resolveAdminDisplayNameFromMe, + resolveAdminNumberFromMe, } from "@/lib/api/admin" import { useToast } from "@/hooks/use-toast" import { Lock } from "lucide-react" @@ -54,14 +55,10 @@ export function SettingsContent() { setIsLoading(true); try { const response = await getMe(); - const adminNumber = - response.participant.adminNumber?.trim() || - response.participant.name?.trim() || - ""; setAdminProfile({ name: resolveAdminDisplayNameFromMe(response), email: response.participant.phone || "", - adminNumber, + adminNumber: resolveAdminNumberFromMe(response), }); } catch (error) { if (error instanceof LoginFailedError) { @@ -275,7 +272,7 @@ export function SettingsContent() {
diff --git a/components/test-session-details-content.tsx b/components/test-session-details-content.tsx index 172d941..5d0e9de 100644 --- a/components/test-session-details-content.tsx +++ b/components/test-session-details-content.tsx @@ -136,6 +136,7 @@ export default function TestSessionDetailsContent({ examId, onBack }: TestSessio 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 @@ -245,7 +246,7 @@ export default function TestSessionDetailsContent({ examId, onBack }: TestSessio

생성자

-

Admin

+

{displayCreator}

생성일

diff --git a/components/users-content.tsx b/components/users-content.tsx index fc2f8dd..fd9af2b 100644 --- a/components/users-content.tsx +++ b/components/users-content.tsx @@ -8,102 +8,24 @@ import { type Exam, type ExamineeBoardEntry, } from "@/lib/api/admin" - -type ConnectionStatus = "응시 완료" | "응시 중" | "대기 중" | "종료됨" - -const EXAM_ENDED_STATES = new Set(["ENDED", "COMPLETED", "FINISHED", "CLOSED"]) -type SubmissionStatus = "시작 전" | "진행 중" | "채점 중" | "제출 완료" +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 PARTICIPANT_WAITING_STATES = new Set(["WAITING", "PENDING", "IDLE"]) - -const PARTICIPANT_EXAMINING_STATES = new Set([ - "ACTIVE", - "RUNNING", - "IN_PROGRESS", - "ENTRANCE", - "STARTED", - "JOINED", -]) - -function normalizeParticipantState(state: string | null | undefined): string { - return (state ?? "").trim().toUpperCase() -} - -function isWaitingParticipant(entry: ExamineeBoardEntry): boolean { - const state = normalizeParticipantState(entry.state) - if (PARTICIPANT_WAITING_STATES.has(state)) return true - if (!state && (entry.tokenUsed ?? 0) === 0 && !entry.submitted) return true - return false -} - -function isExamineeInProgress(entry: ExamineeBoardEntry): boolean { - if (entry.submitted) return false - const state = normalizeParticipantState(entry.state) - if (PARTICIPANT_EXAMINING_STATES.has(state)) return true - if ((entry.tokenUsed ?? 0) > 0) return true - if ( - entry.submissionStatus === "QUEUED" || - entry.submissionStatus === "RUNNING" - ) { - return true - } - return false -} - -function normalizeSubmissionStatus(status: string | null | undefined): string { - return (status ?? "").trim().toUpperCase() -} - -function isGradingComplete(entry: ExamineeBoardEntry): boolean { - if (!entry.submitted) return false - const status = normalizeSubmissionStatus(entry.submissionStatus) - if (status === "FAILED") return true - - if (entry.evaluatedAt) return true - if (entry.totalScore != null && entry.totalScore !== undefined) { - const n = Number(entry.totalScore) - if (!Number.isNaN(n)) return true - } - return false -} - -function isExamEnded(exam: Exam): boolean { - const state = (exam.state ?? "").trim().toUpperCase() - if (EXAM_ENDED_STATES.has(state)) return true - if (exam.endsAt) { - const endMs = new Date(exam.endsAt).getTime() - if (!Number.isNaN(endMs) && endMs <= Date.now()) return true - } - return false -} - -function mapConnectionStatus(entry: ExamineeBoardEntry, exam: Exam): ConnectionStatus { - if (isExamEnded(exam)) return "종료됨" - if (entry.submitted) return "응시 완료" - if (isWaitingParticipant(entry)) return "대기 중" - if (isExamineeInProgress(entry)) return "응시 중" - return "대기 중" -} - -function mapSubmissionStatus(entry: ExamineeBoardEntry): SubmissionStatus { - if (!entry.submitted) { - if (isExamineeInProgress(entry)) return "진행 중" - return "시작 전" - } - if (isGradingComplete(entry)) return "제출 완료" - return "채점 중" -} - function resolveExamDisplayLabel(exam: Exam): string { const code = exam.entryCode?.trim() if (code) return code @@ -111,19 +33,20 @@ function resolveExamDisplayLabel(exam: Exam): string { } 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: mapConnectionStatus(entry, exam), - submissionStatus: mapSubmissionStatus(entry), + connectionStatus, + submissionStatus: resolveAdminUsersSubmissionStatus(entry, exam, connectionStatus), tokenUsage: entry.tokenUsed ?? 0, } } -function ConnectionBadge({ status }: { status: ConnectionStatus }) { - const styles: Record = { +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]", @@ -136,12 +59,15 @@ function ConnectionBadge({ status }: { status: ConnectionStatus }) { ) } -function SubmissionBadge({ status }: { status: SubmissionStatus }) { - const styles: Record = { +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} @@ -254,7 +180,10 @@ export function UsersContent() { const displayEnd = Math.min(endIndex, filteredParticipants.length) const completedCount = useMemo( - () => filteredParticipants.filter((p) => p.submissionStatus === "제출 완료").length, + () => + filteredParticipants.filter((p) => + isAdminUsersSubmissionCountedComplete(p.submissionStatus) + ).length, [filteredParticipants] ) diff --git a/lib/admin-users-participant-status.ts b/lib/admin-users-participant-status.ts new file mode 100644 index 0000000..38b8857 --- /dev/null +++ b/lib/admin-users-participant-status.ts @@ -0,0 +1,150 @@ +/** + * 관리자 참가자 목록(/admin/users) — 응시·제출 상태 표시 (FE 보정, API 변경 없음). + */ + +import type { Exam, ExamineeBoardEntry } from "@/lib/api/admin" +import { isExamSessionEnded } from "@/lib/master-test-sessions" + +export type AdminUsersConnectionStatus = "응시 완료" | "응시 중" | "대기 중" | "종료됨" + +export type AdminUsersSubmissionStatus = + | "시작 전" + | "진행 중" + | "채점 중" + | "제출 완료" + | "채점 완료" + | "미제출" + | "제출 실패" + +const PARTICIPANT_WAITING_STATES = new Set(["WAITING", "PENDING", "IDLE"]) + +const PARTICIPANT_EXAMINING_STATES = new Set([ + "ACTIVE", + "RUNNING", + "IN_PROGRESS", + "ENTRANCE", + "STARTED", + "JOINED", +]) + +function normalizeParticipantState(state: string | null | undefined): string { + return (state ?? "").trim().toUpperCase() +} + +function normalizeSubmissionStatus(status: string | null | undefined): string { + return (status ?? "").trim().toUpperCase() +} + +export function isAdminExamEnded(exam: Exam): boolean { + if (isExamSessionEnded(exam.state)) return true + if (exam.endsAt) { + const endMs = new Date(exam.endsAt).getTime() + if (!Number.isNaN(endMs) && endMs <= Date.now()) return true + } + return false +} + +function isWaitingParticipant(entry: ExamineeBoardEntry): boolean { + const state = normalizeParticipantState(entry.state) + if (PARTICIPANT_WAITING_STATES.has(state)) return true + if (!state && (entry.tokenUsed ?? 0) === 0 && !entry.submitted) return true + return false +} + +/** 응시가 진행 중인지 (시험·응시 종료 전용 판단에는 사용하지 않음) */ +export function isExamineeInProgress(entry: ExamineeBoardEntry): boolean { + if (entry.submitted) return false + const state = normalizeParticipantState(entry.state) + if (PARTICIPANT_EXAMINING_STATES.has(state)) return true + if ((entry.tokenUsed ?? 0) > 0) return true + if ( + entry.submissionStatus === "QUEUED" || + entry.submissionStatus === "RUNNING" + ) { + return true + } + return false +} + +export function isSubmissionGradingComplete(entry: ExamineeBoardEntry): boolean { + if (!entry.submitted) return false + const status = normalizeSubmissionStatus(entry.submissionStatus) + if (status === "FAILED") return true + + if (entry.evaluatedAt) return true + if (entry.totalScore != null && entry.totalScore !== undefined) { + const n = Number(entry.totalScore) + if (!Number.isNaN(n)) return true + } + if (status === "DONE") return true + return false +} + +function isSubmissionGradingInFlight(entry: ExamineeBoardEntry): boolean { + const status = normalizeSubmissionStatus(entry.submissionStatus) + return status === "QUEUED" || status === "RUNNING" +} + +export function isExamineeSessionEnded( + connectionStatus: AdminUsersConnectionStatus, + exam: Exam +): boolean { + if (connectionStatus === "종료됨" || connectionStatus === "응시 완료") { + return true + } + return isAdminExamEnded(exam) +} + +/** 응시 상태 (관리자 참가자 목록) */ +export function resolveAdminUsersConnectionStatus( + entry: ExamineeBoardEntry, + exam: Exam +): AdminUsersConnectionStatus { + if (isAdminExamEnded(exam)) return "종료됨" + if (entry.submitted) return "응시 완료" + if (isWaitingParticipant(entry)) return "대기 중" + if (isExamineeInProgress(entry)) return "응시 중" + return "대기 중" +} + +/** + * 제출 상태 — 응시가 종료된 경우 `진행 중`을 쓰지 않음. + */ +export function resolveAdminUsersSubmissionStatus( + entry: ExamineeBoardEntry, + exam: Exam, + connectionStatus: AdminUsersConnectionStatus +): AdminUsersSubmissionStatus { + const examineeEnded = isExamineeSessionEnded(connectionStatus, exam) + + if (!examineeEnded) { + if (!entry.submitted) { + if (isExamineeInProgress(entry)) return "진행 중" + return "시작 전" + } + if (normalizeSubmissionStatus(entry.submissionStatus) === "FAILED") { + return "제출 실패" + } + if (isSubmissionGradingComplete(entry)) return "채점 완료" + if (isSubmissionGradingInFlight(entry)) return "채점 중" + return "제출 완료" + } + + if (!entry.submitted) { + return "미제출" + } + + if (normalizeSubmissionStatus(entry.submissionStatus) === "FAILED") { + return "제출 실패" + } + if (isSubmissionGradingComplete(entry)) return "채점 완료" + if (isSubmissionGradingInFlight(entry)) return "채점 중" + return "제출 완료" +} + +/** 제출·채점이 끝난 것으로 집계할 상태 (통계용) */ +export function isAdminUsersSubmissionCountedComplete( + status: AdminUsersSubmissionStatus +): boolean { + return status === "제출 완료" || status === "채점 완료" +} diff --git a/lib/api/admin.ts b/lib/api/admin.ts index 5247e9b..adf78b8 100644 --- a/lib/api/admin.ts +++ b/lib/api/admin.ts @@ -117,26 +117,65 @@ export interface MeResponse { role: string; participant: { id: number; - name: string; // ADMIN: displayName(또는 fallback), USER: 참가자 이름 + /** ADMIN: resolveDisplayName() 결과, USER: 참가자 이름 */ + name: string; phone: string; // ADMIN: email, USER: 전화번호 adminNumber?: string | null; // ADMIN 전용 + /** ADMIN: DB display_name 원본 (nullable). USER는 null/미포함 */ + displayName?: string | null; }; exam?: null; session?: null; } -/** GET /api/auth/me 응답에서 관리자 표시 이름 해석 (displayName → adminNumber → "관리자") */ +function pickFirstNonEmpty( + ...values: (string | null | undefined)[] +): string | undefined { + for (const value of values) { + const trimmed = value?.trim(); + if (trimmed) return trimmed; + } + return undefined; +} + +/** + * GET /api/auth/me — 관리자 표시 이름 + * 우선순위: displayName → name(관리자번호와 다를 때) → name → adminNumber → "알 수 없음" + */ export function resolveAdminDisplayNameFromMe(response: MeResponse): string { const participant = response.participant; - const adminNumber = - participant.adminNumber?.trim() || - participant.name?.trim() || - ""; - return ( - participant.name?.trim() || - adminNumber || - "관리자" - ); + const displayName = pickFirstNonEmpty(participant.displayName); + const name = pickFirstNonEmpty(participant.name); + const adminNumber = pickFirstNonEmpty(participant.adminNumber); + + if (displayName) return displayName; + if (name && adminNumber && name !== adminNumber) return name; + if (name) return name; + if (adminNumber) return adminNumber; + return "알 수 없음"; +} + +/** GET /api/auth/me — 관리자 번호 필드 (name fallback 사용하지 않음) */ +export function resolveAdminNumberFromMe(response: MeResponse): string { + return pickFirstNonEmpty(response.participant.adminNumber) ?? ""; +} + +/** 관리자 목록/상세 — 표시 이름 (displayName 원본 우선, 번호와 동일한 값은 이름으로 취급하지 않음) */ +export function resolveAdminAccountDisplayName(account: { + displayName?: string | null; + adminNumber: string; +}): string { + const displayName = pickFirstNonEmpty(account.displayName); + const adminNumber = pickFirstNonEmpty(account.adminNumber); + + if (displayName && adminNumber && displayName !== adminNumber) { + return displayName; + } + if (displayName && !adminNumber) { + return displayName; + } + if (adminNumber) return adminNumber; + return "알 수 없음"; } // AdminInfo (AdminListResponse에서 사용) @@ -1190,6 +1229,8 @@ export interface Exam { endsAt: string; // ISO 8601 형식 version: number; createdBy: number; + /** 생성 관리자 표시 이름 (GET /api/admin/exams) */ + creatorName?: string | null; participantCount: number; completedCount: number; entryCode?: string; // 입장 코드 (선택적) diff --git a/lib/api/master-admin-accounts.ts b/lib/api/master-admin-accounts.ts index 73904f3..5a974f8 100644 --- a/lib/api/master-admin-accounts.ts +++ b/lib/api/master-admin-accounts.ts @@ -7,6 +7,7 @@ import { issueAdminNumber, updateAdminNumber, resetAdminPasswordByMaster, + resolveAdminAccountDisplayName, LoginFailedError, NetworkError, type AdminInfo, @@ -67,7 +68,10 @@ export function mapAdminApiRecordToAccount(record: MasterAdminApiRecord): Master return { id: record.id, adminNumber: record.adminNumber, - displayName: record.displayName?.trim() || record.adminNumber, + displayName: resolveAdminAccountDisplayName({ + displayName: record.displayName, + adminNumber: record.adminNumber, + }), email: record.email, role: record.role, is2faEnabled: record.is2faEnabled, diff --git a/lib/master-test-sessions.ts b/lib/master-test-sessions.ts index 993ce67..757097c 100644 --- a/lib/master-test-sessions.ts +++ b/lib/master-test-sessions.ts @@ -80,6 +80,15 @@ export function getExamDisplayDate(exam: Exam): string { } /** 목록 필터용 Active / Completed */ +const UNKNOWN_CREATOR_LABEL = "알 수 없음" + +/** API creatorName → 목록/상세 표시용 생성자 라벨 */ +export function resolveExamCreatorDisplayName(exam: Exam): string { + const name = exam.creatorName?.trim() + if (name) return name + return UNKNOWN_CREATOR_LABEL +} + export function getTestSessionFilterStatus(state: string | null | undefined): string { const normalized = (state ?? "").trim().toUpperCase() if (["RUNNING", "IN_PROGRESS", "ACTIVE"].includes(normalized)) return "Active" @@ -91,7 +100,7 @@ export function mapExamToTestSession(exam: Exam): TestSessionListItem { return { id: exam.id, sessionId: title || `시험 #${exam.id}`, - createdBy: "Admin", + createdBy: resolveExamCreatorDisplayName(exam), createdAt: formatSessionCreatedAt( (exam as ExamWithOptionalCreatedAt).createdAt ?? exam.startsAt ), From f949ae1947a61764062439af36c36cb2a5a2a8ef Mon Sep 17 00:00:00 2001 From: ChanWook Lee Date: Fri, 22 May 2026 05:47:51 +0900 Subject: [PATCH 16/16] =?UTF-8?q?=EC=9A=B4=EC=98=81=20UI=20=EC=A0=95?= =?UTF-8?q?=EB=A6=AC=20=EB=B0=8F=20Copilot=20=EB=A6=AC=EB=B7=B0=20?= =?UTF-8?q?=EB=B0=98=EC=98=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- components/admin-accounts-content.tsx | 148 ++++++++---------- components/entry-codes-content.tsx | 28 +++- components/master-dashboard-content.tsx | 11 +- components/participant-evaluation-content.tsx | 1 + components/test-sessions-content.tsx | 13 +- components/users-content.tsx | 70 ++++++--- lib/api/master-admin-accounts.ts | 45 ++++-- 7 files changed, 197 insertions(+), 119 deletions(-) diff --git a/components/admin-accounts-content.tsx b/components/admin-accounts-content.tsx index e9f7a2a..14da240 100644 --- a/components/admin-accounts-content.tsx +++ b/components/admin-accounts-content.tsx @@ -1,6 +1,6 @@ "use client" -import { useState, useEffect } from "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" @@ -19,7 +19,6 @@ 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 { fetchMasterAdminAccounts, issueMasterAdminNumber, @@ -39,6 +38,14 @@ function displayValue(value: string | null | undefined): string { return value && value.trim() ? value : "-" } +/** 관리자 계정 상태 Badge (활성=초록, 비활성=빨간 계열) */ +function adminAccountStatusBadgeStyle(status: MasterAdminAccount["status"]): CSSProperties { + if (status === "활성화") { + return { backgroundColor: "#DCFCE7", color: "#166534" } + } + return { backgroundColor: "#FEE2E2", color: "#DC2626" } +} + export function AdminAccountsContent() { const [adminUsers, setAdminUsers] = useState([]) const [isLoading, setIsLoading] = useState(true) @@ -438,7 +445,7 @@ export function AdminAccountsContent() { 이메일 {user.email} - - - {user.role === "MASTER" ? "마스터" : "관리자"} - + +
+ + {user.role === "MASTER" ? "마스터" : "관리자"} + +
- - - {user.status} - + +
+ + {user.status} + +
- - {displayValue(user.lastLogin)} - - - + + {displayValue(user.lastLogin)} + + +
+
+
+ ); }) )} @@ -1014,28 +1029,9 @@ export function AdminAccountsContent() {

관리자 번호

-
-

- {selectedAdmin?.adminNumber} -

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

+ {selectedAdmin?.adminNumber} +

역할

@@ -1093,19 +1088,6 @@ export function AdminAccountsContent() {
- - - - {/* Security Settings Section */} -
-

보안 설정

-
-

비밀번호 상태

-

- {selectedAdmin?.passwordStatus ?? "-"} -

-
-
{/* Bottom Action Buttons */} diff --git a/components/entry-codes-content.tsx b/components/entry-codes-content.tsx index 633e6ab..61d4e65 100644 --- a/components/entry-codes-content.tsx +++ b/components/entry-codes-content.tsx @@ -14,6 +14,7 @@ import { import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" 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" @@ -65,6 +66,27 @@ const pickEntryCode = (source: unknown): string | undefined => { 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() { // 시험 생성 모달 상태 @@ -149,7 +171,7 @@ export function EntryCodesContent() { }) ) - setExams(examsWithEntryCodes) + setExams(sortExamsForEntryCodes(examsWithEntryCodes)) // 시험 목록을 새로 가져올 때 페이지를 1로 리셋 setCurrentExamPage(1) } catch (error) { @@ -252,7 +274,7 @@ export function EntryCodesContent() { if (prev === null) { return [createdExamWithEntryCode] } - return [createdExamWithEntryCode, ...prev] + return sortExamsForEntryCodes([createdExamWithEntryCode, ...prev]) }) // 모달 닫기 @@ -471,7 +493,7 @@ export function EntryCodesContent() { } else if (newList.length === 0) { setCurrentExamPage(1) } - return newList + return sortExamsForEntryCodes(newList) }) // 성공 토스트 표시 diff --git a/components/master-dashboard-content.tsx b/components/master-dashboard-content.tsx index 7c981da..301c3a6 100644 --- a/components/master-dashboard-content.tsx +++ b/components/master-dashboard-content.tsx @@ -18,6 +18,7 @@ import { countActiveExamSessions, countTodayParticipants, deriveMasterSystemStatusDisplay, + isActiveExam, type MasterSystemStatusDisplay, } from "@/lib/master-dashboard-kpi" import { @@ -77,9 +78,15 @@ export function MasterDashboardContent({ onNavigate }: DashboardContentProps) { const [examsResult, statusResult] = await Promise.allSettled([ (async () => { const exams = await getExams() - const boards = await Promise.all( - exams.map((e) => getBoard(e.id).catch(() => [])) + // 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(), diff --git a/components/participant-evaluation-content.tsx b/components/participant-evaluation-content.tsx index 6f6f560..e1f31fa 100644 --- a/components/participant-evaluation-content.tsx +++ b/components/participant-evaluation-content.tsx @@ -105,6 +105,7 @@ export function ParticipantEvaluationContent({ setBoardError(null) setBoardEntry(null) setExamTitle(null) + setExamId(null) const directExamId = examIdProp != null && Number.isFinite(examIdProp) && examIdProp > 0 ? examIdProp : null diff --git a/components/test-sessions-content.tsx b/components/test-sessions-content.tsx index c1027f0..fe75f0a 100644 --- a/components/test-sessions-content.tsx +++ b/components/test-sessions-content.tsx @@ -36,6 +36,15 @@ function submissionBadgeClassName(label: string): string { 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 { @@ -338,7 +347,7 @@ export function TestSessionsContent({ onViewDetails }: TestSessionsContentProps) fontFamily: "Inter, system-ui, -apple-system, sans-serif", }} > - {session.status === "Active" ? "진행 중" : session.status === "Completed" ? "완료" : session.statusLabel} + {formatSessionStatusDisplay(session)} - {detailsSession?.status === "Active" ? "진행 중" : detailsSession?.status === "Completed" ? "완료" : detailsSession?.status} + {detailsSession ? formatSessionStatusDisplay(detailsSession) : "–"}
diff --git a/components/users-content.tsx b/components/users-content.tsx index fd9af2b..cc3218b 100644 --- a/components/users-content.tsx +++ b/components/users-content.tsx @@ -73,6 +73,10 @@ function SubmissionBadge({ status }: { status: AdminUsersSubmissionStatus }) { 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 [exams, setExams] = useState([]) const [participants, setParticipants] = useState([]) @@ -245,19 +249,35 @@ export function UsersContent() { )}
-
- 이름 - 시험 - 전화번호 - - 응시 상태 - - - 제출 상태 +
+ + 이름 - - 토큰 사용량 + + 시험 +
+ + 전화번호 + +
+
+ + 응시 상태 + +
+
+ + 제출 상태 + +
+
+ + 토큰 사용량 + +
@@ -279,22 +299,32 @@ export function UsersContent() { visibleParticipants.map((participant, index) => (
- {participant.name} - {participant.examLabel} - {participant.phone} -
+ + {participant.name} + + + {participant.examLabel} + +
+ + {participant.phone} + +
+
-
+
- - {participant.tokenUsage.toLocaleString()} - +
+ + {participant.tokenUsage.toLocaleString()} + +
)) )} diff --git a/lib/api/master-admin-accounts.ts b/lib/api/master-admin-accounts.ts index 5a974f8..eee6bff 100644 --- a/lib/api/master-admin-accounts.ts +++ b/lib/api/master-admin-accounts.ts @@ -38,7 +38,12 @@ export type MasterAdminAccount = { isActive: boolean; status: '활성화' | '비활성화'; lastLogin: string | null; + /** 정렬용 — lastLoginAt ISO의 getTime(), 없거나 invalid면 null */ + lastLoginSortKey: number | null; + /** UI 표시용 (locale 포맷) */ createdAt: string | null; + /** 정렬용 — 원본 ISO의 getTime(), 없거나 invalid면 null */ + createdAtSortKey: number | null; passwordStatus: string; }; @@ -63,6 +68,19 @@ function mapActiveToStatus(isActive: boolean): '활성화' | '비활성화' { return isActive ? '활성화' : '비활성화'; } +function parseIsoSortKey(iso: string | null | undefined): number | null { + if (!iso?.trim()) return null; + const time = new Date(iso).getTime(); + return Number.isNaN(time) ? null : time; +} + +function compareAdminNumber(a: MasterAdminAccount, b: MasterAdminAccount): number { + return a.adminNumber.localeCompare(b.adminNumber, undefined, { + numeric: true, + sensitivity: 'base', + }); +} + export function mapAdminApiRecordToAccount(record: MasterAdminApiRecord): MasterAdminAccount { const isActive = record.isActive !== false; return { @@ -80,7 +98,9 @@ export function mapAdminApiRecordToAccount(record: MasterAdminApiRecord): Master lastLogin: record.lastLoginAt ? formatSessionDateTime(record.lastLoginAt) : null, + lastLoginSortKey: parseIsoSortKey(record.lastLoginAt), createdAt: formatDisplayDate(record.createdAt ?? null), + createdAtSortKey: parseIsoSortKey(record.createdAt), passwordStatus: '비밀번호 설정됨', }; } @@ -91,8 +111,8 @@ export function mapAdminListResponse(response: AdminListResponse): MasterAdminAc } /** - * MASTER를 최상단에 두고, MASTER끼리는 adminNumber(숫자 인식) → createdAt 순으로 정렬. - * ADMIN은 API에서 내려온 상대 순서를 유지한다. + * MASTER를 최상단에 두고, MASTER끼리는 adminNumber → createdAtSortKey 순. + * 일반 관리자(ADMIN)는 lastLoginSortKey 내림차순(최신 로그인 우선), 동률·미로그인은 adminNumber 등 fallback. */ export function sortMasterAdminAccounts( accounts: readonly MasterAdminAccount[] @@ -108,16 +128,23 @@ export function sortMasterAdminAccounts( } } + const lastLoginDescKey = (key: number | null) => key ?? Number.NEGATIVE_INFINITY; + masters.sort((a, b) => { - const byNumber = a.adminNumber.localeCompare(b.adminNumber, undefined, { - numeric: true, - sensitivity: 'base', - }); + const byNumber = compareAdminNumber(a, b); + if (byNumber !== 0) return byNumber; + return (a.createdAtSortKey ?? 0) - (b.createdAtSortKey ?? 0); + }); + + admins.sort((a, b) => { + const byLastLogin = + lastLoginDescKey(b.lastLoginSortKey) - lastLoginDescKey(a.lastLoginSortKey); + if (byLastLogin !== 0) return byLastLogin; + + const byNumber = compareAdminNumber(a, b); if (byNumber !== 0) return byNumber; - const aCreated = a.createdAt ?? ''; - const bCreated = b.createdAt ?? ''; - return aCreated.localeCompare(bCreated, undefined, { numeric: true }); + return (a.createdAtSortKey ?? 0) - (b.createdAtSortKey ?? 0); }); return [...masters, ...admins];