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 && (
void handleSubmit()}
disabled={isSubmitting}
className="h-8 px-4 text-sm font-medium rounded-md bg-[#2563EB] text-white hover:bg-[#1D4ED8] disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
@@ -257,4 +277,4 @@ export function CodeEditorSection({
)
-}
+})
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 */}
- {/* 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}
-
- ))}
-
+ ) : (
+
그룹별 채점 요약 데이터가 없습니다.
+ )}
+
+ )}
- 결과 내보내기 (CSV)
+ 결과보내기 (CSV)
- {/* Toast Notifications */}
{toasts.map((toast) => (
{toast.description}
removeToast(toast.id)}
className="shrink-0 rounded p-0.5 text-[#9CA3AF] transition-colors hover:bg-[#F3F4F6] hover:text-[#6B7280]"
>
diff --git a/components/participant-list-content.tsx b/components/participant-list-content.tsx
index 5c22241..cfc93ef 100644
--- a/components/participant-list-content.tsx
+++ b/components/participant-list-content.tsx
@@ -3,7 +3,7 @@
import { useState, useEffect, useMemo } from "react"
import Link from "next/link"
import { ArrowLeft, Eye, ChevronLeft, ChevronRight } from "lucide-react"
-import { getExams, getBoard, ExamineeBoardEntry } from "@/lib/api/admin"
+import { getExams, getBoard, ExamineeBoardEntry, type Exam } from "@/lib/api/admin"
type TrendLevel = "High" | "Average" | "Low"
@@ -20,6 +20,31 @@ interface ParticipantListContentProps {
entryCode: string
}
+/**
+ * /admin/results/[segment] 세그먼트로 시험을 찾습니다.
+ * - API entryCode와 일치(있을 때)
+ * - 시험 제목과 일치(평가 결과 목록이 title을 URL에 넣는 기존 동작)
+ * - 전부 숫자면 exam.id (직접 링크용)
+ */
+function findExamByResultsSegment(exams: Exam[], segment: string) {
+ const trimmed = segment.trim()
+ if (!trimmed) return undefined
+
+ const byEntryCode = exams.find(
+ (e) => e.entryCode != null && String(e.entryCode).length > 0 && e.entryCode === trimmed
+ )
+ if (byEntryCode) return byEntryCode
+
+ const byTitle = exams.find((e) => e.title === trimmed)
+ if (byTitle) return byTitle
+
+ if (/^\d+$/.test(trimmed)) {
+ return exams.find((e) => String(e.id) === trimmed)
+ }
+
+ return undefined
+}
+
function TrendBadge({ trend }: { trend: TrendLevel }) {
const styles = {
High: "bg-[#DCFCE7] text-[#16A34A]",
@@ -58,7 +83,7 @@ export function ParticipantListContent({ entryCode }: ParticipantListContentProp
try {
// 1) 시험 목록에서 entryCode에 매핑된 examId 찾기
const exams = await getExams()
- const matched = exams.find((e) => e.entryCode === entryCode)
+ const matched = findExamByResultsSegment(exams, entryCode)
if (!matched) {
// entryCode로 직접 매핑이 안 될 때 — 첫 번째 시험 또는 에러
setError("해당 입장 코드에 대한 시험을 찾을 수 없습니다.")
diff --git a/components/results-content.tsx b/components/results-content.tsx
index 687d4c9..60f94a9 100644
--- a/components/results-content.tsx
+++ b/components/results-content.tsx
@@ -40,7 +40,8 @@ export function ResultsContent() {
const exams = await getExams()
const mapped: ResultEntry[] = exams.map((exam: Exam) => ({
id: String(exam.id),
- entryCode: exam.title,
+ // BE ExamResponse에 entryCode가 없을 수 있음 — 목록 표시·상세 URL은 title과 동기화
+ entryCode: exam.entryCode?.trim() ? exam.entryCode : exam.title,
total: exam.participantCount,
completed: exam.completedCount,
}))
diff --git a/components/test-session-details-content.tsx b/components/test-session-details-content.tsx
index b7b4f00..e012121 100644
--- a/components/test-session-details-content.tsx
+++ b/components/test-session-details-content.tsx
@@ -8,7 +8,7 @@ import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import Link from "next/link";
-import { getBoard } from "@/lib/api/admin";
+import { getBoard, formatBoardSubmissionLabelKo, type ExamineeBoardEntry } from "@/lib/api/admin";
// Participant type
type Participant = {
@@ -16,7 +16,10 @@ type Participant = {
name: string
phoneNumber: string
connectionStatus: string
- submissionStatus: string
+ /** 제출 레코드 존재 여부 (요약 통계용) */
+ hasSubmission: boolean
+ /** 제출·채점 상태 표시 문구 */
+ submissionStatusLabel: string
tokenUsage: number
}
@@ -43,16 +46,13 @@ export default function TestSessionDetailsContent({ session, onBack }: TestSessi
setIsLoading(true);
try {
const board = await getBoard(session.id);
- const mapped: Participant[] = board.map((p) => ({
+ const mapped: Participant[] = board.map((p: ExamineeBoardEntry) => ({
id: p.examParticipantId,
name: p.name,
phoneNumber: p.phoneMasked,
connectionStatus: p.state === "ENTRANCE" ? "Connected" : "Pending",
- submissionStatus: p.submitted
- ? "Submitted"
- : p.state === "ENTRANCE"
- ? "In Progress"
- : "Not Started",
+ hasSubmission: p.submitted,
+ submissionStatusLabel: formatBoardSubmissionLabelKo(p),
tokenUsage: p.tokenUsed || 0,
}));
setParticipants(mapped);
@@ -77,7 +77,7 @@ export default function TestSessionDetailsContent({ session, onBack }: TestSessi
const currentParticipants = participants.slice(startIndex, endIndex)
// Calculate summary stats
- const submissions = participants.filter((p) => p.submissionStatus === "Submitted").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)
@@ -97,14 +97,26 @@ export default function TestSessionDetailsContent({ session, onBack }: TestSessi
return 대기 중
}
- const getSubmissionBadge = (status: string) => {
- if (status === "Submitted") {
- return 제출됨
+ const getSubmissionBadge = (label: string) => {
+ if (label === "시작 안 함") {
+ return 시작 안 함
}
- if (status === "In Progress") {
+ if (label === "진행 중") {
return 진행 중
}
- return 시작 안 함
+ if (label === "제출 실패") {
+ return 제출 실패
+ }
+ if (label.startsWith("채점 완료")) {
+ return {label}
+ }
+ if (label === "제출·채점 중") {
+ return {label}
+ }
+ if (label === "제출됨") {
+ return 제출됨
+ }
+ return {label}
}
// Generate page numbers for pagination
@@ -260,7 +272,7 @@ export default function TestSessionDetailsContent({ session, onBack }: TestSessi
{getConnectionBadge(participant.connectionStatus)}
- {getSubmissionBadge(participant.submissionStatus)}
+ {getSubmissionBadge(participant.submissionStatusLabel)}
{participant.tokenUsage.toLocaleString()}
diff --git a/components/test-sessions-content.tsx b/components/test-sessions-content.tsx
index 695a45f..eb20c61 100644
--- a/components/test-sessions-content.tsx
+++ b/components/test-sessions-content.tsx
@@ -18,7 +18,17 @@ import {
import { ScrollArea } from "@/components/ui/scroll-area"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet"
-import { deleteExam, getBoard, getExams, type Exam, type ExamineeBoardEntry } from "@/lib/api/admin";
+import { deleteExam, getBoard, getExams, type Exam, type ExamineeBoardEntry, formatBoardSubmissionLabelKo } from "@/lib/api/admin";
+
+function submissionBadgeClassName(label: string): string {
+ if (label === "시작 안 함") return "bg-gray-100 text-gray-700 hover:bg-gray-100"
+ if (label === "진행 중") return "bg-yellow-100 text-yellow-700 hover:bg-yellow-100"
+ if (label === "제출 실패") return "bg-red-100 text-red-700 hover:bg-red-100"
+ if (label.startsWith("채점 완료")) return "bg-green-100 text-green-700 hover:bg-green-100"
+ if (label === "제출·채점 중") return "bg-amber-100 text-amber-800 hover:bg-amber-100"
+ if (label === "제출됨") return "bg-blue-100 text-blue-700 hover:bg-blue-100"
+ return "bg-gray-100 text-gray-700 hover:bg-gray-100"
+}
export interface TestSession {
id: number
@@ -34,7 +44,10 @@ interface Participant {
name: string
phoneNumber: string
connectionStatus: string
- submissionStatus: string
+ /** 제출 레코드 존재 */
+ hasSubmission: boolean
+ /** 표시용 한글 상태 */
+ submissionStatusLabel: string
tokenUsage: number
}
@@ -89,11 +102,8 @@ export function TestSessionsContent({ onViewDetails }: TestSessionsContentProps)
name: participant.name,
phoneNumber: participant.phoneMasked,
connectionStatus: participant.state === "ENTRANCE" ? "Connected" : "Disconnected",
- submissionStatus: participant.submitted
- ? "Submitted"
- : participant.state === "ENTRANCE"
- ? "In Progress"
- : "Not Started",
+ hasSubmission: participant.submitted,
+ submissionStatusLabel: formatBoardSubmissionLabelKo(participant),
tokenUsage: participant.tokenUsed || 0,
}))
setParticipants(mapped)
@@ -156,7 +166,7 @@ export function TestSessionsContent({ onViewDetails }: TestSessionsContentProps)
const participantEndIndex = Math.min(participantStartIndex + participantPageSize, totalParticipants)
const paginatedParticipants = participants.slice(participantStartIndex, participantEndIndex)
- const submittedCount = participants.filter((p) => p.submissionStatus === "Submitted").length
+ const submittedCount = participants.filter((p) => p.hasSubmission).length
const avgTokenUsage =
participants.length > 0
? Math.round(participants.reduce((sum, p) => sum + p.tokenUsage, 0) / participants.length)
@@ -680,16 +690,10 @@ export function TestSessionsContent({ onViewDetails }: TestSessionsContentProps)
- {participant.submissionStatus === "Submitted" ? "제출됨" : participant.submissionStatus === "In Progress" ? "진행 중" : "시작 안 함"}
+ {participant.submissionStatusLabel}
diff --git a/components/user-test-screen.tsx b/components/user-test-screen.tsx
index 736cf0d..1bdffcc 100644
--- a/components/user-test-screen.tsx
+++ b/components/user-test-screen.tsx
@@ -5,7 +5,7 @@ import { Clock, Coins } from "lucide-react"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button"
import { ProblemSection } from "@/components/problem-section"
-import { CodeEditorSection } from "@/components/code-editor-section"
+import { CodeEditorSection, type CodeEditorSectionHandle } from "@/components/code-editor-section"
import { AiAssistantSidebar } from "@/components/ai-assistant-sidebar"
import { useRouter } from "next/navigation";
import { CheckCircle2 } from "lucide-react";
@@ -85,6 +85,10 @@ export default function UserTestScreen() {
const [isSidebarOpen, setIsSidebarOpen] = useState(false)
const [isSubmitModalOpen, setIsSubmitModalOpen] = useState(false)
+ /** 헤더 제출 확인 모달에서 POST 제출 중 */
+ const [isModalSubmitting, setIsModalSubmitting] = useState(false)
+
+ const codeEditorRef = useRef(null)
// ── 초기 토큰 사용량 로드 (getChatHistory.totalTokens) ──────────────────────
useEffect(() => {
@@ -307,6 +311,7 @@ export default function UserTestScreen() {
{/* Code Editor Section */}
{
- setIsSubmitModalOpen(false);
- setShowFinishedModal(true);
+ disabled={isModalSubmitting}
+ onClick={async () => {
+ setIsModalSubmitting(true)
+ try {
+ const ok = await codeEditorRef.current?.submit()
+ if (ok) {
+ setIsSubmitModalOpen(false)
+ setShowFinishedModal(true)
+ }
+ } finally {
+ setIsModalSubmitting(false)
+ }
}}
>
- 네
+ {isModalSubmitting ? "제출 중…" : "네"}
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() {
router.push("/")}
+ onClick={handleGoHome}
>
홈 화면으로 돌아가기
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({
-
-
+
+
-
성과 수준 (보드 기준)
+
+ 성과 수준 (총점 기준)
+
+ {effectiveTotalScore != null && (
+
+ 기준: 80점 이상 높음 · 50점 이상 보통 · 50점 미만 낮음
+ {detailScoresMeaningful
+ ? " (관리자 제출 상세 API 총점)"
+ : showBoardTotalOnly
+ ? " (관리자 보드 총점)"
+ : ""}
+
+ )}
제출·채점 상태
@@ -403,107 +402,48 @@ export function ParticipantEvaluationContent({
제출한 코드
-
-
-
-
- {isLoadingSubmission ? (
-
불러오는 중…
- ) : submissionDetail?.codeInline != null && submissionDetail.codeInline.trim() !== "" ? (
-
- {submissionDetail.codeInline}
-
- ) : submissionDetail ? (
-
저장된 제출 코드가 없습니다.
- ) : (
-
제출 상세를 불러오면 표시됩니다.
- )}
+
+
-
-
- AI 피드백 (루브릭·턴 평가)
-
-
- {isLoadingSubmission ? (
-
불러오는 중…
- ) : submissionDetail?.rubricJson != null && submissionDetail.rubricJson.trim() !== "" ? (
-
- {formatRubricDisplay(submissionDetail.rubricJson)}
-
- ) : submissionDetail ? (
-
- 채점 루브릭 JSON(scores.rubric_json)이 아직 없습니다.
-
- ) : (
-
제출 상세를 불러오면 표시됩니다.
- )}
-
+
+ {isLoadingSubmission ? (
+
불러오는 중…
+ ) : submissionDetail?.codeInline != null && submissionDetail.codeInline.trim() !== "" ? (
+
+ {submissionDetail.codeInline}
+
+ ) : submissionDetail ? (
+
저장된 제출 코드가 없습니다.
+ ) : (
+
제출 상세를 불러오면 표시됩니다.
+ )}
-
채점·테스트 요약
-
- {!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)}%
-
- )}
-
- ) : (
-
그룹별 채점 요약 데이터가 없습니다.
- )}
-
- )}
+
AI 피드백 (루브릭·턴 평가)
+
+
+
+
+
채점·테스트 요약
+
+ setOpen((v) => !v)}
+ className="flex w-full items-center justify-between px-4 py-3 text-left"
+ >
+ {title}
+ {open ? (
+
+ ) : (
+
+ )}
+
+ {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) => (
+
+ ))}
+
+
+ )
+}
+
+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 (
+
+
+
+
+
+ Turn
+ 점수
+ 비고
+
+
+
+ {rows.map((r) => (
+
+ {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 (
+
+ setOpen((v) => !v)}
+ className="flex w-full items-center justify-between px-4 py-3 text-left text-sm font-medium text-[#374151]"
+ >
+ 7. 원본 JSON 보기
+ {open ? : }
+
+ {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
{
timestamp: string;
@@ -72,13 +66,11 @@ export interface SubmissionDetailResponse {
* HTTP 202 Accepted 반환 (비동기 채점)
*/
export async function submitCode(examId: number, request: SubmitRequest): Promise {
- const url = `${getApiBaseUrl()}/api/exams/${examId}/submissions`;
-
- const response = await fetch(url, {
+ const response = await userApiFetch(`/api/exams/${examId}/submissions`, {
method: 'POST',
- headers: getUserAuthHeaders(),
- body: JSON.stringify(request),
credentials: 'include',
+ headers: USER_JSON_HEADERS,
+ body: JSON.stringify(request),
});
// 202 Accepted도 성공으로 처리
@@ -101,12 +93,10 @@ export async function submitCode(examId: number, request: SubmitRequest): Promis
* GET /api/submissions/{submissionId}
*/
export async function getSubmission(submissionId: number): Promise {
- const url = `${getApiBaseUrl()}/api/submissions/${submissionId}`;
-
- const response = await fetch(url, {
+ const response = await userApiFetch(`/api/submissions/${submissionId}`, {
method: 'GET',
- headers: getUserAuthHeaders(),
credentials: 'include',
+ headers: USER_JSON_HEADERS,
});
const data: BaseResponse = await response.json();
@@ -166,15 +156,13 @@ export function streamScoringResult(
callbacks: ScoringStreamCallbacks
): () => void {
const controller = new AbortController();
- const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8080';
- const url = `${apiBaseUrl}/api/submissions/${submissionId}/stream`;
async function connect() {
try {
- const response = await fetch(url, {
+ const response = await userApiFetch(`/api/submissions/${submissionId}/stream`, {
method: 'GET',
- headers: { Accept: 'text/event-stream' },
credentials: 'include',
+ headers: { Accept: 'text/event-stream' },
signal: controller.signal,
});
diff --git a/lib/api/user-client.ts b/lib/api/user-client.ts
new file mode 100644
index 0000000..e73279c
--- /dev/null
+++ b/lib/api/user-client.ts
@@ -0,0 +1,36 @@
+/**
+ * 응시자(일반 사용자) API용 공통 fetch.
+ * HttpOnly Cookie 인증 — Authorization 헤더 대신 항상 credentials: "include" 로 쿠키 전송.
+ */
+
+export function getUserApiBaseUrl(): string {
+ return process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8080';
+}
+
+export const USER_JSON_HEADERS: HeadersInit = {
+ 'Content-Type': 'application/json',
+};
+
+function resolveUrl(pathOrAbsolute: string): string {
+ if (pathOrAbsolute.startsWith('http://') || pathOrAbsolute.startsWith('https://')) {
+ return pathOrAbsolute;
+ }
+ const base = getUserApiBaseUrl().replace(/\/$/, '');
+ const path = pathOrAbsolute.startsWith('/') ? pathOrAbsolute : `/${pathOrAbsolute}`;
+ return `${base}${path}`;
+}
+
+/**
+ * 사용자 세션 쿠키를 반드시 실어 보내는 fetch.
+ * 호출부에서 credentials 를 덮어써도 최종적으로 include 가 적용된다.
+ */
+export async function userApiFetch(pathOrAbsolute: string, init: RequestInit = {}): Promise {
+ if (typeof fetch === 'undefined') {
+ throw new Error('fetch is not available');
+ }
+ const url = resolveUrl(pathOrAbsolute);
+ return fetch(url, {
+ ...init,
+ credentials: 'include',
+ });
+}
diff --git a/lib/code-quality-metrics-labels.ts b/lib/code-quality-metrics-labels.ts
new file mode 100644
index 0000000..358fe11
--- /dev/null
+++ b/lib/code-quality-metrics-labels.ts
@@ -0,0 +1,83 @@
+/** 코드 품질 메트릭 화면 표시용 라벨 (값/계산 로직과 무관) */
+
+import { asNumber, asString, isRecord } from "@/lib/rubric-json"
+
+const CODE_QUALITY_METRIC_LABELS: Record = {
+ "radon_cc.avg_cc": "평균 순환 복잡도",
+ "radon_cc.max_cc": "최대 순환 복잡도",
+ "radon_cc.junior_grade": "주니어 기준 초과 여부",
+ "reference_radon_cc.avg_cc": "기준 평균 순환 복잡도",
+ "reference_radon_cc.max_cc": "기준 최대 순환 복잡도",
+ "delta_cc_vs_reference.delta_cc_pct": "기준 대비 복잡도 증가율(%)",
+ "delta_cc_vs_reference.v1_avg_cc": "기준 평균 순환 복잡도",
+ "delta_cc_vs_reference.v2_avg_cc": "제출 평균 순환 복잡도",
+ "delta_cc_vs_reference.v1_max_cc": "기준 최대 순환 복잡도",
+ "delta_cc_vs_reference.v2_max_cc": "제출 최대 순환 복잡도",
+ "delta_cc.delta_cc_pct": "이전 코드 대비 복잡도 증가율(%)",
+ "delta_cc.v1_avg_cc": "이전 평균 순환 복잡도",
+ "delta_cc.v2_avg_cc": "현재 평균 순환 복잡도",
+ "delta_cc.v1_max_cc": "이전 최대 순환 복잡도",
+ "delta_cc.v2_max_cc": "현재 최대 순환 복잡도",
+ "v2_metrics.radon_cc.avg_cc": "현재 평균 순환 복잡도",
+ "v2_metrics.radon_cc.max_cc": "현재 최대 순환 복잡도",
+ has_v1: "이전 코드 존재 여부",
+ junior_grade: "주니어 기준 초과 여부",
+ ast_applicable: "AST 패턴 검사 적용 여부",
+ ast_pattern_matched: "AST 패턴 일치 여부",
+}
+
+export function formatCodeQualityMetricLabel(metricKey: string): string {
+ return CODE_QUALITY_METRIC_LABELS[metricKey] ?? metricKey
+}
+
+function formatFunctionComplexityRecord(record: Record): string | null {
+ const name = asString(record.name) ?? asString(record.function)
+ const complexity = asNumber(record.complexity ?? record.cc)
+ if (name && complexity !== null) {
+ return `${name}: 복잡도 ${complexity}`
+ }
+ if (name) return name
+ return null
+}
+
+function parseFunctionComplexityLine(item: unknown): string | null {
+ if (item == null) return null
+
+ if (typeof item === "string") {
+ const trimmed = item.trim()
+ if (!trimmed) return null
+ if (trimmed.startsWith("{")) {
+ try {
+ const parsed: unknown = JSON.parse(trimmed)
+ if (isRecord(parsed)) return formatFunctionComplexityRecord(parsed)
+ } catch {
+ /* 원문 fallback */
+ }
+ }
+ return trimmed
+ }
+
+ if (isRecord(item)) {
+ return formatFunctionComplexityRecord(item)
+ }
+
+ return String(item)
+}
+
+/** functions 배열을 사람이 읽기 쉬운 줄 목록으로 변환 (중복 제거) */
+export function collectFunctionComplexityDisplayLines(...sources: unknown[]): string[] {
+ const seen = new Set()
+ const lines: string[] = []
+
+ for (const source of sources) {
+ if (!Array.isArray(source)) continue
+ for (const item of source) {
+ const line = parseFunctionComplexityLine(item)
+ if (!line || seen.has(line)) continue
+ seen.add(line)
+ lines.push(line)
+ }
+ }
+
+ return lines
+}
diff --git a/lib/paths/admin-participant-evaluation.ts b/lib/paths/admin-participant-evaluation.ts
new file mode 100644
index 0000000..b9ce540
--- /dev/null
+++ b/lib/paths/admin-participant-evaluation.ts
@@ -0,0 +1,34 @@
+/**
+ * 관리자 평가 결과 — 참가자 상세 화면 URL
+ * 라우트: app/admin/results/[entryCode]/[participantId]/page.tsx
+ *
+ * 첫 경로 세그먼트는 participant-list-content 의 findExamByResultsSegment 와 동일하게
+ * entryCode · 시험 제목 · 또는 숫자 exam id 를 사용할 수 있습니다.
+ */
+export type AdminParticipantEvaluationFrom = "results" | "analytics" | "master"
+
+export function adminParticipantEvaluationHref(opts: {
+ resultsSegment: string | number
+ participantId: string | number
+ from: AdminParticipantEvaluationFrom
+ participantName?: string
+ /** from === "master" 일 때 뒤로가기용 */
+ sessionId?: string | number
+}): string {
+ const seg = String(opts.resultsSegment).trim()
+ const pid = String(opts.participantId)
+ const path = `/admin/results/${encodeURIComponent(seg)}/${encodeURIComponent(pid)}`
+ const q = new URLSearchParams()
+ q.set("from", opts.from)
+ if (opts.participantName != null && String(opts.participantName).trim() !== "") {
+ q.set("participantName", String(opts.participantName).trim())
+ }
+ if (opts.from === "results") {
+ q.set("entryCode", seg)
+ }
+ if (opts.from === "master" && opts.sessionId != null && String(opts.sessionId) !== "") {
+ q.set("sessionId", String(opts.sessionId))
+ }
+ const qs = q.toString()
+ return qs ? `${path}?${qs}` : path
+}
diff --git a/lib/performance-level.ts b/lib/performance-level.ts
new file mode 100644
index 0000000..8b15dee
--- /dev/null
+++ b/lib/performance-level.ts
@@ -0,0 +1,43 @@
+/** 보드·상세 화면 공통 — 총점 기준 성과 수준 (80 / 50 구간) */
+export type BoardPerformanceLevel = "high" | "medium" | "low" | "unscored"
+
+export interface BoardPerformanceLevelDisplay {
+ level: BoardPerformanceLevel
+ label: string
+ badgeClass: string
+}
+
+const THRESHOLD_HIGH = 80
+const THRESHOLD_MEDIUM = 50
+
+export function resolveBoardPerformanceLevel(
+ totalScore: number | null | undefined
+): BoardPerformanceLevelDisplay {
+ if (totalScore === null || totalScore === undefined || Number.isNaN(Number(totalScore))) {
+ return {
+ level: "unscored",
+ label: "미채점",
+ badgeClass: "bg-[#F3F4F6] text-[#6B7280]",
+ }
+ }
+ const n = Number(totalScore)
+ if (n >= THRESHOLD_HIGH) {
+ return {
+ level: "high",
+ label: "높음",
+ badgeClass: "bg-[#DCFCE7] text-[#16A34A]",
+ }
+ }
+ if (n >= THRESHOLD_MEDIUM) {
+ return {
+ level: "medium",
+ label: "보통",
+ badgeClass: "bg-[#FEF3C7] text-[#D97706]",
+ }
+ }
+ return {
+ level: "low",
+ label: "낮음",
+ badgeClass: "bg-[#FEE2E2] text-[#DC2626]",
+ }
+}
diff --git a/lib/rubric-json.ts b/lib/rubric-json.ts
new file mode 100644
index 0000000..03b3ca2
--- /dev/null
+++ b/lib/rubric-json.ts
@@ -0,0 +1,219 @@
+/** scores.rubric_json 파싱·접근 유틸 (관리자 평가 리포트용) */
+
+export type RubricJsonRecord = Record
+
+export type ParseRubricJsonResult =
+ | { ok: true; data: RubricJsonRecord; raw: string }
+ | { ok: false; raw: string; error?: string }
+
+export function parseRubricJson(
+ input: string | RubricJsonRecord | null | undefined
+): ParseRubricJsonResult | null {
+ if (input == null) return null
+ if (typeof input === "object" && !Array.isArray(input)) {
+ return { ok: true, data: input as RubricJsonRecord, raw: JSON.stringify(input, null, 2) }
+ }
+ const raw = String(input).trim()
+ if (!raw) return null
+ try {
+ const parsed: unknown = JSON.parse(raw)
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
+ return { ok: true, data: parsed as RubricJsonRecord, raw }
+ }
+ return { ok: false, raw, error: "object가 아님" }
+ } catch (e) {
+ return { ok: false, raw, error: e instanceof Error ? e.message : "parse 실패" }
+ }
+}
+
+export function isRecord(v: unknown): v is RubricJsonRecord {
+ return v != null && typeof v === "object" && !Array.isArray(v)
+}
+
+export function hasPresentValue(v: unknown): boolean {
+ if (v === null || v === undefined) return false
+ if (typeof v === "string") return v.trim().length > 0
+ if (typeof v === "number") return !Number.isNaN(v)
+ if (Array.isArray(v)) return v.length > 0
+ if (isRecord(v)) return Object.keys(v).length > 0
+ return true
+}
+
+export function asNumber(v: unknown): number | null {
+ if (v === null || v === undefined || v === "") return null
+ const n = Number(v)
+ return Number.isFinite(n) ? n : null
+}
+
+export function asString(v: unknown): string | null {
+ if (v === null || v === undefined) return null
+ if (typeof v === "string") {
+ const t = v.trim()
+ return t.length > 0 ? t : null
+ }
+ if (typeof v === "number" || typeof v === "boolean") return String(v)
+ return null
+}
+
+export function asStringArray(v: unknown): string[] {
+ if (!Array.isArray(v)) return []
+ return v
+ .map((item) => {
+ if (typeof item === "string") return item.trim()
+ if (item != null && typeof item === "object") return JSON.stringify(item)
+ return item != null ? String(item) : ""
+ })
+ .filter((s) => s.length > 0)
+}
+
+export function asRecordArray(v: unknown): RubricJsonRecord[] {
+ if (!Array.isArray(v)) return []
+ return v.filter(isRecord)
+}
+
+/** rubric 최상위 또는 중첩에서 숫자 점수 조회 */
+export function pickScore(data: RubricJsonRecord, ...keys: string[]): number | null {
+ for (const key of keys) {
+ const n = asNumber(data[key])
+ if (n !== null) return n
+ }
+ return null
+}
+
+export function pickNestedNumber(obj: unknown, ...path: string[]): number | null {
+ let cur: unknown = obj
+ for (const key of path) {
+ if (!isRecord(cur)) return null
+ cur = cur[key]
+ }
+ return asNumber(cur)
+}
+
+export function pickNestedString(obj: unknown, ...path: string[]): string | null {
+ let cur: unknown = obj
+ for (const key of path) {
+ if (!isRecord(cur)) return null
+ cur = cur[key]
+ }
+ return asString(cur)
+}
+
+export interface HolisticAnalysisSection {
+ title: string
+ body: string
+}
+
+const HOLISTIC_SECTION_PATTERN =
+ /\[(합의 요약|종합 분석|점수 근거|R4 맥락 유지)\]/g
+
+export function splitHolisticFlowAnalysis(text: string): HolisticAnalysisSection[] {
+ const trimmed = text.trim()
+ if (!trimmed) return []
+
+ const markers: { index: number; title: string }[] = []
+ let match: RegExpExecArray | null
+ const re = new RegExp(HOLISTIC_SECTION_PATTERN.source, "g")
+ while ((match = re.exec(trimmed)) !== null) {
+ markers.push({ index: match.index, title: match[1] })
+ }
+
+ if (markers.length === 0) {
+ return [{ title: "종합 분석", body: trimmed }]
+ }
+
+ const sections: HolisticAnalysisSection[] = []
+ for (let i = 0; i < markers.length; i++) {
+ const start = markers[i].index
+ const headerEnd = start + markers[i].title.length + 2
+ const end = i + 1 < markers.length ? markers[i + 1].index : trimmed.length
+ const body = trimmed.slice(headerEnd, end).trim()
+ if (body) sections.push({ title: markers[i].title, body })
+ }
+ return sections
+}
+
+export function collectDebateEntries(data: RubricJsonRecord): RubricJsonRecord[] {
+ for (const key of ["debate_log", "debate_rebuttals", "debate_initial_opinions"] as const) {
+ const arr = asRecordArray(data[key])
+ if (arr.length > 0) return arr
+ }
+ return []
+}
+
+export function isVerdictDebateEntry(entry: RubricJsonRecord): boolean {
+ return asString(entry.agent)?.toLowerCase() === "verdict"
+}
+
+/** debate 항목의 라운드 번호 (데이터에 있는 값만, 1 이상 정수) */
+export function pickDebateRoundNumber(entry: RubricJsonRecord): number | null {
+ const raw = entry.round ?? entry.round_number ?? entry.roundNumber
+ const n = asNumber(raw)
+ if (n === null || n <= 0) return null
+ return Math.trunc(n)
+}
+
+export interface GroupedDebateEntries {
+ /** 데이터에 실제 존재하는 라운드 번호 (오름차순, 고정 개수 없음) */
+ roundNumbers: number[]
+ byRound: Map
+ verdicts: RubricJsonRecord[]
+}
+
+export function groupDebateEntriesByRound(entries: RubricJsonRecord[]): GroupedDebateEntries {
+ const verdicts = entries.filter(isVerdictDebateEntry)
+ const opinions = entries.filter((e) => !isVerdictDebateEntry(e))
+ const byRound = new Map()
+
+ for (const entry of opinions) {
+ const round = pickDebateRoundNumber(entry)
+ if (round === null) continue
+ const list = byRound.get(round) ?? []
+ list.push(entry)
+ byRound.set(round, list)
+ }
+
+ const roundNumbers = Array.from(byRound.keys()).sort((a, b) => a - b)
+
+ return { roundNumbers, byRound, verdicts }
+}
+
+export function rubricHasStructuredFields(data: RubricJsonRecord): boolean {
+ if (asString(data.grade)) return true
+ if (pickScore(data, "total_score", "totalScore") !== null) return true
+ if (pickScore(data, "prompt_score", "promptScore") !== null) return true
+ if (
+ pickScore(
+ data,
+ "correctness_score",
+ "code_correctness_score",
+ "performance_score",
+ "code_performance_score"
+ ) !== null
+ ) {
+ return true
+ }
+ if (pickScore(data, "holistic_flow_score") !== null) return true
+ if (isRecord(data.weights) && Object.keys(data.weights).length > 0) return true
+ if (asString(data.holistic_flow_analysis)) return true
+ if (isRecord(data.code_eval_report) || isRecord(data.codeEvalReport)) return true
+ if (collectDebateEntries(data).length > 0) return true
+ if (isRecord(data.turn_scores) || isRecord(data.turnScores)) return true
+ if (isRecord(data.code_quality_metrics) || isRecord(data.codeQualityMetrics)) return true
+ return false
+}
+
+export function formatWeightLabel(value: unknown, label: string): string | null {
+ const n = asNumber(value)
+ if (n === null) return null
+ const pct = n <= 1 ? n * 100 : n
+ return `${label}: ${pct.toFixed(0)}%`
+}
+
+export function formatRubricJsonPretty(data: RubricJsonRecord | string): string {
+ if (typeof data === "string") return data
+ try {
+ return JSON.stringify(data, null, 2)
+ } catch {
+ return String(data)
+ }
+}
From c7c3e8d9c0711cc53da56d66e4780f21ccd02986 Mon Sep 17 00:00:00 2001
From: ChanWook Lee
Date: Mon, 18 May 2026 01:07:19 +0900
Subject: [PATCH 10/16] fix: resolve copilot review issues and improve runtime
safety
---
app/admin/results/[entryCode]/page.tsx | 8 ++++-
components/participant-evaluation-content.tsx | 32 +++++++++++--------
.../participant-evaluation-rubric-report.tsx | 3 +-
components/results-content.tsx | 2 +-
lib/rubric-json.ts | 8 ++++-
5 files changed, 36 insertions(+), 17 deletions(-)
diff --git a/app/admin/results/[entryCode]/page.tsx b/app/admin/results/[entryCode]/page.tsx
index 691018c..b143653 100644
--- a/app/admin/results/[entryCode]/page.tsx
+++ b/app/admin/results/[entryCode]/page.tsx
@@ -12,7 +12,13 @@ export default async function ResultParticipantsPage({
}: ResultParticipantsPageProps) {
const { entryCode: rawEntryCode } = await params;
const safe = rawEntryCode ?? "";
- const decodedEntryCode = decodeURIComponent(safe);
+ let decodedEntryCode = safe;
+
+ try {
+ decodedEntryCode = decodeURIComponent(safe);
+ } catch {
+ decodedEntryCode = safe;
+ }
return ;
}
diff --git a/components/participant-evaluation-content.tsx b/components/participant-evaluation-content.tsx
index 045a745..a4b2d60 100644
--- a/components/participant-evaluation-content.tsx
+++ b/components/participant-evaluation-content.tsx
@@ -1,6 +1,7 @@
"use client"
import { useState, useEffect, useMemo } from "react"
+import type { MouseEvent } from "react"
import { ArrowLeft, User, Code, CheckCircle, X } from "lucide-react"
import { useRouter } from "next/navigation"
import {
@@ -66,6 +67,11 @@ function formatScore(n: number | null | undefined): string {
return `${Number(n).toFixed(1)}`
}
+const escapeCsv = (value: unknown) => {
+ const str = String(value ?? "")
+ return `"${str.replace(/"/g, '""')}"`
+}
+
export function ParticipantEvaluationContent({
entryCode,
participantName: participantNameProp,
@@ -204,18 +210,18 @@ export function ParticipantEvaluationContent({
const handleExport = () => {
const header = "Field,Value"
const rows = [
- `Name,${displayName}`,
- `EntryCodeSegment,${entryCode}`,
- `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 ?? ""}`,
- `CorrectnessScore,${scoreFromDetail?.correctness ?? ""}`,
- `TotalScore,${scoreFromDetail?.total ?? boardEntry?.totalScore ?? ""}`,
+ `Name,${escapeCsv(displayName)}`,
+ `EntryCodeSegment,${escapeCsv(entryCode)}`,
+ `ExamParticipantId,${escapeCsv(participantId)}`,
+ `ExamId,${escapeCsv(examId ?? "")}`,
+ `SubmissionId,${escapeCsv(submissionId ?? "")}`,
+ `HasSubmissionCode,${escapeCsv(submissionDetail?.codeInline?.trim() ? "yes" : "no")}`,
+ `HasRubricJson,${escapeCsv(submissionDetail?.rubricJson?.trim() ? "yes" : "no")}`,
+ `BoardStatus,${escapeCsv(submissionStatusLabel ?? "")}`,
+ `PromptScore,${escapeCsv(scoreFromDetail?.prompt ?? "")}`,
+ `PerfScore,${escapeCsv(scoreFromDetail?.perf ?? "")}`,
+ `CorrectnessScore,${escapeCsv(scoreFromDetail?.correctness ?? "")}`,
+ `TotalScore,${escapeCsv(scoreFromDetail?.total ?? boardEntry?.totalScore ?? "")}`,
]
const csvContent = [header, ...rows].join("\n")
const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" })
@@ -230,7 +236,7 @@ export function ParticipantEvaluationContent({
showToast("보내기 완료", "participant-evaluation.csv")
}
- const handleBackClick = (e: React.MouseEvent) => {
+ const handleBackClick = (e: MouseEvent) => {
e.preventDefault()
if (onBack) onBack()
else router.back()
diff --git a/components/participant-evaluation-rubric-report.tsx b/components/participant-evaluation-rubric-report.tsx
index 6b14b05..162f6f6 100644
--- a/components/participant-evaluation-rubric-report.tsx
+++ b/components/participant-evaluation-rubric-report.tsx
@@ -1,6 +1,7 @@
"use client"
import { useMemo, useState } from "react"
+import type { ReactNode } from "react"
import { ChevronDown, ChevronRight, Info } from "lucide-react"
import {
parseRubricJson,
@@ -34,7 +35,7 @@ function Section({
defaultOpen = false,
}: {
title: string
- children: React.ReactNode
+ children: ReactNode
defaultOpen?: boolean
}) {
const [open, setOpen] = useState(defaultOpen)
diff --git a/components/results-content.tsx b/components/results-content.tsx
index 60f94a9..9b85c17 100644
--- a/components/results-content.tsx
+++ b/components/results-content.tsx
@@ -41,7 +41,7 @@ export function ResultsContent() {
const mapped: ResultEntry[] = exams.map((exam: Exam) => ({
id: String(exam.id),
// BE ExamResponse에 entryCode가 없을 수 있음 — 목록 표시·상세 URL은 title과 동기화
- entryCode: exam.entryCode?.trim() ? exam.entryCode : exam.title,
+ entryCode: exam.entryCode?.trim() || exam.title,
total: exam.participantCount,
completed: exam.completedCount,
}))
diff --git a/lib/rubric-json.ts b/lib/rubric-json.ts
index 03b3ca2..47d1c3f 100644
--- a/lib/rubric-json.ts
+++ b/lib/rubric-json.ts
@@ -11,7 +11,13 @@ export function parseRubricJson(
): ParseRubricJsonResult | null {
if (input == null) return null
if (typeof input === "object" && !Array.isArray(input)) {
- return { ok: true, data: input as RubricJsonRecord, raw: JSON.stringify(input, null, 2) }
+ let raw: string
+ try {
+ raw = JSON.stringify(input, null, 2)
+ } catch {
+ raw = String(input)
+ }
+ return { ok: true, data: input as RubricJsonRecord, raw }
}
const raw = String(input).trim()
if (!raw) return null
From 6a8e63033429b7b1330412e950da3c837eb7eaf8 Mon Sep 17 00:00:00 2001
From: ChanWook Lee
Date: Mon, 18 May 2026 02:07:04 +0900
Subject: [PATCH 11/16] fix: resolve copilot review issues for session recovery
flow
---
app/test/page.tsx | 25 +++++++++++++++---
components/problem-section.tsx | 7 ++++-
lib/api/exams.ts | 48 +++++++++++++++++++++++++++-------
3 files changed, 66 insertions(+), 14 deletions(-)
diff --git a/app/test/page.tsx b/app/test/page.tsx
index e37e962..67bd0df 100644
--- a/app/test/page.tsx
+++ b/app/test/page.tsx
@@ -15,6 +15,18 @@ export default function TestPage() {
useEffect(() => {
let cancelled = false;
+ let redirectTimeoutId: ReturnType | undefined;
+
+ const scheduleRedirect = () => {
+ if (redirectTimeoutId !== undefined) {
+ clearTimeout(redirectTimeoutId);
+ }
+ redirectTimeoutId = setTimeout(() => {
+ if (!cancelled) {
+ router.replace("/");
+ }
+ }, 1200);
+ };
const restoreSession = async () => {
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
@@ -24,6 +36,8 @@ export default function TestPage() {
// 이 경우 즉시 entry로 튕기지 말고 짧게 재시도 후 실패 시에만 리다이렉트한다.
const maxAttempts = 6; // 총 5~6초 내 재시도
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
+ if (cancelled) return;
+
try {
const currentExamId = useExamSessionStore.getState().examId;
const activeSession = currentExamId
@@ -42,17 +56,18 @@ export default function TestPage() {
if (attempt === maxAttempts) {
setRestoreError("활성 시험 세션이 없습니다. 다시 입장해주세요.");
- setTimeout(() => router.replace("/"), 1200);
+ scheduleRedirect();
return;
}
await sleep(300 + attempt * 250);
+ if (cancelled) return;
} catch (error: any) {
if (cancelled) return;
// 인증 실패(쿠키 누락/만료)는 재시도해도 의미 없으므로 즉시 리다이렉트
if (error?.status === 401) {
setRestoreError("인증이 필요합니다. 다시 입장해주세요.");
- setTimeout(() => router.replace("/"), 1200);
+ scheduleRedirect();
return;
}
@@ -60,11 +75,12 @@ export default function TestPage() {
if (attempt === maxAttempts) {
setRestoreError("세션 복구에 실패했습니다. 다시 입장해주세요.");
- setTimeout(() => router.replace("/"), 1200);
+ scheduleRedirect();
return;
}
await sleep(300 + attempt * 250);
+ if (cancelled) return;
}
}
};
@@ -74,6 +90,9 @@ export default function TestPage() {
});
return () => {
cancelled = true;
+ if (redirectTimeoutId !== undefined) {
+ clearTimeout(redirectTimeoutId);
+ }
};
}, [router]);
diff --git a/components/problem-section.tsx b/components/problem-section.tsx
index 6d77b6b..bdde756 100644
--- a/components/problem-section.tsx
+++ b/components/problem-section.tsx
@@ -20,7 +20,11 @@ export function ProblemSection({ examId }: ProblemSectionProps) {
const status = err?.status
const code = err?.code
const msg = String(err?.apiMessage || err?.message || "")
- return status === 400 && (code === "PROBLEM005" || msg.includes("배정된 문제가 없습니다"))
+ return (
+ status === 400 ||
+ code === "PROBLEM005" ||
+ msg.includes("배정된 문제가 없습니다")
+ )
}
const load = async () => {
@@ -52,6 +56,7 @@ export function ProblemSection({ examId }: ProblemSectionProps) {
console.warn(`[ProblemSection] assignment not ready (attempt ${attempt}/${maxAttempts}), retrying...`, err)
}
await sleep(1000)
+ if (cancelled) return
continue
}
diff --git a/lib/api/exams.ts b/lib/api/exams.ts
index 1b98034..075ddde 100644
--- a/lib/api/exams.ts
+++ b/lib/api/exams.ts
@@ -240,23 +240,37 @@ export async function getActiveSessionByExam(examId: number): Promise;
- try {
- data = await response.json();
- } catch {
- throw new Error('활성 세션 응답을 파싱할 수 없습니다.');
+ if (response.status === 404) {
+ return null;
+ }
+
+ let data: BaseResponse | undefined;
+ const text = await response.text();
+ if (text) {
+ try {
+ data = JSON.parse(text) as BaseResponse;
+ } catch {
+ if (!response.ok) {
+ const err: any = new Error('활성 세션 응답을 파싱할 수 없습니다.');
+ err.status = response.status;
+ throw err;
+ }
+ throw new Error('활성 세션 응답을 파싱할 수 없습니다.');
+ }
}
if (!response.ok) {
- if (response.status === 404 || data.code === 'EXAM404_5') {
+ if (data?.code === 'EXAM404_5') {
return null;
}
- 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;
}
- if (data.code !== 'COMMON200' || !data.result) {
+ if (!data || data.code !== 'COMMON200' || !data.result) {
return null;
}
@@ -300,8 +314,22 @@ export async function getAssignment(examId: number): Promise
credentials: 'include',
});
- const data: BaseResponse = await response.json();
- if (!response.ok || data.code !== 'COMMON200' || !data.result) {
+ let data: BaseResponse | undefined;
+ const text = await response.text();
+ if (text) {
+ try {
+ data = JSON.parse(text) as BaseResponse;
+ } catch {
+ if (!response.ok) {
+ const err: any = new Error('문제 조회 응답을 파싱할 수 없습니다.');
+ err.status = response.status;
+ throw err;
+ }
+ throw new Error('문제 조회 응답을 파싱할 수 없습니다.');
+ }
+ }
+
+ if (!response.ok || !data || data.code !== 'COMMON200' || !data.result) {
const err: any = new Error(data?.message || '문제 조회에 실패했습니다.');
err.status = response.status;
err.code = data?.code;
From da92bbb9ee1b7e57e1ea8d57f8a308c22565b4bd Mon Sep 17 00:00:00 2001
From: ChanWook Lee
Date: Mon, 18 May 2026 16:26:53 +0900
Subject: [PATCH 12/16] =?UTF-8?q?=EC=84=B8=EC=85=98=20=EB=B3=B5=EA=B5=AC?=
=?UTF-8?q?=20participantId=20=EA=B5=AC=EC=A1=B0=20=EB=B6=84=EB=A6=AC=20?=
=?UTF-8?q?=EB=B0=8F=20AI=20Assistant=20=EC=88=98=EC=A0=95?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
app/test/page.tsx | 4 +++-
components/code-editor-section.tsx | 14 +-------------
components/login-card.tsx | 1 +
lib/api/auth.ts | 4 +---
lib/api/exams.ts | 2 ++
lib/stores/exam-session-store.ts | 14 ++++++++++++--
6 files changed, 20 insertions(+), 19 deletions(-)
diff --git a/app/test/page.tsx b/app/test/page.tsx
index e37e962..1e42744 100644
--- a/app/test/page.tsx
+++ b/app/test/page.tsx
@@ -32,9 +32,11 @@ export default function TestPage() {
if (cancelled) return;
if (activeSession) {
+ const current = useExamSessionStore.getState();
useExamSessionStore.setState({
examId: activeSession.examId,
- participantId: activeSession.examParticipantId,
+ participantId: activeSession.participantId ?? current.participantId,
+ examParticipantId: activeSession.examParticipantId,
tokenLimit: activeSession.tokenLimit,
});
return;
diff --git a/components/code-editor-section.tsx b/components/code-editor-section.tsx
index 050e69d..7cd4c92 100644
--- a/components/code-editor-section.tsx
+++ b/components/code-editor-section.tsx
@@ -184,7 +184,7 @@ export const CodeEditorSection = forwardRef
Code Editor
-
+
@@ -196,18 +196,6 @@ export const CodeEditorSection = forwardRefJavaScript
-
- {/* 제출 버튼 — isReadOnly일 때 숨김 */}
- {!isReadOnly && examId && (
- void handleSubmit()}
- disabled={isSubmitting}
- className="h-8 px-4 text-sm font-medium rounded-md bg-[#2563EB] text-white hover:bg-[#1D4ED8] disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
- >
- {isSubmitting ? "제출 중…" : "코드 제출"}
-
- )}
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}
-
-
-
-
-
제출 상태
-
- {participant.status}
-
-
-
-
-
+
@@ -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() {
- 결과 내보내기 (CSV)
+ 결과보내기 (CSV)
- {/* 메트릭 카드 — 점수는 채점 완료 후 집계됨 */}
-
-
-
-
+
+
+
+
- {/* 점수 미집계 안내 */}
+ {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}
removeToast(toast.id)}
className="shrink-0 rounded p-0.5 text-[#9CA3AF] transition-colors hover:bg-[#F3F4F6] hover:text-[#6B7280]"
>
diff --git a/components/dashboard-content.tsx b/components/dashboard-content.tsx
index e986c7a..5286682 100644
--- a/components/dashboard-content.tsx
+++ b/components/dashboard-content.tsx
@@ -4,6 +4,7 @@ import { useState, useEffect } from "react"
import Link from "next/link"
import { Users, CheckCircle, Play, Plus, BarChart3, ArrowRight } from "lucide-react"
import { getExams, getBoard } from "@/lib/api/admin"
+import { computeSessionAnalytics } from "@/lib/admin-board-analytics"
// Sample recent activity data (정적 - 활동 로그 API 미지원)
const recentActivity = [
@@ -48,6 +49,7 @@ export function DashboardContent() {
const [totalParticipants, setTotalParticipants] = useState(null)
const [completedCount, setCompletedCount] = useState(null)
const [runningExams, setRunningExams] = useState(null)
+ const [avgPromptScore, setAvgPromptScore] = useState(null)
const [isLoading, setIsLoading] = useState(true)
useEffect(() => {
@@ -66,8 +68,10 @@ export function DashboardContent() {
const allParticipants = boards.flat()
setTotalParticipants(allParticipants.length)
setCompletedCount(allParticipants.filter((p) => p.submitted).length)
+ setAvgPromptScore(computeSessionAnalytics(allParticipants).avgPrompt)
} catch (e) {
console.error("Failed to load dashboard stats", e)
+ setAvgPromptScore(null)
} finally {
setIsLoading(false)
}
@@ -78,6 +82,8 @@ export function DashboardContent() {
const displayValue = (val: number | null) =>
isLoading ? "..." : val !== null ? val.toLocaleString() : "–"
+ const displayAvgPromptScore = isLoading ? "–" : (avgPromptScore ?? "–")
+
return (
{/* Section 2: Top Header Bar */}
@@ -117,7 +123,7 @@ export function DashboardContent() {
- {/* Average Prompt Score - no API available */}
+ {/* Average Prompt Score */}
@@ -125,8 +131,8 @@ export function DashboardContent() {
평균 프롬프트 점수
-
–
-
채점 완료 후 집계
+
{displayAvgPromptScore}
+
채점 완료 후 집계 (전체 세션)
{/* Active Test Sessions */}
diff --git a/components/participant-evaluation-content.tsx b/components/participant-evaluation-content.tsx
index a4b2d60..f6aa05d 100644
--- a/components/participant-evaluation-content.tsx
+++ b/components/participant-evaluation-content.tsx
@@ -13,6 +13,11 @@ import {
type ExamineeBoardEntry,
type AdminSubmissionDetailResponse,
} from "@/lib/api/admin"
+import {
+ buildKeyValueCsvBody,
+ buildParticipantEvaluationCsvFilename,
+ downloadUtf8Csv,
+} from "@/lib/admin-board-csv-export"
import { resolveBoardPerformanceLevel } from "@/lib/performance-level"
import { ParticipantEvaluationTestSummary } from "@/components/participant-evaluation-test-summary"
import { ParticipantEvaluationRubricReport } from "@/components/participant-evaluation-rubric-report"
@@ -67,11 +72,6 @@ function formatScore(n: number | null | undefined): string {
return `${Number(n).toFixed(1)}`
}
-const escapeCsv = (value: unknown) => {
- const str = String(value ?? "")
- return `"${str.replace(/"/g, '""')}"`
-}
-
export function ParticipantEvaluationContent({
entryCode,
participantName: participantNameProp,
@@ -208,32 +208,49 @@ export function ParticipantEvaluationContent({
}
const handleExport = () => {
- const header = "Field,Value"
- const rows = [
- `Name,${escapeCsv(displayName)}`,
- `EntryCodeSegment,${escapeCsv(entryCode)}`,
- `ExamParticipantId,${escapeCsv(participantId)}`,
- `ExamId,${escapeCsv(examId ?? "")}`,
- `SubmissionId,${escapeCsv(submissionId ?? "")}`,
- `HasSubmissionCode,${escapeCsv(submissionDetail?.codeInline?.trim() ? "yes" : "no")}`,
- `HasRubricJson,${escapeCsv(submissionDetail?.rubricJson?.trim() ? "yes" : "no")}`,
- `BoardStatus,${escapeCsv(submissionStatusLabel ?? "")}`,
- `PromptScore,${escapeCsv(scoreFromDetail?.prompt ?? "")}`,
- `PerfScore,${escapeCsv(scoreFromDetail?.perf ?? "")}`,
- `CorrectnessScore,${escapeCsv(scoreFromDetail?.correctness ?? "")}`,
- `TotalScore,${escapeCsv(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")
+ try {
+ const examLabel = entryCode.trim() || "session"
+ const csvBody = buildKeyValueCsvBody([
+ { label: "이름", value: displayName },
+ { label: "시험", value: examLabel, excelTextValue: true },
+ { label: "제출 상태", value: submissionStatusLabel ?? "–" },
+ {
+ label: "총점",
+ value: effectiveTotalScore != null ? formatScore(effectiveTotalScore) : "–",
+ },
+ {
+ label: "프롬프트 점수",
+ value: detailScoresMeaningful ? formatScore(scoreFromDetail?.prompt ?? null) : "–",
+ },
+ {
+ label: "성능 점수",
+ value: detailScoresMeaningful ? formatScore(scoreFromDetail?.perf ?? null) : "–",
+ },
+ {
+ label: "정답률 점수",
+ value: detailScoresMeaningful ? formatScore(scoreFromDetail?.correctness ?? null) : "–",
+ },
+ {
+ label: "코드 LOC",
+ value:
+ submissionDetail?.metrics?.loc != null
+ ? String(submissionDetail.metrics.loc)
+ : "–",
+ },
+ { label: "제출 언어", value: submissionDetail?.lang ?? "–" },
+ { label: "참가자 ID", value: participantId },
+ ...(submissionId != null
+ ? [{ label: "제출 ID", value: String(submissionId) }]
+ : []),
+ ])
+
+ const filename = buildParticipantEvaluationCsvFilename(examLabel, displayName)
+ downloadUtf8Csv(filename, csvBody)
+ showToast("보내기 완료", filename)
+ } catch (e) {
+ console.error("[ParticipantEvaluation] CSV export failed", e)
+ showToast("보내기 실패", "CSV 파일을 생성하지 못했습니다.")
+ }
}
const handleBackClick = (e: MouseEvent) => {
@@ -255,7 +272,7 @@ export function ParticipantEvaluationContent({
-
+
-
+
cleanupAiFeedbackText(text), [text])
return (
- {text}
+
+ {displayText}
+
)
}
@@ -183,10 +187,11 @@ const R4_CONTEXT_SECTION_TITLE = "R4 맥락 유지"
const R4_CONTEXT_SECTION_HINT = "대화 흐름과 문맥 유지 능력 평가"
function HolisticSubsectionTitle({ title }: { title: string }) {
- const showHint = title === R4_CONTEXT_SECTION_TITLE
+ const displayTitle = useMemo(() => cleanupAiFeedbackText(title), [title])
+ const showHint = displayTitle === R4_CONTEXT_SECTION_TITLE
return (
-
{title}
+
{displayTitle}
{showHint && (
{summary ? (
-
{summary}
+
+ {cleanupAiFeedbackText(summary)}
+
) : (
제공되지 않음
)}
@@ -371,7 +378,7 @@ function DebateVerdictCard({ entry }: { entry: RubricJsonRecord }) {
{keyPoints.map((p, i) => (
- {p}
+ {cleanupAiFeedbackText(p)}
))}
@@ -448,7 +455,9 @@ function TurnScoresSection({ data }: { data: RubricJsonRecord }) {
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) ?? "")
+ if (hasPresentValue(val.feedback)) {
+ parts.push(cleanupAiFeedbackText(asString(val.feedback) ?? ""))
+ }
rows.push({
turn,
score: ts !== null ? formatScoreDisplay(ts) : "–",
diff --git a/components/results-content.tsx b/components/results-content.tsx
index 9b85c17..5076622 100644
--- a/components/results-content.tsx
+++ b/components/results-content.tsx
@@ -2,8 +2,13 @@
import { useState, useEffect } from "react"
import Link from "next/link"
-import { Search, Download, Eye, X, CheckCircle, ChevronLeft, ChevronRight } from "lucide-react"
-import { getExams, type Exam } from "@/lib/api/admin"
+import { Search, Download, Eye, X, CheckCircle, ChevronLeft, ChevronRight, Loader2 } from "lucide-react"
+import { getExams, getBoard, type Exam } from "@/lib/api/admin"
+import {
+ buildBoardParticipantsCsvBody,
+ downloadUtf8Csv,
+ sanitizeCsvFilenameSegment,
+} from "@/lib/admin-board-csv-export"
interface ResultEntry {
id: string
@@ -23,6 +28,7 @@ export function ResultsContent() {
const [isLoading, setIsLoading] = useState(true)
const [searchQuery, setSearchQuery] = useState("")
const [toasts, setToasts] = useState
([])
+ const [downloadingExamId, setDownloadingExamId] = useState(null)
const [currentPage, setCurrentPage] = useState(1)
const pageSize = 10
@@ -61,11 +67,32 @@ export function ResultsContent() {
setToasts((prev) => prev.filter((t) => t.id !== id))
}
- const handleDownload = (entryCode: string) => {
- showToast(
- "CSV 다운로드 준비 중",
- "현재 해당 기능을 서버에서 준비 중입니다. 조만간 업데이트될 예정입니다.",
- )
+ const handleDownload = async (result: ResultEntry) => {
+ const examId = Number.parseInt(result.id, 10)
+ if (Number.isNaN(examId)) {
+ showToast("다운로드 실패", "유효하지 않은 시험 ID입니다.")
+ return
+ }
+
+ setDownloadingExamId(result.id)
+ try {
+ const board = await getBoard(examId)
+ const csvBody = buildBoardParticipantsCsvBody(
+ board.map((entry) => ({ entry, examLabel: result.entryCode })),
+ { includeScores: true }
+ )
+ const filename = `results-${sanitizeCsvFilenameSegment(result.entryCode)}.csv`
+ downloadUtf8Csv(filename, csvBody)
+ showToast("다운로드 완료", `${result.entryCode} 세션 결과가 CSV로 저장되었습니다.`)
+ } catch (error) {
+ console.error(`[Results] CSV download failed for examId=${examId}`, error)
+ showToast(
+ "다운로드 실패",
+ "참가자 결과를 불러오지 못했습니다. 잠시 후 다시 시도해 주세요."
+ )
+ } finally {
+ setDownloadingExamId(null)
+ }
}
const filteredResults = results.filter((result) => result.entryCode.toLowerCase().includes(searchQuery.toLowerCase()))
@@ -211,15 +238,21 @@ export function ResultsContent() {
{/* Right Side - Action Buttons */}
handleDownload(result.entryCode)}
- className="flex items-center gap-2 px-4 py-2 rounded-lg bg-[#3B82F6] text-white hover:bg-[#2563EB] transition-colors"
+ type="button"
+ onClick={() => handleDownload(result)}
+ disabled={downloadingExamId === result.id}
+ className="flex items-center gap-2 rounded-lg bg-[#3B82F6] px-4 py-2 text-white transition-colors hover:bg-[#2563EB] disabled:cursor-not-allowed disabled:opacity-60"
style={{
fontSize: "14px",
fontWeight: 500,
}}
>
-
- 다운로드
+ {downloadingExamId === result.id ? (
+
+ ) : (
+
+ )}
+ {downloadingExamId === result.id ? "다운로드 중…" : "다운로드"}
= {
+ 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 */}
+
+
+ setSelectedExamId(e.target.value)}
+ disabled={isLoadingExams}
+ className="appearance-none rounded-lg border border-[#E5E5E5] bg-white py-2 pl-4 pr-10 text-sm text-[#1A1A1A] outline-none transition-colors focus:border-[#3B82F6] focus:ring-1 focus:ring-[#3B82F6] disabled:opacity-50"
+ >
+ 모든 세션
+ {exams.map((exam) => (
+
+ {resolveExamDisplayLabel(exam)}
+
+ ))}
+
+
+
+
+
+
+ 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 && (
+
+ )}
+
- {/* 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}명`}
setCurrentPage((p) => Math.max(1, p - 1))}
disabled={currentPage === 1}
className="flex h-8 items-center gap-1 rounded-md border border-[#E5E7EB] bg-white px-2 text-sm text-[#6B7280] transition-colors hover:bg-[#E0EDFF] disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-white"
@@ -234,6 +393,7 @@ export function UsersContent() {
{Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
setCurrentPage(page)}
className={`flex h-8 w-8 items-center justify-center rounded-md border text-sm transition-colors ${
page === currentPage
@@ -246,6 +406,7 @@ export function UsersContent() {
))}
setCurrentPage((p) => Math.min(totalPages, p + 1))}
disabled={currentPage === totalPages || totalPages === 0}
className="flex h-8 items-center gap-1 rounded-md border border-[#E5E7EB] bg-white px-2 text-sm text-[#6B7280] transition-colors hover:bg-[#E0EDFF] disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-white"
diff --git a/lib/admin-board-analytics.ts b/lib/admin-board-analytics.ts
new file mode 100644
index 0000000..87593d2
--- /dev/null
+++ b/lib/admin-board-analytics.ts
@@ -0,0 +1,111 @@
+import type { ExamineeBoardEntry } from "@/lib/api/admin"
+
+function normalizeSubmissionStatus(status: string | null | undefined): string {
+ return (status ?? "").trim().toUpperCase()
+}
+
+function toNumericScore(value: number | null | undefined): number | null {
+ if (value === null || value === undefined) return null
+ const n = Number(value)
+ return Number.isNaN(n) ? null : n
+}
+
+/** 보드 API 기준 제출 완료 (submissions 행 존재) */
+export function isExamineeBoardSubmitted(entry: ExamineeBoardEntry): boolean {
+ return entry.submitted === true
+}
+
+/**
+ * 채점 완료 — Score 행(evaluatedAt·totalScore) 또는 제출 실패 등
+ * users-content 의 isGradingComplete 와 동일 규칙
+ */
+export function isExamineeBoardGradingComplete(entry: ExamineeBoardEntry): boolean {
+ if (!isExamineeBoardSubmitted(entry)) return false
+ const status = normalizeSubmissionStatus(entry.submissionStatus)
+ if (status === "FAILED") return true
+
+ if (entry.evaluatedAt) return true
+ const total = toNumericScore(entry.totalScore)
+ if (total !== null) return true
+ return false
+}
+
+/** 평균·등급 집계에 포함할 채점 완료 행 (실제 점수 데이터 존재) */
+export function isExamineeBoardScoreGraded(entry: ExamineeBoardEntry): boolean {
+ if (!isExamineeBoardSubmitted(entry)) return false
+ if (entry.evaluatedAt) return true
+ if (toNumericScore(entry.totalScore) !== null) return true
+ if (
+ toNumericScore(entry.promptScore) !== null ||
+ toNumericScore(entry.perfScore) !== null ||
+ toNumericScore(entry.correctnessScore) !== null
+ ) {
+ return true
+ }
+ return false
+}
+
+/** 종합 점수 우선, 없으면 존재하는 항목 점수의 산술 평균 (0~100 스케일) */
+export function computeParticipantCompositeScore(entry: ExamineeBoardEntry): number | null {
+ if (!isExamineeBoardScoreGraded(entry)) return null
+
+ const total = toNumericScore(entry.totalScore)
+ if (total !== null) return total
+
+ const parts: number[] = []
+ const prompt = toNumericScore(entry.promptScore)
+ const perf = toNumericScore(entry.perfScore)
+ const correctness = toNumericScore(entry.correctnessScore)
+ if (prompt !== null) parts.push(prompt)
+ if (perf !== null) parts.push(perf)
+ if (correctness !== null) parts.push(correctness)
+ if (parts.length === 0) return null
+ return parts.reduce((sum, v) => sum + v, 0) / parts.length
+}
+
+export function computeLetterGrade(score: number | null): string {
+ if (score === null) return "–"
+ if (score >= 90) return "A"
+ if (score >= 80) return "B"
+ if (score >= 70) return "C"
+ if (score >= 60) return "D"
+ return "F"
+}
+
+export function computeParticipantLetterGrade(entry: ExamineeBoardEntry): string {
+ return computeLetterGrade(computeParticipantCompositeScore(entry))
+}
+
+function averageOf(values: number[]): string {
+ if (values.length === 0) return "–"
+ const avg = values.reduce((sum, v) => sum + v, 0) / values.length
+ return avg.toFixed(1)
+}
+
+export interface SessionAnalyticsSummary {
+ avgPrompt: string
+ avgPerformance: string
+ avgCorrectness: string
+ cumulativeUsers: number
+}
+
+export function computeSessionAnalytics(entries: ExamineeBoardEntry[]): SessionAnalyticsSummary {
+ const graded = entries.filter(isExamineeBoardScoreGraded)
+
+ const promptValues = graded
+ .map((e) => toNumericScore(e.promptScore))
+ .filter((n): n is number => n !== null)
+ const perfValues = graded
+ .map((e) => toNumericScore(e.perfScore))
+ .filter((n): n is number => n !== null)
+ const correctnessValues = graded
+ .map((e) => toNumericScore(e.correctnessScore))
+ .filter((n): n is number => n !== null)
+
+ return {
+ avgPrompt: averageOf(promptValues),
+ avgPerformance: averageOf(perfValues),
+ avgCorrectness: averageOf(correctnessValues),
+ cumulativeUsers: entries.length,
+ }
+}
diff --git a/lib/admin-board-csv-export.ts b/lib/admin-board-csv-export.ts
new file mode 100644
index 0000000..e5ee1d5
--- /dev/null
+++ b/lib/admin-board-csv-export.ts
@@ -0,0 +1,113 @@
+import {
+ formatBoardSubmissionLabelKo,
+ type ExamineeBoardEntry,
+} from "@/lib/api/admin"
+import { computeParticipantLetterGrade } from "@/lib/admin-board-analytics"
+
+export interface BoardCsvRowInput {
+ entry: ExamineeBoardEntry
+ examLabel: string
+}
+
+function toNumericScore(value: number | null | undefined): number | null {
+ if (value === null || value === undefined) return null
+ const n = Number(value)
+ return Number.isNaN(n) ? null : n
+}
+
+/** 채점·미채점 구분 — 없으면 "–", 0점은 "0.0" */
+export function formatCsvScoreDisplay(value: number | null | undefined): string {
+ const n = toNumericScore(value)
+ if (n === null) return "–"
+ return n.toFixed(1)
+}
+
+/** Excel에서 앞자리 0·한글 깨짐 방지용 텍스트 셀 */
+export function formatCsvExcelTextCell(value: string): string {
+ return `="${String(value).replace(/"/g, '""')}"`
+}
+
+/** RFC 4180 — 쉼표·줄바꿈·따옴표 포함 값 이스케이프 */
+export function escapeCsvCell(value: string): string {
+ const str = String(value ?? "")
+ if (/[",\r\n]/.test(str)) {
+ return `"${str.replace(/"/g, '""')}"`
+ }
+ return str
+}
+
+export interface KeyValueCsvRow {
+ label: string
+ value: string
+ /** 값을 Excel 문자열 수식(="051700")으로보낼지 */
+ excelTextValue?: boolean
+}
+
+/** 항목/값 2열 key-value CSV 본문 (BOM은 downloadUtf8Csv에서 추가) */
+export function buildKeyValueCsvBody(rows: KeyValueCsvRow[]): string {
+ const lines = [
+ `${escapeCsvCell("항목")},${escapeCsvCell("값")}`,
+ ...rows.map(({ label, value, excelTextValue }) => {
+ const valueCell = excelTextValue ? formatCsvExcelTextCell(value) : escapeCsvCell(value)
+ return `${escapeCsvCell(label)},${valueCell}`
+ }),
+ ]
+ return lines.join("\n")
+}
+
+export function buildParticipantEvaluationCsvFilename(
+ examLabel: string,
+ participantName: string
+): string {
+ const examSeg = sanitizeCsvFilenameSegment(examLabel)
+ const nameSeg = sanitizeCsvFilenameSegment(participantName)
+ return `participant-evaluation-${examSeg}-${nameSeg}.csv`
+}
+
+export function sanitizeCsvFilenameSegment(name: string): string {
+ const sanitized = name.replace(/[<>:"/\\|?*\u0000-\u001f]/g, "_").trim()
+ return sanitized.length > 0 ? sanitized : "session"
+}
+
+export function buildBoardParticipantsCsvBody(
+ rows: BoardCsvRowInput[],
+ options?: { includeScores?: boolean }
+): string {
+ const includeScores = options?.includeScores ?? false
+ const header = includeScores
+ ? "이름,시험,제출상태,등급,총점,프롬프트 점수,성능 점수,정답률 점수"
+ : "이름,시험,제출상태,등급"
+
+ const lines = rows.map(({ entry, examLabel }) => {
+ const grade = computeParticipantLetterGrade(entry)
+ const status = formatBoardSubmissionLabelKo(entry)
+ const examCell = formatCsvExcelTextCell(examLabel)
+ const name = entry.name || "–"
+
+ const cells = [name, examCell, status, grade]
+ if (includeScores) {
+ cells.push(
+ formatCsvScoreDisplay(entry.totalScore),
+ formatCsvScoreDisplay(entry.promptScore),
+ formatCsvScoreDisplay(entry.perfScore),
+ formatCsvScoreDisplay(entry.correctnessScore)
+ )
+ }
+ return cells.join(",")
+ })
+
+ return `${header}\n${lines.join("\n")}`
+}
+
+export function downloadUtf8Csv(filename: string, csvBody: string): void {
+ const csvContent = "\uFEFF" + csvBody
+ 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 = filename
+ document.body.appendChild(link)
+ link.click()
+ document.body.removeChild(link)
+ URL.revokeObjectURL(url)
+}
diff --git a/lib/api/admin.ts b/lib/api/admin.ts
index fa56274..2ad1e70 100644
--- a/lib/api/admin.ts
+++ b/lib/api/admin.ts
@@ -1732,6 +1732,12 @@ export interface ExamineeBoardEntry {
submissionId?: number | null;
/** QUEUED | RUNNING | DONE | FAILED */
submissionStatus?: string | null;
+ /** scores.prompt_score (Score 행 없으면 null) */
+ promptScore?: number | null;
+ /** scores.perf_score (Score 행 없으면 null) */
+ perfScore?: number | null;
+ /** scores.correctness_score (Score 행 없으면 null) */
+ correctnessScore?: number | null;
/** scores.total_score (없으면 null) */
totalScore?: number | null;
/** 제출 생성 시각 (ISO 문자열) */
@@ -1780,6 +1786,17 @@ export interface AdminMetrics {
};
}
+export interface SystemStatusServiceItem {
+ key: string;
+ name: string;
+ status: string;
+ latencyMs: number | null;
+}
+
+export interface SystemStatusResponse {
+ services: SystemStatusServiceItem[];
+}
+
// ─── 시험 연장 ─────────────────────────────────────────────────────────────────
/**
@@ -1849,6 +1866,27 @@ export async function deleteEntryCode(code: string): Promise {
// ─── 시험 지표·보드 ────────────────────────────────────────────────────────────
+/**
+ * 관리자 시스템 상태 조회 API 호출
+ * GET /api/admin/system-status
+ */
+export async function getSystemStatus(): Promise {
+ const apiBaseUrl = getApiBaseUrl();
+ const url = `${apiBaseUrl}/api/admin/system-status`;
+
+ 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;
+}
+
/**
* 시험 실시간 지표 조회 API 호출
* GET /api/admin/metrics?examId={}
diff --git a/lib/utils/cleanup-ai-feedback.ts b/lib/utils/cleanup-ai-feedback.ts
new file mode 100644
index 0000000..6b15ab7
--- /dev/null
+++ b/lib/utils/cleanup-ai-feedback.ts
@@ -0,0 +1,43 @@
+/**
+ * AI 피드백·루브릭 텍스트 표시용 — Markdown 장식만 제거하고 plain text 유지
+ * (react-markdown 미사용, inline code 백틱은 유지)
+ */
+
+const INLINE_CODE_PATTERN = /(`[^`\n]+`)/g
+
+function cleanupMarkdownProse(prose: string): string {
+ let s = prose
+
+ // # heading (줄 시작)
+ s = s.replace(/^#{1,6}\s+/gm, "")
+
+ // **bold** / __bold__ (여러 겹이면 반복 제거)
+ let prev = ""
+ while (prev !== s) {
+ prev = s
+ s = s.replace(/\*\*([^*\n]+)\*\*/g, "$1")
+ s = s.replace(/__([^_\n]+)__/g, "$1")
+ }
+
+ // 닫히지 않은 잔여 마커
+ s = s.replace(/\*\*/g, "")
+ s = s.replace(/__/g, "")
+
+ return s
+}
+
+/**
+ * AI 피드백 문자열에서 bold/heading 등 Markdown 흔적만 제거합니다.
+ * inline code (`...`)·줄바꿈·번호 목록은 유지합니다.
+ */
+export function cleanupAiFeedbackText(text: string): string {
+ if (!text) return text
+
+ const parts = text.split(INLINE_CODE_PATTERN)
+ return parts
+ .map((part, index) => {
+ if (index % 2 === 1) return part
+ return cleanupMarkdownProse(part)
+ })
+ .join("")
+}
From 7a293967d7b1819b5b1bbb5262a6f71eb5c3b8fd Mon Sep 17 00:00:00 2001
From: ChanWook Lee
Date: Thu, 21 May 2026 04:36:26 +0900
Subject: [PATCH 14/16] =?UTF-8?q?=EA=B4=80=EB=A6=AC=EC=9E=90=20=EA=B3=84?=
=?UTF-8?q?=EC=A0=95=20=EA=B4=80=EB=A6=AC=20=ED=99=94=EB=A9=B4=20=EB=B0=8F?=
=?UTF-8?q?=20=EC=84=A4=EC=A0=95=20UI=20=EC=97=B0=EB=8F=99=20=EA=B0=9C?=
=?UTF-8?q?=EC=84=A0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
app/admin-login/page.tsx | 9 +
app/admin-signup/page.tsx | 4 +-
app/master/layout.tsx | 37 +-
app/master/test-sessions/[ID]/page.tsx | 35 +-
.../participants/[participantId]/page.tsx | 41 ++
components/admin-accounts-content.tsx | 542 +++++-----------
components/admin-page-header.tsx | 19 +
components/admin-sidebar.tsx | 30 +-
components/admin-signup-form.tsx | 28 +-
components/global-settings-content.tsx | 33 +-
components/master-dashboard-content.tsx | 160 ++++-
components/master-dashboard.tsx | 15 +-
components/participant-evaluation-content.tsx | 64 +-
components/platform-logs-content.tsx | 33 +-
components/problem-content-md-view.tsx | 39 ++
components/problem-content.tsx | 608 +++++++-----------
components/problem-section.tsx | 5 +-
components/settings-content.tsx | 27 +-
components/test-session-details-content.tsx | 607 +++++++++--------
components/test-sessions-content.tsx | 73 +--
lib/api/admin.ts | 204 +++++-
lib/api/master-admin-accounts.ts | 168 +++++
lib/master-dashboard-kpi.ts | 147 +++++
lib/master-problems.ts | 181 ++++++
lib/master-test-sessions.ts | 234 +++++++
lib/paths/master-participant-evaluation.ts | 19 +
lib/problem-content-md.ts | 91 +++
27 files changed, 2240 insertions(+), 1213 deletions(-)
create mode 100644 app/admin-login/page.tsx
create mode 100644 app/master/test-sessions/[ID]/participants/[participantId]/page.tsx
create mode 100644 components/admin-page-header.tsx
create mode 100644 components/problem-content-md-view.tsx
create mode 100644 lib/api/master-admin-accounts.ts
create mode 100644 lib/master-dashboard-kpi.ts
create mode 100644 lib/master-problems.ts
create mode 100644 lib/master-test-sessions.ts
create mode 100644 lib/paths/master-participant-evaluation.ts
create mode 100644 lib/problem-content-md.ts
diff --git a/app/admin-login/page.tsx b/app/admin-login/page.tsx
new file mode 100644
index 0000000..ed8da3b
--- /dev/null
+++ b/app/admin-login/page.tsx
@@ -0,0 +1,9 @@
+import LoginCard from "@/components/login-card"
+
+export default function AdminLoginPage() {
+ return (
+
+
+
+ )
+}
diff --git a/app/admin-signup/page.tsx b/app/admin-signup/page.tsx
index cdce291..5e38521 100644
--- a/app/admin-signup/page.tsx
+++ b/app/admin-signup/page.tsx
@@ -1,10 +1,8 @@
-"use client";
-
import AdminSignupForm from "@/components/admin-signup-form";
export default function AdminSignupPage() {
return (
-
+
);
diff --git a/app/master/layout.tsx b/app/master/layout.tsx
index 7edc1bf..da6ac73 100644
--- a/app/master/layout.tsx
+++ b/app/master/layout.tsx
@@ -1,16 +1,7 @@
-import type React from "react"
-import type { ReactNode } from "react";
+import type { ReactNode } from "react"
import type { Metadata } from "next"
-import { Geist, Geist_Mono } from "next/font/google"
-import { Analytics } from "@vercel/analytics/next"
-import "../globals.css"
-import { Sidebar } from "@/components/sidebar";
-import { TopNavBar } from "@/components/top-nav-bar";
+import { Sidebar } from "@/components/sidebar"
-const _geist = Geist({ subsets: ["latin"] })
-const _geistMono = Geist_Mono({ subsets: ["latin"] })
-
-// Updated metadata for Master Dashboard
export const metadata: Metadata = {
title: "Master Dashboard - AI Vibe Coding Test",
description: "Admin dashboard for AI Vibe Coding Test platform",
@@ -34,23 +25,23 @@ export const metadata: Metadata = {
},
}
-export default function RootLayout({
+export default function MasterLayout({
children,
}: Readonly<{
- children: React.ReactNode
+ children: ReactNode
}>) {
return (
-
- {/* 왼쪽 고정 사이드바 */}
-
+
+
+
+
- {/* 오른쪽 영역(상단바 + 페이지 내용) */}
-
-
-
- {children}
-
+
+ {children}
- );
+ )
}
diff --git a/app/master/test-sessions/[ID]/page.tsx b/app/master/test-sessions/[ID]/page.tsx
index 9814d6d..2583db2 100644
--- a/app/master/test-sessions/[ID]/page.tsx
+++ b/app/master/test-sessions/[ID]/page.tsx
@@ -1,29 +1,18 @@
-"use client";
+"use client"
-import { useRouter, useParams } from "next/navigation";
-import TestSessionDetailsContent from "@/components/test-session-details-content";
+import { useParams, useRouter } from "next/navigation"
+import TestSessionDetailsContent from "@/components/test-session-details-content"
+import { parseExamIdParam } from "@/lib/master-test-sessions"
export default function Page() {
- const router = useRouter();
- const params = useParams<{ id: string }>();
- const sessionId = params?.id;
-
- // 임시 더미 데이터 (나중에 실제 API 연동 시 여기만 교체)
- const session = {
- id: Number(sessionId),
- sessionId: `SESSION-${sessionId}`, // ➜ Session ID
- createdBy: "Master Admin", // ➜ Created By
- createdAt: "2025-12-05 10:00", // ➜ Created At
- status: "Completed", // ➜ Status (Active / Completed 등)
- participants: 48, // ➜ Participants
- };
+ const router = useRouter()
+ const params = useParams<{ ID?: string; id?: string }>()
+ const examId = parseExamIdParam(params?.ID ?? params?.id)
return (
-
- router.push("/master/test-sessions")}
- />
-
- );
+
router.push("/master/test-sessions")}
+ />
+ )
}
diff --git a/app/master/test-sessions/[ID]/participants/[participantId]/page.tsx b/app/master/test-sessions/[ID]/participants/[participantId]/page.tsx
new file mode 100644
index 0000000..f399967
--- /dev/null
+++ b/app/master/test-sessions/[ID]/participants/[participantId]/page.tsx
@@ -0,0 +1,41 @@
+"use client"
+
+import { useParams, useRouter, useSearchParams } from "next/navigation"
+import { ParticipantEvaluationContent } from "@/components/participant-evaluation-content"
+import { parseExamIdParam } from "@/lib/master-test-sessions"
+
+export default function MasterParticipantEvaluationPage() {
+ const router = useRouter()
+ const params = useParams<{ ID?: string; id?: string; participantId: string }>()
+ const searchParams = useSearchParams()
+
+ const examId = parseExamIdParam(params?.ID ?? params?.id)
+ const participantId = String(params?.participantId ?? "")
+ const participantName = searchParams.get("participantName") ?? undefined
+
+ const handleBack = () => {
+ if (examId != null) {
+ router.push(`/master/test-sessions/${examId}`)
+ } else {
+ router.push("/master/test-sessions")
+ }
+ }
+
+ if (examId == null || !participantId.trim()) {
+ return (
+
+
세션 또는 참가자 정보를 찾을 수 없습니다.
+
+ )
+ }
+
+ return (
+
+ )
+}
diff --git a/components/admin-accounts-content.tsx b/components/admin-accounts-content.tsx
index 4e39ee4..e9f7a2a 100644
--- a/components/admin-accounts-content.tsx
+++ b/components/admin-accounts-content.tsx
@@ -1,7 +1,7 @@
"use client"
import { useState, useEffect } from "react"
-import { MoreHorizontal, Copy, Check, Eye, Power, RotateCcw, KeyRound, Trash2, EyeOff } from "lucide-react"
+import { MoreHorizontal, Copy, Check, Eye, Power, RotateCcw, Trash2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
@@ -20,108 +20,92 @@ import { ScrollArea } from "@/components/ui/scroll-area"
import { useToast } from "@/hooks/use-toast"
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet"
import { Separator } from "@/components/ui/separator"
-import { getAllAdmins, AdminInfo, LoginFailedError, NetworkError, issueAdminNumber, updateAdminNumber, AdminNumberUpdateRequest, toggleAdminNumberActive, AdminNumberDto } from "@/lib/api/admin"
-import { isMasterAdmin, isSystemMasterAdmin, SYSTEM_MASTER_ADMIN_NUMBER } from "@/lib/auth/utils"
+import {
+ fetchMasterAdminAccounts,
+ issueMasterAdminNumber,
+ updateMasterAdminAccountStatus,
+ resetMasterAdminPassword,
+ deleteMasterAdminAccount,
+ sortMasterAdminAccounts,
+ LoginFailedError,
+ NetworkError,
+ type MasterAdminAccount,
+} from "@/lib/api/master-admin-accounts"
+import { isMasterAdmin, isSystemMasterAdmin } from "@/lib/auth/utils"
import { useRouter } from "next/navigation"
+import { AdminPageHeader } from "@/components/admin-page-header"
-type Admin = AdminInfo & {
- status?: string; // UI 표시용: "활성화" | "비활성화"
- lastLogin?: string;
- createdAt?: string;
- secretKey?: string;
- lastKeyIssued?: string;
-}
-
-function generateSecretKey(): string {
- const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
- let key = "sk_prod_"
- for (let i = 0; i < 22; i++) {
- key += chars.charAt(Math.floor(Math.random() * chars.length))
- }
- return key
-}
-
-function generateTempPassword(): string {
- const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
- let password = "temp-"
- for (let i = 0; i < 5; i++) {
- password += chars.charAt(Math.floor(Math.random() * chars.length))
- }
- password += "!"
- password += chars.charAt(Math.floor(Math.random() * 26)) // Add a letter at the end
- return password
+function displayValue(value: string | null | undefined): string {
+ return value && value.trim() ? value : "-"
}
export function AdminAccountsContent() {
- const [adminUsers, setAdminUsers] = useState([])
+ const [adminUsers, setAdminUsers] = useState([])
const [isLoading, setIsLoading] = useState(true)
+ const [listError, setListError] = useState(null)
const [isGenerateModalOpen, setIsGenerateModalOpen] = useState(false)
const [generatedKey, setGeneratedKey] = useState("")
const [copied, setCopied] = useState(false)
- const [selectedAdmin, setSelectedAdmin] = useState(null)
+ const [selectedAdmin, setSelectedAdmin] = useState(null)
const [isChangeStatusOpen, setIsChangeStatusOpen] = useState(false)
const [isResetPasswordOpen, setIsResetPasswordOpen] = useState(false)
const [isResetPasswordResultOpen, setIsResetPasswordResultOpen] = useState(false)
const [tempPassword, setTempPassword] = useState("")
const [tempPasswordCopied, setTempPasswordCopied] = useState(false)
- const [isReissueKeyOpen, setIsReissueKeyOpen] = useState(false)
- const [isReissueKeyResultOpen, setIsReissueKeyResultOpen] = useState(false)
- const [reissuedSecretKey, setReissuedSecretKey] = useState("")
- const [reissuedKeyCopied, setReissuedKeyCopied] = useState(false)
const [isDeleteAdminOpen, setIsDeleteAdminOpen] = useState(false)
const [isDetailsOpen, setIsDetailsOpen] = useState(false)
- const [showSecretKey, setShowSecretKey] = useState(false)
- const [detailsKeyCopied, setDetailsKeyCopied] = useState(false)
const [isChangingStatus, setIsChangingStatus] = useState(false)
+ const [isResettingPassword, setIsResettingPassword] = useState(false)
+ const [isDeletingAdmin, setIsDeletingAdmin] = useState(false)
const { toast } = useToast()
const router = useRouter()
- // 관리자 목록 조회 함수
const fetchAdmins = async () => {
- setIsLoading(true);
+ setIsLoading(true)
+ setListError(null)
try {
- const response = await getAllAdmins();
- // 백엔드 AdminInfo를 Admin 타입으로 변환
- const admins: Admin[] = response.admins.map((admin) => ({
- ...admin,
- status: "활성화", // 백엔드에 상태 필드가 없으면 기본값
- lastLogin: "-", // 백엔드에 마지막 로그인 필드가 없으면 기본값
- createdAt: "-", // 백엔드에 생성일 필드가 없으면 기본값
- }));
- setAdminUsers(admins);
+ const { admins } = await fetchMasterAdminAccounts()
+ setAdminUsers(admins)
} catch (error) {
+ setAdminUsers([])
if (error instanceof LoginFailedError) {
- if (error.message.includes('인증')) {
+ const message = error.message || "관리자 목록 조회에 실패했습니다."
+ setListError(message)
+ if (error.message.includes("인증")) {
toast({
title: "인증 오류",
description: "다시 로그인해주세요.",
variant: "destructive",
- });
- router.push("/");
+ })
+ router.push("/")
} else {
toast({
title: "조회 실패",
- description: error.message,
+ description: message,
variant: "destructive",
- });
+ })
}
} else if (error instanceof NetworkError) {
+ const message = error.message
+ setListError(message)
toast({
title: "네트워크 오류",
- description: error.message,
+ description: message,
variant: "destructive",
- });
+ })
} else {
+ const message = "관리자 목록을 불러오는 중 오류가 발생했습니다."
+ setListError(message)
toast({
title: "오류",
- description: "관리자 목록을 불러오는 중 오류가 발생했습니다.",
+ description: message,
variant: "destructive",
- });
+ })
}
} finally {
- setIsLoading(false);
+ setIsLoading(false)
}
- };
+ }
// 관리자 목록 조회
useEffect(() => {
@@ -149,7 +133,7 @@ export function AdminAccountsContent() {
if (!generatedKey) {
// 관리자 번호 발급 API 호출
try {
- const response = await issueAdminNumber({
+ const response = await issueMasterAdminNumber({
label: undefined,
expiresAt: undefined,
})
@@ -187,7 +171,7 @@ export function AdminAccountsContent() {
}
}
- const handleOpenChangeStatus = (admin: Admin) => {
+ const handleOpenChangeStatus = (admin: MasterAdminAccount) => {
// MASTER-0001 보호 로직
if (isSystemMasterAdmin({ adminNumber: admin.adminNumber })) {
toast({
@@ -203,7 +187,7 @@ export function AdminAccountsContent() {
}
// 공용 상태 변경 핸들러 (모달에서 확인 버튼을 누른 후 호출됨)
- const handleToggleStatus = async (admin: Admin) => {
+ const handleToggleStatus = async (admin: MasterAdminAccount) => {
// MASTER-0001 보호 로직 (이중 체크)
if (isSystemMasterAdmin({ adminNumber: admin.adminNumber })) {
toast({
@@ -218,47 +202,24 @@ export function AdminAccountsContent() {
setIsChangingStatus(true);
try {
- // 현재 상태를 기반으로 active 값 추론
- const currentActive = admin.status === "활성화";
-
- // AdminNumberDto 구성 (status 기반으로 active 추론)
- const adminNumberDto: AdminNumberDto = {
- adminNumber: admin.adminNumber,
- label: undefined,
- active: currentActive,
- issuedBy: 0, // 실제 값은 필요 없음 (API에서 사용하지 않음)
- assignedAdminId: admin.id,
- expiresAt: undefined,
- usedAt: undefined,
- createdAt: "",
- };
-
- // toggleAdminNumberActive 호출
- const updated = await toggleAdminNumberActive(adminNumberDto);
+ const updated = await updateMasterAdminAccountStatus(admin)
- // 성공 시 목록(state) 즉시 업데이트
setAdminUsers((prevUsers) =>
prevUsers.map((user) =>
- user.adminNumber === admin.adminNumber
- ? { ...user, status: updated.active ? "활성화" : "비활성화" }
- : user
+ user.adminNumber === admin.adminNumber ? updated : user
)
- );
+ )
- // 상세 패널이 열려 있으면 selectedAdmin도 업데이트
if (selectedAdmin && selectedAdmin.adminNumber === admin.adminNumber) {
- setSelectedAdmin({
- ...selectedAdmin,
- status: updated.active ? "활성화" : "비활성화",
- });
+ setSelectedAdmin(updated)
}
toast({
title: "상태 변경 성공",
- description: updated.active
+ description: updated.isActive
? "관리자 계정이 활성화되었습니다."
: "관리자 계정이 비활성화되었습니다.",
- });
+ })
setIsChangeStatusOpen(false);
setSelectedAdmin(null);
@@ -292,9 +253,8 @@ export function AdminAccountsContent() {
await handleToggleStatus(selectedAdmin);
}
- const handleOpenResetPassword = (admin: Admin) => {
- // MASTER-0001 보호 로직
- if (isSystemMasterAdmin({ adminNumber: admin.adminNumber })) {
+ const handleOpenResetPassword = (admin: MasterAdminAccount) => {
+ if (isSystemMasterAdmin({ adminNumber: admin.adminNumber }) || admin.role === "MASTER") {
toast({
title: "변경 불가",
description: "마스터 관리자 계정은 비밀번호를 재설정할 수 없습니다.",
@@ -307,12 +267,29 @@ export function AdminAccountsContent() {
setIsResetPasswordOpen(true)
}
- const handleConfirmResetPassword = () => {
- const newTempPassword = generateTempPassword()
- setTempPassword(newTempPassword)
- setTempPasswordCopied(false)
- setIsResetPasswordOpen(false)
- setIsResetPasswordResultOpen(true)
+ const handleConfirmResetPassword = async () => {
+ if (!selectedAdmin) return
+
+ setIsResettingPassword(true)
+ try {
+ const { temporaryPassword } = await resetMasterAdminPassword(selectedAdmin)
+ setTempPassword(temporaryPassword)
+ setTempPasswordCopied(false)
+ setIsResetPasswordOpen(false)
+ setIsResetPasswordResultOpen(true)
+ } catch (error) {
+ const message =
+ error instanceof LoginFailedError || error instanceof NetworkError
+ ? error.message
+ : "비밀번호 재설정에 실패했습니다."
+ toast({
+ title: "비밀번호 재설정 불가",
+ description: message,
+ variant: "destructive",
+ })
+ } finally {
+ setIsResettingPassword(false)
+ }
}
const handleCopyTempPassword = async () => {
@@ -324,75 +301,14 @@ export function AdminAccountsContent() {
setTimeout(() => setTempPasswordCopied(false), 2000)
}
- const handleOpenReissueKey = (admin: Admin) => {
- // MASTER-0001 보호 로직
- if (isSystemMasterAdmin({ adminNumber: admin.adminNumber })) {
- toast({
- title: "변경 불가",
- description: "마스터 관리자 계정은 시크릿 키를 재발급할 수 없습니다.",
- variant: "destructive",
- });
- return;
- }
-
- setSelectedAdmin(admin)
- setIsReissueKeyOpen(true)
- }
-
- const formatDateToKorean = (date: Date) => {
- const year = date.getFullYear()
- const month = date.getMonth() + 1
- const day = date.getDate()
- const hours = date.getHours()
- const minutes = date.getMinutes()
- const ampm = hours >= 12 ? "오후" : "오전"
- const displayHours = hours % 12 || 12
- const displayMinutes = minutes.toString().padStart(2, "0")
- return `${year}년 ${month}월 ${day}일 ${ampm} ${displayHours}:${displayMinutes}`
- }
-
- const handleConfirmReissueKey = () => {
- const randomStr = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 11)
- const newKey = `sk_prod_${randomStr}`
- setReissuedSecretKey(newKey)
-
- // Update the admin user's secret key and lastKeyIssued date
- if (selectedAdmin) {
- const now = new Date()
- const koreanDate = formatDateToKorean(now)
- setAdminUsers((prevUsers) =>
- prevUsers.map((user) =>
- user.id === selectedAdmin.id
- ? { ...user, secretKey: newKey, lastKeyIssued: koreanDate }
- : user
- )
- )
- // Update selectedAdmin to reflect the changes
- setSelectedAdmin((prev) => prev ? {
- ...prev,
- secretKey: newKey,
- lastKeyIssued: koreanDate,
- } : null)
- }
-
- setIsReissueKeyOpen(false)
- setIsReissueKeyResultOpen(true)
- setReissuedKeyCopied(false)
- }
-
- const copyReissuedKey = async () => {
- await navigator.clipboard.writeText(reissuedSecretKey)
- setReissuedKeyCopied(true)
- toast({
- title: "Secret key copied to clipboard",
- duration: 2000,
- })
- setTimeout(() => setReissuedKeyCopied(false), 2000)
+ const handleCloseResetPasswordResult = () => {
+ setIsResetPasswordResultOpen(false)
+ setTempPassword("")
+ setTempPasswordCopied(false)
}
- const handleOpenDeleteAdmin = (admin: Admin) => {
- // MASTER-0001 보호 로직
- if (isSystemMasterAdmin({ adminNumber: admin.adminNumber })) {
+ const handleOpenDeleteAdmin = (admin: MasterAdminAccount) => {
+ if (isSystemMasterAdmin({ adminNumber: admin.adminNumber }) || admin.role === "MASTER") {
toast({
title: "삭제 불가",
description: "마스터 관리자 계정은 삭제할 수 없습니다.",
@@ -405,40 +321,48 @@ export function AdminAccountsContent() {
setIsDeleteAdminOpen(true)
}
- const handleConfirmDeleteAdmin = () => {
- if (selectedAdmin) {
+ const handleConfirmDeleteAdmin = async () => {
+ if (!selectedAdmin) return
+ setIsDeletingAdmin(true)
+ try {
+ await deleteMasterAdminAccount(selectedAdmin)
setAdminUsers((prev) => prev.filter((a) => a.id !== selectedAdmin.id))
setIsDeleteAdminOpen(false)
+ setIsDetailsOpen(false)
+ setSelectedAdmin(null)
+ toast({
+ title: "관리자 삭제 완료",
+ description: "관리자 계정이 삭제되었습니다.",
+ })
+ } catch (error) {
+ const message =
+ error instanceof LoginFailedError || error instanceof NetworkError
+ ? error.message
+ : "관리자 삭제에 실패했습니다."
+ toast({
+ title: "관리자 삭제 불가",
+ description: message,
+ variant: "destructive",
+ })
+ } finally {
+ setIsDeletingAdmin(false)
}
}
- const handleOpenDetails = (admin: Admin) => {
+ const handleOpenDetails = (admin: MasterAdminAccount) => {
setSelectedAdmin(admin)
- setShowSecretKey(false)
- setDetailsKeyCopied(false)
setIsDetailsOpen(true)
}
- const handleCopyDetailsKey = async () => {
- if (selectedAdmin) {
- // 시크릿 키는 백엔드에 없는 필드이므로 임시로 관리자 번호 복사
- await navigator.clipboard.writeText(selectedAdmin.adminNumber)
- setDetailsKeyCopied(true)
- toast({
- description: "관리자 번호가 클립보드에 복사되었습니다.",
- })
- setTimeout(() => setDetailsKeyCopied(false), 2000)
- }
- }
-
const handleChangeStatusFromPanel = () => {
setIsDetailsOpen(false)
setIsChangeStatusOpen(true)
}
const handleResetPasswordFromPanel = () => {
+ if (!selectedAdmin) return
setIsDetailsOpen(false)
- setIsResetPasswordOpen(true)
+ handleOpenResetPassword(selectedAdmin)
}
const handleDeleteAdminFromPanel = () => {
@@ -447,29 +371,13 @@ export function AdminAccountsContent() {
}
return (
-
- {/* Page Header */}
-
-
- 관리자 계정 관리
-
-
- 관리자 계정과 접근 권한을 관리합니다.
-
-
+
+
+
{/* Admin Users Card */}
@@ -496,6 +404,14 @@ export function AdminAccountsContent() {
+ {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)}
- >
-
- 시크릿 키 재발급
-
- 관리자의 다음 로그인을 위해 임시 비밀번호가 생성됩니다.
+ 해당 관리자의 비밀번호를 임시 비밀번호로 재설정하시겠습니까?
- 이 관리자의 비밀번호를 재설정하시겠습니까?
+ 생성된 임시 비밀번호는 한 번만 표시됩니다. 관리자에게 안전하게 전달한 뒤, 해당 관리자는 설정 화면에서 본인이 직접 비밀번호를 변경할 수 있습니다.
setIsResetPasswordOpen(false)}
+ disabled={isResettingPassword}
style={{
fontSize: "14px",
fontWeight: 500,
@@ -946,21 +861,28 @@ export function AdminAccountsContent() {
- 비밀번호 재설정
+ {isResettingPassword ? "처리 중..." : "비밀번호 재설정"}
{/* Modal — Temporary password generated (result) */}
-
+ {
+ if (!open) handleCloseResetPasswordResult()
+ }}
+ >
- 이 비밀번호를 복사하여 관리자에게 안전하게 전달해주세요.
+ 이 비밀번호는 한 번만 표시됩니다. 모달을 닫으면 다시 확인할 수 없습니다.
@@ -1019,7 +941,7 @@ export function AdminAccountsContent() {
setIsResetPasswordResultOpen(false)}
+ onClick={handleCloseResetPasswordResult}
style={{
backgroundColor: "#3B82F6",
color: "#FFFFFF",
@@ -1033,75 +955,18 @@ 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?
-
-
-
- setIsReissueKeyOpen(false)}>
- Cancel
-
-
- Reissue Key
-
-
-
-
-
- {/* Modal — Reissue Secret Key result dialog */}
-
-
-
-
- New Secret Key Issued
-
-
-
-
- This secret key will only be shown once. Please copy and store it safely.
-
-
-
Secret Key
-
-
-
- {reissuedKeyCopied ? : }
-
-
-
-
-
- setIsReissueKeyResultOpen(false)}
- >
- Close
-
-
-
-
-
{/* 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.
+ 해당 관리자의 접근 권한이 즉시 제거됩니다.
setIsDeleteAdminOpen(false)}>
- Cancel
+ 취소
-
- Delete Admin
+
+ {isDeletingAdmin ? "삭제 중..." : "관리자 삭제"}
@@ -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 : "•••••••••••••••••••••"}
-
-
setShowSecretKey(!showSecretKey)}
- className="h-9 w-9 shrink-0 bg-transparent border-[#E5E5E5]"
- >
- {showSecretKey ? (
-
- ) : (
-
- )}
-
-
- {detailsKeyCopied ? (
-
- ) : (
-
- )}
-
-
-
-
-
마지막 시크릿 키 발급일
-
- {selectedAdmin?.lastKeyIssued}
-
-
+
+
비밀번호 상태
+
+ {selectedAdmin?.passwordStatus ?? "-"}
+
@@ -1304,18 +1136,6 @@ export function AdminAccountsContent() {
>
비밀번호 재설정
-
- 시크릿 키 재발급
-
비밀번호 재설정
- {
- setIsDetailsOpen(false);
- if (selectedAdmin) {
- handleOpenReissueKey(selectedAdmin);
- }
- }}>
-
- 시크릿 키 재발급
-
관리자 삭제
@@ -1357,6 +1168,7 @@ export function AdminAccountsContent() {
+
)
}
diff --git a/components/admin-page-header.tsx b/components/admin-page-header.tsx
new file mode 100644
index 0000000..395253e
--- /dev/null
+++ b/components/admin-page-header.tsx
@@ -0,0 +1,19 @@
+import type { ReactNode } from "react"
+
+export type AdminPageHeaderProps = {
+ title: string
+ description?: string
+ actions?: ReactNode
+}
+
+export function AdminPageHeader({ title, description, actions }: AdminPageHeaderProps) {
+ return (
+
+
+
{title}
+ {description ?
{description}
: null}
+
+ {actions ? {actions}
: null}
+
+ )
+}
diff --git a/components/admin-sidebar.tsx b/components/admin-sidebar.tsx
index 6ba0a73..55aa97b 100644
--- a/components/admin-sidebar.tsx
+++ b/components/admin-sidebar.tsx
@@ -1,6 +1,6 @@
"use client"
-import { useState } from "react"
+import { useState, useEffect } from "react"
import Link from "next/link"
import { usePathname, useRouter } from "next/navigation"
import {
@@ -25,7 +25,7 @@ import {
DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
-import { logoutAdmin } from "@/lib/api/admin"
+import { getMe, logoutAdmin, resolveAdminDisplayNameFromMe } from "@/lib/api/admin"
const menuGroupA = [
{ icon: LayoutDashboard, label: "대시보드", href: "/admin/dashboard" },
@@ -74,6 +74,30 @@ export function AdminSidebar() {
const router = useRouter()
const [showLogoutModal, setShowLogoutModal] = useState(false)
const [isLoggingOut, setIsLoggingOut] = useState(false)
+ const [displayName, setDisplayName] = useState("관리자")
+
+ useEffect(() => {
+ let cancelled = false
+
+ const fetchAdminDisplayName = async () => {
+ try {
+ const response = await getMe()
+ if (!cancelled) {
+ setDisplayName(resolveAdminDisplayNameFromMe(response))
+ }
+ } catch {
+ if (!cancelled) {
+ setDisplayName("관리자")
+ }
+ }
+ }
+
+ fetchAdminDisplayName()
+
+ return () => {
+ cancelled = true
+ }
+ }, [])
const isActive = (href: string) => {
if (href === "/") {
@@ -124,7 +148,7 @@ export function AdminSidebar() {
- Admin
+ {displayName}
관리자
diff --git a/components/admin-signup-form.tsx b/components/admin-signup-form.tsx
index 5480290..5414acf 100644
--- a/components/admin-signup-form.tsx
+++ b/components/admin-signup-form.tsx
@@ -3,7 +3,7 @@
import type React from "react"
import { useState } from "react"
-
+import Link from "next/link"
import { useRouter } from "next/navigation";
import { signUpAdmin, LoginFailedError, NetworkError } from "@/lib/api/admin"
import { useToast } from "@/hooks/use-toast"
@@ -11,6 +11,7 @@ import { useToast } from "@/hooks/use-toast"
export default function AdminSignupForm() {
const [formData, setFormData] = useState({
adminNumber: "",
+ displayName: "",
email: "",
password: "",
confirmPassword: "",
@@ -35,6 +36,10 @@ export default function AdminSignupForm() {
setError("관리자 번호를 입력해주세요.")
return
}
+ if (!formData.displayName.trim()) {
+ setError("이름을 입력해주세요.")
+ return
+ }
if (!formData.email.trim()) {
setError("이메일을 입력해주세요.")
return
@@ -63,6 +68,7 @@ export default function AdminSignupForm() {
try {
await signUpAdmin({
adminNumber: formData.adminNumber.trim(),
+ displayName: formData.displayName.trim(),
email: formData.email.trim(),
password: formData.password.trim(),
})
@@ -91,6 +97,13 @@ export default function AdminSignupForm() {
return (
+
+ ← 로그인으로
+
+
{/* Header */}
관리자 회원가입
@@ -110,6 +123,19 @@ export default function AdminSignupForm() {
/>
+ {/* Display Name */}
+
+ 이름
+
+
+
{/* Email Address */}
이메일 주소
diff --git a/components/global-settings-content.tsx b/components/global-settings-content.tsx
index 0424645..c95ff37 100644
--- a/components/global-settings-content.tsx
+++ b/components/global-settings-content.tsx
@@ -8,6 +8,7 @@ import { Button } from "@/components/ui/button"
import { Switch } from "@/components/ui/switch"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { useToast } from "@/hooks/use-toast"
+import { AdminPageHeader } from "@/components/admin-page-header"
type Settings = {
defaultTestDuration: string
@@ -116,32 +117,13 @@ export function GlobalSettingsContent() {
}
return (
-
- {/* Page Header */}
-
-
- 전역 설정
-
-
- 플랫폼 전역 설정 및 시스템 보안 정책을 관리합니다
-
-
+
+
+
{/* Settings Cards Container */}
{/* Section 1: Test Configuration */}
@@ -415,6 +397,7 @@ export function GlobalSettingsContent() {
)}
+
)
}
diff --git a/components/master-dashboard-content.tsx b/components/master-dashboard-content.tsx
index 9a70ed5..7c981da 100644
--- a/components/master-dashboard-content.tsx
+++ b/components/master-dashboard-content.tsx
@@ -1,12 +1,30 @@
"use client"
-import { useState } from "react"
+import { useEffect, useState } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Users, UserCheck, CheckCircle2, CalendarClock, FileCode, ScrollText, ArrowRight, KeyRound, Copy, Check } from "lucide-react"
import Link from "next/link";
-import { issueAdminNumber, LoginFailedError, NetworkError } from "@/lib/api/admin"
+import {
+ getBoard,
+ getExams,
+ getSystemStatus,
+ issueAdminNumber,
+ LoginFailedError,
+ NetworkError,
+} from "@/lib/api/admin"
+import {
+ countActiveExamSessions,
+ countTodayParticipants,
+ deriveMasterSystemStatusDisplay,
+ type MasterSystemStatusDisplay,
+} from "@/lib/master-dashboard-kpi"
+import {
+ isMasterSessionInProgress,
+ pickRecentSessions,
+ type MasterRecentSession,
+} from "@/lib/master-test-sessions"
import { useToast } from "@/hooks/use-toast"
import {
Dialog,
@@ -18,13 +36,7 @@ import {
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
-
-const recentSessions = [
- { id: 1, sessionId: "SESSION-2025-001", status: "진행 중", createdAt: "2025년 1월 14일", participants: 18 },
- { id: 2, sessionId: "SESSION-2025-002", status: "완료", createdAt: "2025년 1월 13일", participants: 25 },
- { id: 3, sessionId: "SESSION-2025-003", status: "진행 중", createdAt: "2025년 1월 12일", participants: 12 },
- { id: 4, sessionId: "SESSION-2025-004", status: "완료", createdAt: "2025년 1월 11일", participants: 30 },
-]
+import { AdminPageHeader } from "@/components/admin-page-header"
const recentLogs = [
{ id: 1, timestamp: "오전 10:33", type: "관리자", description: "관리자 'john.smith'가 플랫폼 설정을 업데이트했습니다" },
@@ -43,8 +55,79 @@ export function MasterDashboardContent({ onNavigate }: DashboardContentProps) {
const [issuedAdminNumber, setIssuedAdminNumber] = useState
(null)
const [copied, setCopied] = useState(false)
const [isLoading, setIsLoading] = useState(false)
+ const [activeSessions, setActiveSessions] = useState(null)
+ const [todayParticipants, setTodayParticipants] = useState(null)
+ const [systemStatus, setSystemStatus] = useState(
+ deriveMasterSystemStatusDisplay({ type: "fetch_failed" })
+ )
+ const [kpiLoading, setKpiLoading] = useState(true)
+ const [recentSessions, setRecentSessions] = useState([])
+ const [recentSessionsLoading, setRecentSessionsLoading] = useState(true)
+ const [recentSessionsError, setRecentSessionsError] = useState(false)
const { toast } = useToast()
+ useEffect(() => {
+ let cancelled = false
+
+ async function loadKpi() {
+ setKpiLoading(true)
+ setRecentSessionsLoading(true)
+ setRecentSessionsError(false)
+ try {
+ const [examsResult, statusResult] = await Promise.allSettled([
+ (async () => {
+ const exams = await getExams()
+ const boards = await Promise.all(
+ exams.map((e) => getBoard(e.id).catch(() => []))
+ )
+ return { exams, boards }
+ })(),
+ getSystemStatus(),
+ ])
+
+ if (cancelled) return
+
+ if (examsResult.status === "fulfilled") {
+ const { exams, boards } = examsResult.value
+ setActiveSessions(countActiveExamSessions(exams))
+ setTodayParticipants(countTodayParticipants(exams, boards))
+ setRecentSessions(pickRecentSessions(exams))
+ } else {
+ console.error("[MasterDashboard] Failed to load session/participant KPI", examsResult.reason)
+ setActiveSessions(0)
+ setTodayParticipants(0)
+ setRecentSessions([])
+ setRecentSessionsError(true)
+ }
+
+ if (statusResult.status === "fulfilled") {
+ setSystemStatus(
+ deriveMasterSystemStatusDisplay({
+ type: "services",
+ services: statusResult.value.services ?? [],
+ })
+ )
+ } else {
+ console.error("[MasterDashboard] Failed to load system status", statusResult.reason)
+ setSystemStatus(deriveMasterSystemStatusDisplay({ type: "fetch_failed" }))
+ }
+ } finally {
+ if (!cancelled) {
+ setKpiLoading(false)
+ setRecentSessionsLoading(false)
+ }
+ }
+ }
+
+ loadKpi()
+ return () => {
+ cancelled = true
+ }
+ }, [])
+
+ const displayKpiNumber = (val: number | null) =>
+ kpiLoading ? "..." : val !== null ? val.toLocaleString() : "0"
+
const handleIssueAdminNumber = async () => {
setIsLoading(true)
try {
@@ -105,15 +188,10 @@ export function MasterDashboardContent({ onNavigate }: DashboardContentProps) {
}
return (
-
- {/* Page Header */}
-
-
- 마스터 대시보드
-
-
플랫폼 활동 및 코딩 테스트 운영 개요.
-
+
+
+
{/* Section 1: KPI Summary Cards */}
{/* Active Sessions */}
@@ -121,7 +199,9 @@ export function MasterDashboardContent({ onNavigate }: DashboardContentProps) {
- 12
+
+ {displayKpiNumber(activeSessions)}
+
진행 중인 세션
- 148
+
+ {displayKpiNumber(todayParticipants)}
+
오늘의 참가자
- 운영 중
+
+ {kpiLoading ? "..." : systemStatus.label}
+
시스템 상태
-
+
@@ -197,8 +290,17 @@ export function MasterDashboardContent({ onNavigate }: DashboardContentProps) {
최근 세션
-
- {recentSessions.map((session) => (
+
+ {recentSessionsLoading ? (
+
최근 세션을 불러오는 중…
+ ) : recentSessionsError ? (
+
+ 최근 세션을 불러오지 못했습니다.
+
+ ) : recentSessions.length === 0 ? (
+
최근 세션이 없습니다.
+ ) : (
+ recentSessions.map((session) => (
- ))}
+ ))
+ )}
+
)
}
diff --git a/components/master-dashboard.tsx b/components/master-dashboard.tsx
index b70d8aa..c3f601c 100644
--- a/components/master-dashboard.tsx
+++ b/components/master-dashboard.tsx
@@ -2,8 +2,7 @@
import { useState } from "react"
import { Sidebar } from "@/components/sidebar"
-import { TopNavBar } from "@/components/top-nav-bar"
-import { DashboardContent } from "@/components/dashboard-content"
+import { MasterDashboardContent } from "@/components/master-dashboard-content"
import { AdminAccountsContent } from "@/components/admin-accounts-content"
import { TestSessionsContent } from "@/components/test-sessions-content"
import TestSessionDetailsContent from "@/components/test-session-details-content"
@@ -43,19 +42,15 @@ export function MasterDashboard() {
-
-
-
-
-
-
- {activeItem === "Dashboard" && }
+
+
+ {activeItem === "Dashboard" && }
{activeItem === "Admin Accounts" && }
{activeItem === "Test Sessions" && !selectedSession && (
)}
{activeItem === "Test Sessions" && selectedSession && (
-
+
)}
{activeItem === "Global Settings" && }
{activeItem === "Problem" && }
diff --git a/components/participant-evaluation-content.tsx b/components/participant-evaluation-content.tsx
index 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 */}
-
{
- e.stopPropagation()
- handleViewDetail(problem)
- }}
- className="flex items-center gap-2 px-4 py-2 rounded-lg text-blue-600 hover:bg-blue-50 transition-colors"
- style={{
- fontSize: "14px",
- fontWeight: 500,
- }}
- >
-
- 상세 보기
-
-
- ))}
-
- {/* 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}
+
+
+
+
생성일
+
{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)} 표시
-
-
- setCurrentPage(currentPage - 1)}
- disabled={currentPage === 1}
- className="h-8 w-8 p-0"
- >
-
-
- {getPageNumbers().map((page) => (
- setCurrentPage(page)}
- className={`h-8 w-8 p-0 ${
- currentPage === page
- ? "bg-blue-600 text-white hover:bg-blue-700"
- : "text-gray-600 hover:bg-gray-100"
- }`}
- >
- {page}
-
- ))}
- setCurrentPage(currentPage + 1)}
- disabled={currentPage === totalPages}
- className="h-8 w-8 p-0"
- >
-
-
-
-
- )}
-
-
+ {totalPages > 1 && (
+
+
+ 총 {participants.length}명의 참가자 중 {startIndex + 1}–
+ {Math.min(endIndex, participants.length)} 표시
+
+
+ setCurrentPage(currentPage - 1)}
+ disabled={currentPage === 1}
+ className="h-8 w-8 p-0"
+ >
+
+
+ {getPageNumbers().map((page) => (
+ setCurrentPage(page)}
+ className={`h-8 w-8 p-0 ${
+ currentPage === page
+ ? "bg-blue-600 text-white hover:bg-blue-700"
+ : "text-gray-600 hover:bg-gray-100"
+ }`}
+ >
+ {page}
+
+ ))}
+ setCurrentPage(currentPage + 1)}
+ disabled={currentPage === totalPages}
+ className="h-8 w-8 p-0"
+ >
+
+
+
+
+ )}
+ >
+ )}
+
+
+ >
+ )}
+
)
}
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)}
+
+
+
+
@@ -626,9 +640,10 @@ export function AdminAccountsContent() {
관리자 삭제
-
-
-
+
+
+
+
);
})
)}
@@ -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];