Phase 10. 마에스트로 정보 수정 및 학생 목록 페이지네이션 적용

This commit is contained in:
2026-06-29 17:20:24 +09:00
parent f384388c67
commit 5f9bb39ce1
11 changed files with 1130 additions and 91 deletions
@@ -0,0 +1,254 @@
"use client";
import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Save } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
ACCOUNT_TYPE_LABELS,
ACCOUNT_TYPES,
ACTIVATE_STATUS_LABELS,
ACTIVATE_STATUSES,
} from "@/lib/constants";
import { formatDate, formatDateTime, toDatetimeLocal } from "@/lib/utils";
import type { MaestroDetail } from "@/lib/maestros";
type MaestroEditFormProps = {
maestro: MaestroDetail["maestro"];
playerCount: number;
};
const paidAccountTypeOptions = [
ACCOUNT_TYPES.BASIC_20,
ACCOUNT_TYPES.STANDARD_50,
ACCOUNT_TYPES.PRO_100,
ACCOUNT_TYPES.SCHOOL_500,
ACCOUNT_TYPES.SCHOOL_1000,
] as const;
const activateStatusOptions = [
ACTIVATE_STATUSES.PENDING,
ACTIVATE_STATUSES.TRIAL,
ACTIVATE_STATUSES.ACTIVE,
ACTIVATE_STATUSES.CANCELED,
] as const;
const inputClass =
"h-9 w-full rounded-md border bg-background px-3 text-sm outline-none transition-colors focus:border-ring focus:ring-3 focus:ring-ring/30 disabled:opacity-50";
export function MaestroEditForm({ maestro, playerCount }: MaestroEditFormProps) {
const router = useRouter();
const [isPending, startTransition] = useTransition();
const [isSaving, setIsSaving] = useState(false);
const [name, setName] = useState(maestro.name);
const [email, setEmail] = useState(maestro.email);
const [activateStatus, setActivateStatus] = useState(maestro.activateStatus);
const [accountType, setAccountType] = useState(maestro.accountType);
const [availableActivateDateTime, setAvailableActivateDateTime] = useState(
toDatetimeLocal(maestro.availableActivateDateTime)
);
const [allowEditEnterCode, setAllowEditEnterCode] = useState(
maestro.allowEditEnterCode
);
const [errorMessage, setErrorMessage] = useState("");
const [successMessage, setSuccessMessage] = useState("");
const isDisabled = isSaving || isPending;
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!window.confirm("마에스트로 정보를 저장하시겠습니까?")) return;
setIsSaving(true);
setErrorMessage("");
setSuccessMessage("");
try {
const response = await fetch(`/api/maestros/${maestro.maestroID}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name,
email,
activateStatus,
accountType,
availableActivateDateTime,
allowEditEnterCode,
}),
});
const body = (await response.json().catch(() => null)) as {
changed?: boolean;
message?: string;
} | null;
if (!response.ok) {
throw new Error(body?.message ?? "저장에 실패했습니다.");
}
if (body?.changed) {
setSuccessMessage("저장 완료");
startTransition(() => {
router.refresh();
});
} else {
setSuccessMessage("변경 사항이 없습니다.");
}
} catch (error) {
setErrorMessage(
error instanceof Error ? error.message : "저장에 실패했습니다."
);
} finally {
setIsSaving(false);
}
}
return (
<form onSubmit={(e) => void handleSubmit(e)} className="mt-4 space-y-5">
<div className="grid gap-x-8 gap-y-4 text-sm md:grid-cols-2 xl:grid-cols-3">
<FormField label="이름">
<input
className={inputClass}
disabled={isDisabled}
maxLength={50}
onChange={(e) => setName(e.target.value)}
required
type="text"
value={name}
/>
</FormField>
<FormField label="이메일">
<input
className={inputClass}
disabled={isDisabled}
maxLength={50}
onChange={(e) => setEmail(e.target.value)}
required
type="email"
value={email}
/>
</FormField>
<FormField label="상태">
<select
className={inputClass}
disabled={isDisabled}
onChange={(e) => setActivateStatus(Number(e.target.value))}
value={activateStatus}
>
{activateStatusOptions.map((s) => (
<option key={s} value={s}>
{ACTIVATE_STATUS_LABELS[s]}
</option>
))}
</select>
</FormField>
<FormField label="계정 유형">
<select
className={inputClass}
disabled={isDisabled}
onChange={(e) => setAccountType(Number(e.target.value))}
value={accountType}
>
{paidAccountTypeOptions.map((t) => (
<option key={t} value={t}>
{ACCOUNT_TYPE_LABELS[t]}
</option>
))}
</select>
</FormField>
<FormField label="사용 가능일">
<input
className={inputClass}
disabled={isDisabled}
onChange={(e) => setAvailableActivateDateTime(e.target.value)}
required
type="datetime-local"
value={availableActivateDateTime}
/>
</FormField>
<FormField label="입장코드 수정">
<select
className={inputClass}
disabled={isDisabled}
onChange={(e) => setAllowEditEnterCode(Number(e.target.value))}
value={allowEditEnterCode}
>
<option value={1}></option>
<option value={0}></option>
</select>
</FormField>
</div>
<div className="grid gap-x-8 gap-y-3 border-t pt-4 text-sm md:grid-cols-2 xl:grid-cols-3">
<ReadOnlyItem
label="약관 동의일"
value={formatDateTime(maestro.acceptClausesDateTime)}
/>
<ReadOnlyItem
label="DB 학생 수"
value={playerCount.toLocaleString()}
/>
<ReadOnlyItem
label="PlayerCount"
value={maestro.playerCount.toLocaleString()}
/>
<ReadOnlyItem
label="체험 MaestroID"
value={maestro.maestroTestID?.toString() ?? "-"}
/>
<ReadOnlyItem
label="사용 가능일 (현재)"
value={formatDate(maestro.availableActivateDateTime)}
/>
</div>
<div className="flex items-center gap-3">
<Button disabled={isDisabled} size="sm" type="submit">
<Save aria-hidden="true" className="size-4" />
</Button>
{successMessage ? (
<p className="text-sm text-green-700 dark:text-green-400">
{successMessage}
</p>
) : null}
{errorMessage ? (
<p className="text-sm text-destructive">{errorMessage}</p>
) : null}
</div>
</form>
);
}
function FormField({
label,
children,
}: {
label: string;
children: React.ReactNode;
}) {
return (
<label className="space-y-1.5">
<span className="text-xs font-medium text-muted-foreground">{label}</span>
{children}
</label>
);
}
function ReadOnlyItem({ label, value }: { label: string; value: string }) {
return (
<div>
<dt className="text-xs font-medium text-muted-foreground">{label}</dt>
<dd className="mt-1 font-medium">{value}</dd>
</div>
);
}
@@ -0,0 +1,325 @@
"use client";
import { useState, useEffect } from "react";
import {
ChevronLeft,
ChevronRight,
ChevronsLeft,
ChevronsRight,
Search,
} from "lucide-react";
import { Button, buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import type { MaestroStudentsResult } from "@/lib/maestros";
type StudentsSectionProps = {
maestroID: number;
};
export function StudentsSection({ maestroID }: StudentsSectionProps) {
const [q, setQ] = useState("");
const [submittedQ, setSubmittedQ] = useState("");
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [data, setData] = useState<MaestroStudentsResult | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [errorMessage, setErrorMessage] = useState("");
useEffect(() => {
let cancelled = false;
const run = async () => {
setIsLoading(true);
setErrorMessage("");
try {
const params = new URLSearchParams({
page: String(page),
pageSize: String(pageSize),
q: submittedQ,
});
const response = await fetch(
`/api/maestros/${maestroID}/students?${params.toString()}`
);
if (!response.ok) {
throw new Error("학생 목록을 불러오지 못했습니다.");
}
const result = (await response.json()) as MaestroStudentsResult;
if (!cancelled) {
setData(result);
}
} catch (err) {
if (!cancelled) {
setErrorMessage(
err instanceof Error
? err.message
: "학생 목록을 불러오지 못했습니다."
);
}
} finally {
if (!cancelled) {
setIsLoading(false);
}
}
};
void run();
return () => {
cancelled = true;
};
}, [maestroID, submittedQ, page, pageSize]);
function handleSearch(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
setPage(1);
setSubmittedQ(q);
}
return (
<section className="rounded-lg border bg-background p-5">
<div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
<div>
<h2 className="text-base font-semibold"> </h2>
<p className="mt-1 text-sm text-muted-foreground">
{data
? `전체 ${data.totalCount.toLocaleString()}${submittedQ ? ` — "${submittedQ}" 검색 결과` : ""}`
: "로딩 중..."}
</p>
</div>
<form className="flex gap-2" onSubmit={handleSearch}>
<div className="relative">
<Search
aria-hidden="true"
className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"
/>
<input
className="h-8 w-44 rounded-md border bg-background pl-9 pr-3 text-sm outline-none transition-colors focus:border-ring focus:ring-3 focus:ring-ring/30"
onChange={(e) => setQ(e.target.value)}
placeholder="이름 검색"
type="search"
value={q}
/>
</div>
<Button size="sm" type="submit">
</Button>
</form>
</div>
{errorMessage ? (
<p className="mt-4 text-sm text-destructive">{errorMessage}</p>
) : (
<>
<StudentTable isLoading={isLoading} result={data} />
{data ? (
<StudentPagination
onPageChange={setPage}
onPageSizeChange={(size) => {
setPageSize(size);
setPage(1);
}}
page={data.page}
pageSize={pageSize}
totalPages={data.totalPages}
/>
) : null}
</>
)}
</section>
);
}
function StudentTable({
result,
isLoading,
}: {
result: MaestroStudentsResult | null;
isLoading: boolean;
}) {
if (isLoading || !result) {
return (
<div className="mt-4 flex h-24 items-center justify-center rounded-lg border">
<p className="text-sm text-muted-foreground"> ...</p>
</div>
);
}
return (
<div className="mt-4 overflow-hidden rounded-lg border">
<div className="overflow-x-auto">
<table className="w-full min-w-[360px] border-collapse text-sm">
<thead className="bg-muted/60">
<tr className="border-b">
<th className="h-10 px-3 text-left text-xs font-medium text-muted-foreground">
PlayerID
</th>
<th className="h-10 px-3 text-left text-xs font-medium text-muted-foreground">
</th>
<th className="h-10 px-3 text-left text-xs font-medium text-muted-foreground">
</th>
</tr>
</thead>
<tbody>
{result.items.length > 0 ? (
result.items.map((player) => (
<tr
className="border-b last:border-b-0"
key={player.playerID}
>
<td className="h-11 px-3 align-middle">
<span className="font-mono text-xs tabular-nums">
{player.playerID}
</span>
</td>
<td className="h-11 px-3 align-middle">{player.name}</td>
<td className="h-11 px-3 align-middle">
<span className="font-mono text-xs">{player.enterCode}</span>
</td>
</tr>
))
) : (
<tr>
<td
className="h-24 text-center text-sm text-muted-foreground"
colSpan={3}
>
{result.q
? "검색 결과가 없습니다."
: "등록된 학생이 없습니다."}
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
);
}
function StudentPagination({
page,
pageSize,
totalPages,
onPageChange,
onPageSizeChange,
}: {
page: number;
pageSize: number;
totalPages: number;
onPageChange: (page: number) => void;
onPageSizeChange: (pageSize: number) => void;
}) {
const showNav = totalPages > 1;
const paginationItems = buildPaginationItems(page, totalPages);
const firstVisiblePage = paginationItems[0] ?? 1;
const lastVisiblePage = paginationItems.at(-1) ?? totalPages;
const hasFirstPage = paginationItems.includes(1);
const hasLastPage = paginationItems.includes(totalPages);
const hasPreviousPageGroup = firstVisiblePage > 1;
const hasNextPageGroup = lastVisiblePage < totalPages;
return (
<div className="mt-3 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<label className="flex items-center gap-2">
<span className="text-sm text-muted-foreground"></span>
<select
className="h-7 rounded-md border bg-background px-2 text-sm outline-none transition-colors focus:border-ring focus:ring-3 focus:ring-ring/30"
onChange={(e) => onPageSizeChange(Number(e.target.value))}
value={pageSize}
>
{[10, 20, 50].map((size) => (
<option key={size} value={size}>
{size}
</option>
))}
</select>
<span className="text-sm text-muted-foreground"> </span>
</label>
{showNav ? <nav
aria-label="학생 목록 페이지"
className="flex flex-wrap items-center gap-1.5"
>
{!hasFirstPage ? (
<Button
aria-label="처음 페이지"
className={buttonVariants({ variant: "outline", size: "icon-sm" })}
onClick={() => onPageChange(1)}
type="button"
>
<ChevronsLeft aria-hidden="true" className="size-4" />
</Button>
) : null}
{hasPreviousPageGroup ? (
<Button
aria-label="이전 5페이지"
className={buttonVariants({ variant: "outline", size: "icon-sm" })}
onClick={() => onPageChange(Math.max(1, page - 5))}
type="button"
>
<ChevronLeft aria-hidden="true" className="size-4" />
</Button>
) : null}
{paginationItems.map((item) => (
<Button
aria-current={item === page ? "page" : undefined}
className={cn(
buttonVariants({
variant: item === page ? "default" : "outline",
size: "sm",
}),
"min-w-8 px-2"
)}
key={item}
onClick={() => onPageChange(item)}
type="button"
>
{item}
</Button>
))}
{hasNextPageGroup ? (
<Button
aria-label="다음 5페이지"
className={buttonVariants({ variant: "outline", size: "icon-sm" })}
onClick={() => onPageChange(Math.min(totalPages, page + 5))}
type="button"
>
<ChevronRight aria-hidden="true" className="size-4" />
</Button>
) : null}
{!hasLastPage ? (
<Button
aria-label="끝 페이지"
className={buttonVariants({ variant: "outline", size: "icon-sm" })}
onClick={() => onPageChange(totalPages)}
type="button"
>
<ChevronsRight aria-hidden="true" className="size-4" />
</Button>
) : null}
</nav> : null}
</div>
);
}
function buildPaginationItems(currentPage: number, totalPages: number) {
const startPage = Math.max(1, currentPage - 2);
const endPage = Math.min(totalPages, currentPage + 2);
return Array.from(
{ length: endPage - startPage + 1 },
(_, index) => startPage + index
);
}
+7 -65
View File
@@ -11,6 +11,8 @@ import {
getActivateStatusLabel,
getRequestStatusLabel,
} from "@/lib/utils";
import { MaestroEditForm } from "./MaestroEditForm";
import { StudentsSection } from "./StudentsSection";
type MaestroDetailPageProps = {
params: Promise<{
@@ -81,65 +83,14 @@ export default async function MaestroDetailPage({
<section className="rounded-lg border bg-background p-5">
<h2 className="text-base font-semibold"> </h2>
<dl className="mt-4 grid gap-x-8 gap-y-4 text-sm md:grid-cols-2 xl:grid-cols-3">
<InfoItem label="이름" value={maestro.name} />
<InfoItem label="이메일" value={maestro.email} />
<InfoItem
label="상태"
value={getActivateStatusLabel(maestro.activateStatus)}
/>
<InfoItem
label="계정 유형"
value={getAccountTypeLabel(maestro.accountType)}
/>
<InfoItem
label="DB 학생 수"
value={detail.counts.players.toLocaleString()}
/>
<InfoItem
label="PlayerCount"
value={maestro.playerCount.toLocaleString()}
/>
<InfoItem
label="사용 가능일"
value={formatDateTime(maestro.availableActivateDateTime)}
/>
<InfoItem
label="약관 동의일"
value={formatDateTime(maestro.acceptClausesDateTime)}
/>
<InfoItem
label="입장코드 수정"
value={maestro.allowEditEnterCode === 1 ? "허용" : "비허용"}
/>
<InfoItem
label="체험 MaestroID"
value={maestro.maestroTestID?.toString() ?? "-"}
/>
</dl>
</section>
<section className="rounded-lg border bg-background p-5">
<div className="flex items-end justify-between gap-3">
<div>
<h2 className="text-base font-semibold"> </h2>
<p className="mt-1 text-sm text-muted-foreground">
{detail.counts.players.toLocaleString()} 20
</p>
</div>
</div>
<SimpleTable
emptyText="등록된 학생이 없습니다."
headers={["PlayerID", "이름", "입장코드", "AccountType"]}
rows={detail.players.map((player) => [
player.playerID,
player.name,
player.enterCode,
player.accountType ?? "-",
])}
<MaestroEditForm
maestro={detail.maestro}
playerCount={detail.counts.players}
/>
</section>
<StudentsSection maestroID={maestroID} />
<div className="grid gap-4 xl:grid-cols-2">
<section className="rounded-lg border bg-background p-5">
<h2 className="text-base font-semibold"> </h2>
@@ -207,15 +158,6 @@ function SummaryCard({ label, value }: { label: string; value: string }) {
);
}
function InfoItem({ label, value }: { label: string; value: string }) {
return (
<div>
<dt className="text-xs font-medium text-muted-foreground">{label}</dt>
<dd className="mt-1 break-words font-medium">{value}</dd>
</div>
);
}
function SimpleTable({
headers,
rows,
+22 -21
View File
@@ -73,7 +73,7 @@ export default async function MaestrosPage({
</div>
<form
className="grid grid-cols-1 gap-3 rounded-lg border bg-background p-4 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-[minmax(220px,1fr)_160px_180px_190px_110px_auto]"
className="grid grid-cols-1 gap-3 rounded-lg border bg-background p-4 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-[minmax(220px,1fr)_160px_180px_190px_auto]"
method="get"
>
<label className="min-w-0 space-y-1.5">
@@ -148,23 +148,6 @@ export default async function MaestrosPage({
</AutoSubmitSelect>
</label>
<label className="min-w-0 space-y-1.5">
<span className="text-xs font-medium text-muted-foreground">
</span>
<AutoSubmitSelect
className="h-9 w-full min-w-0 rounded-md border bg-background px-3 text-sm outline-none transition-colors focus:border-ring focus:ring-3 focus:ring-ring/30"
name="pageSize"
value={result.pageSize}
>
{[10, 20, 50, 100].map((pageSize) => (
<option key={pageSize} value={pageSize}>
{pageSize}
</option>
))}
</AutoSubmitSelect>
</label>
<div className="flex min-w-0 flex-wrap items-end gap-2 sm:col-span-2 xl:col-span-1">
<Button className="h-9" type="submit">
@@ -185,9 +168,27 @@ export default async function MaestrosPage({
<MaestrosTable data={result.items} />
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<p className="text-sm text-muted-foreground">
{result.pageSize}
</p>
<form className="flex items-center gap-2" method="get">
{Object.entries(params).flatMap(([key, value]) => {
if (key === "page" || key === "pageSize") return [];
const v = Array.isArray(value) ? value[0] : value;
if (!v) return [];
return [<input key={key} name={key} type="hidden" value={v} />];
})}
<span className="text-sm text-muted-foreground"></span>
<AutoSubmitSelect
className="h-7 rounded-md border bg-background px-2 text-sm outline-none transition-colors focus:border-ring focus:ring-3 focus:ring-ring/30"
name="pageSize"
value={result.pageSize}
>
{[10, 20, 50, 100].map((size) => (
<option key={size} value={size}>
{size}
</option>
))}
</AutoSubmitSelect>
<span className="text-sm text-muted-foreground"> </span>
</form>
<nav
aria-label="마에스트로 목록 페이지"
className="flex flex-wrap items-center gap-1.5"