Phase 4. 마에스트로 목록 화면 구현

This commit is contained in:
2026-06-10 22:22:45 +09:00
parent dbf9b3e180
commit fbe4caa9e1
8 changed files with 1226 additions and 4 deletions
+273
View File
@@ -0,0 +1,273 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft } from "lucide-react";
import { buttonVariants } from "@/components/ui/button";
import { getMaestroDetail } from "@/lib/maestros";
import {
formatDate,
formatDateTime,
getAccountTypeLabel,
getActivateStatusLabel,
getRequestStatusLabel,
} from "@/lib/utils";
type MaestroDetailPageProps = {
params: Promise<{
maestroId: string;
}>;
};
export default async function MaestroDetailPage({
params,
}: MaestroDetailPageProps) {
const { maestroId } = await params;
const maestroID = Number(maestroId);
if (!Number.isInteger(maestroID) || maestroID <= 0) {
notFound();
}
const detail = await getMaestroDetail(maestroID);
if (!detail) {
notFound();
}
const { maestro } = detail;
return (
<section className="space-y-5">
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
<div>
<Link
className={buttonVariants({
variant: "ghost",
size: "sm",
className: "mb-2 -ml-2",
})}
href="/maestros"
>
<ArrowLeft className="size-4" aria-hidden="true" />
</Link>
<h1 className="text-2xl font-semibold tracking-normal">
{maestro.name}
</h1>
<p className="mt-1 text-sm text-muted-foreground">
MaestroID {maestro.maestroID} · {maestro.email}
</p>
</div>
</div>
<div className="grid gap-4 lg:grid-cols-4">
<SummaryCard
label="상태"
value={getActivateStatusLabel(maestro.activateStatus)}
/>
<SummaryCard
label="계정 유형"
value={getAccountTypeLabel(maestro.accountType)}
/>
<SummaryCard
label="학생 수"
value={detail.counts.players.toLocaleString()}
/>
<SummaryCard
label="사용 가능일"
value={formatDate(maestro.availableActivateDateTime)}
/>
</div>
<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 ?? "-",
])}
/>
</section>
<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>
<p className="mt-1 text-sm text-muted-foreground">
{detail.counts.extensionRequests.toLocaleString()}
20
</p>
<SimpleTable
emptyText="연장 신청 이력이 없습니다."
headers={["신청ID", "계정 유형", "신청일시", "상태"]}
rows={detail.extensionRequests.map((request) => [
request.maestroExtensionID,
getAccountTypeLabel(request.accountType),
formatDateTime(request.requestedDateTime),
getRequestStatusLabel(request.status),
])}
/>
</section>
<section className="rounded-lg border bg-background p-5">
<h2 className="text-base font-semibold"> </h2>
<p className="mt-1 text-sm text-muted-foreground">
{detail.counts.upgradeRequests.toLocaleString()} 20
</p>
<SimpleTable
emptyText="업그레이드 신청 이력이 없습니다."
headers={["신청ID", "현재", "요청", "신청일시", "상태"]}
rows={detail.upgradeRequests.map((request) => [
request.maestroUpgradeID,
getAccountTypeLabel(request.registeredAccountType),
getAccountTypeLabel(request.requestedAccountType),
formatDateTime(request.requestedDateTime),
getRequestStatusLabel(request.status),
])}
/>
</section>
</div>
<section className="rounded-lg border bg-background p-5">
<h2 className="text-base font-semibold"> </h2>
<p className="mt-1 text-sm text-muted-foreground">
{detail.counts.logs.toLocaleString()} 30
</p>
<SimpleTable
emptyText="처리 로그가 없습니다."
headers={["LogID", "유형", "처리일시", "내용"]}
rows={detail.logs.map((log) => [
log.maestroLogID,
log.type,
formatDateTime(log.logDateTime),
log.remark,
])}
/>
</section>
</section>
);
}
function SummaryCard({ label, value }: { label: string; value: string }) {
return (
<article className="rounded-lg border bg-background p-4">
<p className="text-xs font-medium text-muted-foreground">{label}</p>
<p className="mt-2 text-lg font-semibold">{value}</p>
</article>
);
}
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,
emptyText,
}: {
headers: string[];
rows: Array<Array<string | number>>;
emptyText: string;
}) {
return (
<div className="mt-4 overflow-hidden rounded-lg border">
<div className="overflow-x-auto">
<table className="w-full min-w-[560px] border-collapse text-sm">
<thead className="bg-muted/60">
<tr className="border-b">
{headers.map((header) => (
<th
className="h-10 px-3 text-left text-xs font-medium text-muted-foreground"
key={header}
>
{header}
</th>
))}
</tr>
</thead>
<tbody>
{rows.length > 0 ? (
rows.map((row, index) => (
<tr className="border-b last:border-b-0" key={index}>
{row.map((cell, cellIndex) => (
<td
className="h-11 max-w-[360px] break-words px-3 align-middle"
key={cellIndex}
>
{cell}
</td>
))}
</tr>
))
) : (
<tr>
<td
className="h-24 px-3 text-center text-sm text-muted-foreground"
colSpan={headers.length}
>
{emptyText}
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
);
}
+295
View File
@@ -0,0 +1,295 @@
import Link from "next/link";
import {
ChevronLeft,
ChevronRight,
ChevronsLeft,
ChevronsRight,
Search,
} from "lucide-react";
import { Button, buttonVariants } from "@/components/ui/button";
import { MaestrosTable } from "@/components/data-table/maestros-table";
import { AutoSubmitSelect } from "@/components/forms/auto-submit-select";
import {
ACCOUNT_TYPE_LABELS,
ACCOUNT_TYPES,
ACTIVATE_STATUS_LABELS,
ACTIVATE_STATUSES,
} from "@/lib/constants";
import { getMaestros, type RawSearchParams } from "@/lib/maestros";
import { cn } from "@/lib/utils";
type MaestrosPageProps = {
searchParams: Promise<RawSearchParams>;
};
const activateStatusOptions = [
ACTIVATE_STATUSES.PENDING,
ACTIVATE_STATUSES.TRIAL,
ACTIVATE_STATUSES.ACTIVE,
ACTIVATE_STATUSES.CANCELED,
] as const;
const accountTypeOptions = [
ACCOUNT_TYPES.BASIC_20,
ACCOUNT_TYPES.STANDARD_50,
ACCOUNT_TYPES.PRO_100,
ACCOUNT_TYPES.SCHOOL_500,
ACCOUNT_TYPES.SCHOOL_1000,
] as const;
const sortOptions = [
{ value: "id-desc", label: "ID 최신순" },
{ value: "id-asc", label: "ID 오래된순" },
{ value: "joinedAt-desc", label: "가입일 최신순" },
{ value: "joinedAt-asc", label: "가입일 오래된순" },
{ value: "availableAt-desc", label: "사용 가능일 최신순" },
{ value: "availableAt-asc", label: "사용 가능일 오래된순" },
] as const;
export default async function MaestrosPage({
searchParams,
}: MaestrosPageProps) {
const params = await searchParams;
const result = await getMaestros(params);
const paginationItems = buildPaginationItems(result.page, result.totalPages);
const firstVisiblePage = paginationItems[0] ?? 1;
const lastVisiblePage = paginationItems.at(-1) ?? result.totalPages;
const hasFirstPage = paginationItems.includes(1);
const hasLastPage = paginationItems.includes(result.totalPages);
const hasPreviousPageGroup = firstVisiblePage > 1;
const hasNextPageGroup = lastVisiblePage < result.totalPages;
return (
<section className="space-y-5">
<div className="flex flex-col gap-1 sm:flex-row sm:items-end sm:justify-between">
<div>
<h1 className="text-2xl font-semibold tracking-normal"></h1>
<p className="mt-1 text-sm text-muted-foreground">
{result.totalCount.toLocaleString()} {result.page} /{" "}
{result.totalPages}
</p>
</div>
</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]"
method="get"
>
<label className="min-w-0 space-y-1.5">
<span className="text-xs font-medium text-muted-foreground">
</span>
<div className="relative min-w-0">
<Search
className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"
aria-hidden="true"
/>
<input
className="h-9 w-full min-w-0 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"
defaultValue={result.q}
name="q"
placeholder="이름, 이메일, ID"
type="search"
/>
</div>
</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="activateStatus"
value={result.activateStatus ?? "all"}
>
<option value="all"></option>
{activateStatusOptions.map((status) => (
<option key={status} value={status}>
{ACTIVATE_STATUS_LABELS[status]}
</option>
))}
</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="accountType"
value={result.accountType ?? "all"}
>
<option value="all"></option>
{accountTypeOptions.map((accountType) => (
<option key={accountType} value={accountType}>
{ACCOUNT_TYPE_LABELS[accountType]}
</option>
))}
</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="sort"
value={result.sort}
>
{sortOptions.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</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">
</Button>
<Link
className={buttonVariants({
variant: "outline",
size: "default",
className: "h-9",
})}
href="/maestros"
>
</Link>
</div>
</form>
<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>
<nav
aria-label="마에스트로 목록 페이지"
className="flex flex-wrap items-center gap-1.5"
>
{!hasFirstPage ? (
<Link
aria-label="처음 페이지"
className={buttonVariants({
variant: "outline",
size: "icon-sm",
})}
href={buildPageHref(params, 1)}
>
<ChevronsLeft className="size-4" aria-hidden="true" />
</Link>
) : null}
{hasPreviousPageGroup ? (
<Link
aria-label="이전 5페이지"
className={buttonVariants({
variant: "outline",
size: "icon-sm",
})}
href={buildPageHref(params, Math.max(1, result.page - 5))}
>
<ChevronLeft className="size-4" aria-hidden="true" />
</Link>
) : null}
{paginationItems.map((item) => (
<Link
aria-current={item === result.page ? "page" : undefined}
className={cn(
buttonVariants({
variant: item === result.page ? "default" : "outline",
size: "sm",
}),
"min-w-8 px-2"
)}
href={buildPageHref(params, item)}
key={item}
>
{item}
</Link>
))}
{hasNextPageGroup ? (
<Link
aria-label="다음 5페이지"
className={buttonVariants({
variant: "outline",
size: "icon-sm",
})}
href={buildPageHref(
params,
Math.min(result.totalPages, result.page + 5)
)}
>
<ChevronRight className="size-4" aria-hidden="true" />
</Link>
) : null}
{!hasLastPage ? (
<Link
aria-label="끝 페이지"
className={buttonVariants({
variant: "outline",
size: "icon-sm",
})}
href={buildPageHref(params, result.totalPages)}
>
<ChevronsRight className="size-4" aria-hidden="true" />
</Link>
) : null}
</nav>
</div>
</section>
);
}
function buildPageHref(rawParams: RawSearchParams, page: number) {
const params = new URLSearchParams();
Object.entries(rawParams).forEach(([key, value]) => {
const firstValue = Array.isArray(value) ? value[0] : value;
if (firstValue && key !== "page") {
params.set(key, firstValue);
}
});
params.set("page", String(Math.max(1, page)));
return `/maestros?${params.toString()}`;
}
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
);
}
+39
View File
@@ -0,0 +1,39 @@
import { NextResponse } from "next/server";
import { auth } from "@/auth";
import { getMaestroDetail } from "@/lib/maestros";
type MaestroDetailRouteContext = {
params: Promise<{
id: string;
}>;
};
export async function GET(
_request: Request,
{ params }: MaestroDetailRouteContext
) {
const session = await auth();
if (!session) {
return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
}
const { id } = await params;
const maestroID = Number(id);
if (!Number.isInteger(maestroID) || maestroID <= 0) {
return NextResponse.json(
{ message: "Invalid maestro id" },
{ status: 400 }
);
}
const result = await getMaestroDetail(maestroID);
if (!result) {
return NextResponse.json({ message: "Not found" }, { status: 404 });
}
return NextResponse.json(result);
}
+17
View File
@@ -0,0 +1,17 @@
import { NextResponse } from "next/server";
import { auth } from "@/auth";
import { getMaestros } from "@/lib/maestros";
export async function GET(request: Request) {
const session = await auth();
if (!session) {
return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
}
const url = new URL(request.url);
const result = await getMaestros(url.searchParams);
return NextResponse.json(result);
}
+208
View File
@@ -0,0 +1,208 @@
"use client";
import { useRouter } from "next/navigation";
import {
flexRender,
getCoreRowModel,
type ColumnDef,
useReactTable,
} from "@tanstack/react-table";
import { useMemo } from "react";
import type { MaestroListItem } from "@/lib/maestros";
import { cn } from "@/lib/utils";
import {
formatDate,
getAccountTypeLabel,
getActivateStatusLabel,
} from "@/lib/utils";
type MaestrosTableProps = {
data: MaestroListItem[];
};
export function MaestrosTable({ data }: MaestrosTableProps) {
const router = useRouter();
const columns = useMemo<ColumnDef<MaestroListItem>[]>(
() => [
{
accessorKey: "maestroID",
header: "ID",
cell: ({ row }) => (
<span className="font-mono text-xs tabular-nums">
{row.original.maestroID}
</span>
),
},
{
accessorKey: "name",
header: "이름",
cell: ({ row }) => (
<div className="min-w-32">
<p className="font-medium">{row.original.name}</p>
<p className="mt-1 text-xs text-muted-foreground md:hidden">
{row.original.email}
</p>
</div>
),
},
{
accessorKey: "email",
header: "이메일",
cell: ({ row }) => (
<span className="text-muted-foreground">{row.original.email}</span>
),
},
{
accessorKey: "accountType",
header: "계정 유형",
cell: ({ row }) => getAccountTypeLabel(row.original.accountType),
},
{
accessorKey: "activateStatus",
header: "상태",
cell: ({ row }) => (
<span
className={cn(
"inline-flex h-6 items-center rounded-md border px-2 text-xs font-medium",
getActivateStatusBadgeClass(row.original)
)}
>
{getActivateStatusLabel(row.original.activateStatus)}
</span>
),
},
{
accessorKey: "playerCount",
header: "학생 수",
cell: ({ row }) => (
<span className="tabular-nums">
{row.original.playerCount.toLocaleString()}
</span>
),
},
{
accessorKey: "acceptClausesDateTime",
header: "가입일",
cell: ({ row }) => formatDate(row.original.acceptClausesDateTime),
},
{
accessorKey: "availableActivateDateTime",
header: "사용 가능일",
cell: ({ row }) => formatDate(row.original.availableActivateDateTime),
},
],
[]
);
// TanStack Table manages internal functions that React Compiler should not memoize.
// eslint-disable-next-line react-hooks/incompatible-library
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
});
return (
<div className="overflow-hidden rounded-lg border bg-background">
<div className="overflow-x-auto">
<table className="w-full min-w-[980px] border-collapse text-sm">
<thead className="bg-muted/60">
{table.getHeaderGroups().map((headerGroup) => (
<tr className="border-b" key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<th
className="h-10 px-3 text-left text-xs font-medium text-muted-foreground"
key={header.id}
>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</th>
))}
</tr>
))}
</thead>
<tbody>
{table.getRowModel().rows.length > 0 ? (
table.getRowModel().rows.map((row) => (
<tr
aria-label={`${row.original.name} 마에스트로 상세 보기`}
className="cursor-pointer border-b transition-colors last:border-b-0 hover:bg-muted/60 focus-visible:bg-muted/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
key={row.id}
onClick={() => {
router.push(`/maestros/${row.original.maestroID}`);
}}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
router.push(`/maestros/${row.original.maestroID}`);
}
}}
role="link"
tabIndex={0}
>
{row.getVisibleCells().map((cell) => (
<td className="h-12 px-3 align-middle" key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</td>
))}
</tr>
))
) : (
<tr>
<td
className="h-28 px-3 text-center text-sm text-muted-foreground"
colSpan={columns.length}
>
.
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
);
}
function getActivateStatusBadgeClass(maestro: MaestroListItem) {
if (
maestro.activateStatus === 2 &&
isBeforeToday(maestro.availableActivateDateTime)
) {
return "border-rose-200 bg-rose-50 text-rose-700";
}
if (maestro.activateStatus === 2) {
return "border-emerald-200 bg-emerald-50 text-emerald-700";
}
if (maestro.activateStatus === 100) {
return "border-muted bg-muted text-muted-foreground";
}
return "border-amber-200 bg-amber-50 text-amber-700";
}
function isBeforeToday(value: string) {
const date = new Date(value);
if (Number.isNaN(date.getTime())) {
return false;
}
const targetDate = new Date(date);
const today = new Date();
targetDate.setHours(0, 0, 0, 0);
today.setHours(0, 0, 0, 0);
return targetDate.getTime() < today.getTime();
}
+20
View File
@@ -0,0 +1,20 @@
"use client";
import type { ComponentProps } from "react";
type AutoSubmitSelectProps = ComponentProps<"select">;
export function AutoSubmitSelect({
onChange,
...props
}: AutoSubmitSelectProps) {
return (
<select
{...props}
onChange={(event) => {
onChange?.(event);
event.currentTarget.form?.requestSubmit();
}}
/>
);
}
+4 -4
View File
@@ -325,10 +325,10 @@ choco-admin/
### Phase 4. 마에스트로 목록 및 상세
- [ ] 마에스트로 목록 API (`GET /api/maestros`) — 검색·필터·페이지네이션 포함
- [ ] TanStack Table 기반 목록 화면
- [ ] 마에스트로 상세 API (`GET /api/maestros/[id]`)
- [ ] 상세 화면 — 연장/업그레이드 이력, 학생 목록 요약, 처리 로그
- [x] 마에스트로 목록 API (`GET /api/maestros`) — 검색·필터·페이지네이션 포함
- [x] TanStack Table 기반 목록 화면
- [x] 마에스트로 상세 API (`GET /api/maestros/[id]`)
- [x] 상세 화면 — 연장/업그레이드 이력, 학생 목록 요약, 처리 로그
### Phase 5. 연장 신청 관리
+370
View File
@@ -0,0 +1,370 @@
import { z } from "zod";
import { db } from "@/lib/db";
import type { Prisma } from "@/lib/generated/prisma/client";
const pageSizeOptions = [10, 20, 50, 100] as const;
const sortOptions = [
"id-desc",
"id-asc",
"joinedAt-desc",
"joinedAt-asc",
"availableAt-desc",
"availableAt-asc",
] as const;
const maestroListSearchSchema = z.object({
page: z.coerce.number().int().min(1).catch(1),
pageSize: z.coerce
.number()
.int()
.refine((value) => pageSizeOptions.includes(value as PageSize))
.catch(10),
q: z.string().trim().catch(""),
activateStatus: z
.union([z.literal("all"), z.coerce.number().int().min(0)])
.optional()
.catch(undefined),
accountType: z
.union([z.literal("all"), z.coerce.number().int().min(0)])
.optional()
.catch(undefined),
sort: z.enum(sortOptions).catch("id-desc"),
});
type PageSize = (typeof pageSizeOptions)[number];
export type MaestroSort = (typeof sortOptions)[number];
export type MaestroListSearchParams = z.infer<typeof maestroListSearchSchema>;
export type RawSearchParams =
| URLSearchParams
| Record<string, string | string[] | undefined>;
export type MaestroListItem = {
maestroID: number;
name: string;
email: string;
accountType: number;
activateStatus: number;
availableActivateDateTime: string;
acceptClausesDateTime: string;
playerCount: number;
};
export type MaestroListResult = {
items: MaestroListItem[];
page: number;
pageSize: number;
totalCount: number;
totalPages: number;
q: string;
activateStatus?: number | "all";
accountType?: number | "all";
sort: MaestroSort;
};
export type MaestroDetail = {
maestro: MaestroListItem & {
allowEditEnterCode: number;
maestroTestID: number | null;
};
counts: {
players: number;
extensionRequests: number;
upgradeRequests: number;
logs: number;
};
players: Array<{
playerID: number;
name: string;
enterCode: string;
accountType: number | null;
}>;
extensionRequests: Array<{
maestroExtensionID: number;
accountType: number;
requestedDateTime: string;
status: number;
}>;
upgradeRequests: Array<{
maestroUpgradeID: number;
registeredActivateStatus: number;
registeredAccountType: number;
requestedAccountType: number;
requestedDateTime: string;
status: number;
}>;
logs: Array<{
maestroLogID: number;
type: string;
logDateTime: string;
remark: string;
}>;
};
export async function getMaestros(
rawSearchParams: RawSearchParams = {}
): Promise<MaestroListResult> {
const params = parseMaestroListSearchParams(rawSearchParams);
const where = buildMaestroWhere(params);
const orderBy = buildMaestroOrderBy(params.sort);
const skip = (params.page - 1) * params.pageSize;
const [totalCount, maestros] = await Promise.all([
db.maestro.count({ where }),
db.maestro.findMany({
where,
orderBy,
skip,
take: params.pageSize,
select: {
MaestroID: true,
Name: true,
Email: true,
AccountType: true,
ActivateStatus: true,
AvailableActivateDateTime: true,
AcceptClausesDateTime: true,
PlayerCount: true,
},
}),
]);
const totalPages = Math.max(1, Math.ceil(totalCount / params.pageSize));
return {
items: maestros.map(toMaestroListItem),
page: params.page,
pageSize: params.pageSize,
totalCount,
totalPages,
q: params.q,
activateStatus: params.activateStatus,
accountType: params.accountType,
sort: params.sort,
};
}
export async function getMaestroDetail(
maestroID: number
): Promise<MaestroDetail | null> {
const maestro = await db.maestro.findUnique({
where: { MaestroID: maestroID },
select: {
MaestroID: true,
Name: true,
Email: true,
AccountType: true,
ActivateStatus: true,
AvailableActivateDateTime: true,
AcceptClausesDateTime: true,
PlayerCount: true,
AllowEditEnterCode: true,
MaestroTestID: true,
},
});
if (!maestro) {
return null;
}
const [
playersCount,
extensionRequestsCount,
upgradeRequestsCount,
logsCount,
players,
extensionRequests,
upgradeRequests,
logs,
] = await Promise.all([
db.player.count({ where: { MaestroID: maestroID } }),
db.maestro_extension.count({ where: { MaestroID: maestroID } }),
db.maestro_upgrade.count({ where: { MaestroID: maestroID } }),
db.maestro_log.count({ where: { MaestroID: maestroID } }),
db.player.findMany({
where: { MaestroID: maestroID },
orderBy: { PlayerID: "desc" },
take: 20,
select: {
PlayerID: true,
Name: true,
EnterCode: true,
AccountType: true,
},
}),
db.maestro_extension.findMany({
where: { MaestroID: maestroID },
orderBy: { MaestroExtensionID: "desc" },
take: 20,
select: {
MaestroExtensionID: true,
AccountType: true,
RequestedDateTime: true,
Status: true,
},
}),
db.maestro_upgrade.findMany({
where: { MaestroID: maestroID },
orderBy: { MaestroUpgradeID: "desc" },
take: 20,
select: {
MaestroUpgradeID: true,
RegisteredActivateStatus: true,
RegisteredAccountType: true,
RequestedAccountType: true,
RequestedDateTime: true,
Status: true,
},
}),
db.maestro_log.findMany({
where: { MaestroID: maestroID },
orderBy: { MaestroLogID: "desc" },
take: 30,
select: {
MaestroLogID: true,
Type: true,
LogDateTime: true,
Remark: true,
},
}),
]);
return {
maestro: {
...toMaestroListItem(maestro),
allowEditEnterCode: maestro.AllowEditEnterCode,
maestroTestID: maestro.MaestroTestID,
},
counts: {
players: playersCount,
extensionRequests: extensionRequestsCount,
upgradeRequests: upgradeRequestsCount,
logs: logsCount,
},
players: players.map((player) => ({
playerID: player.PlayerID,
name: player.Name.trim(),
enterCode: player.EnterCode.trim(),
accountType: player.AccountType,
})),
extensionRequests: extensionRequests.map((request) => ({
maestroExtensionID: request.MaestroExtensionID,
accountType: request.AccountType,
requestedDateTime: request.RequestedDateTime.toISOString(),
status: request.Status,
})),
upgradeRequests: upgradeRequests.map((request) => ({
maestroUpgradeID: request.MaestroUpgradeID,
registeredActivateStatus: request.RegisteredActivateStatus,
registeredAccountType: request.RegisteredAccountType,
requestedAccountType: request.RequestedAccountType,
requestedDateTime: request.RequestedDateTime.toISOString(),
status: request.Status,
})),
logs: logs.map((log) => ({
maestroLogID: log.MaestroLogID,
type: log.Type.trim(),
logDateTime: log.LogDateTime.toISOString(),
remark: log.Remark.trim(),
})),
};
}
export function parseMaestroListSearchParams(
rawSearchParams: RawSearchParams
): MaestroListSearchParams {
return maestroListSearchSchema.parse(searchParamsToRecord(rawSearchParams));
}
function buildMaestroWhere(
params: MaestroListSearchParams
): Prisma.maestroWhereInput {
const conditions: Prisma.maestroWhereInput[] = [];
if (params.q) {
const keywordConditions: Prisma.maestroWhereInput[] = [
{ Name: { contains: params.q } },
{ Email: { contains: params.q } },
];
const numericQuery = Number(params.q);
if (Number.isInteger(numericQuery) && numericQuery > 0) {
keywordConditions.unshift({ MaestroID: numericQuery });
}
conditions.push({ OR: keywordConditions });
}
if (
typeof params.activateStatus === "number" &&
Number.isInteger(params.activateStatus)
) {
conditions.push({ ActivateStatus: params.activateStatus });
}
if (
typeof params.accountType === "number" &&
Number.isInteger(params.accountType)
) {
conditions.push({ AccountType: params.accountType });
}
return conditions.length > 0 ? { AND: conditions } : {};
}
function buildMaestroOrderBy(
sort: MaestroSort
): Prisma.maestroOrderByWithRelationInput {
switch (sort) {
case "id-asc":
return { MaestroID: "asc" };
case "joinedAt-desc":
return { AcceptClausesDateTime: "desc" };
case "joinedAt-asc":
return { AcceptClausesDateTime: "asc" };
case "availableAt-desc":
return { AvailableActivateDateTime: "desc" };
case "availableAt-asc":
return { AvailableActivateDateTime: "asc" };
case "id-desc":
default:
return { MaestroID: "desc" };
}
}
function searchParamsToRecord(
rawSearchParams: RawSearchParams
): Record<string, string | undefined> {
if (rawSearchParams instanceof URLSearchParams) {
return Object.fromEntries(rawSearchParams.entries());
}
return Object.fromEntries(
Object.entries(rawSearchParams).map(([key, value]) => [
key,
Array.isArray(value) ? value[0] : value,
])
);
}
function toMaestroListItem(maestro: {
MaestroID: number;
Name: string;
Email: string;
AccountType: number;
ActivateStatus: number;
AvailableActivateDateTime: Date;
AcceptClausesDateTime: Date;
PlayerCount: number;
}): MaestroListItem {
return {
maestroID: maestro.MaestroID,
name: maestro.Name.trim(),
email: maestro.Email.trim(),
accountType: maestro.AccountType,
activateStatus: maestro.ActivateStatus,
availableActivateDateTime: maestro.AvailableActivateDateTime.toISOString(),
acceptClausesDateTime: maestro.AcceptClausesDateTime.toISOString(),
playerCount: maestro.PlayerCount,
};
}