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
+258
View File
@@ -2,6 +2,8 @@ import { z } from "zod";
import { db } from "@/lib/db";
import { logger } from "@/lib/logger";
import { ApiError } from "@/lib/errors";
import { ACTIVATE_STATUSES, ACCOUNT_TYPES } from "@/lib/constants";
import type { Prisma } from "@/lib/generated/prisma/client";
const pageSizeOptions = [10, 20, 50, 100] as const;
@@ -102,6 +104,262 @@ export type MaestroDetail = {
}>;
};
const paidAccountTypeValues = [
ACCOUNT_TYPES.BASIC_20,
ACCOUNT_TYPES.STANDARD_50,
ACCOUNT_TYPES.PRO_100,
ACCOUNT_TYPES.SCHOOL_500,
ACCOUNT_TYPES.SCHOOL_1000,
] as const;
const activateStatusValues = [
ACTIVATE_STATUSES.PENDING,
ACTIVATE_STATUSES.TRIAL,
ACTIVATE_STATUSES.ACTIVE,
ACTIVATE_STATUSES.CANCELED,
] as const;
export const updateMaestroSchema = z.object({
name: z.string().trim().min(1).max(50).optional(),
email: z.string().trim().email().max(50).optional(),
activateStatus: z.coerce
.number()
.int()
.refine((v) => (activateStatusValues as readonly number[]).includes(v))
.optional(),
accountType: z.coerce
.number()
.int()
.refine((v) => (paidAccountTypeValues as readonly number[]).includes(v))
.optional(),
availableActivateDateTime: z.string().min(1).optional(),
allowEditEnterCode: z.coerce.number().int().min(0).max(1).optional(),
});
export type UpdateMaestroPayload = z.infer<typeof updateMaestroSchema>;
export async function updateMaestro(
maestroID: number,
payload: UpdateMaestroPayload
): Promise<{ changed: boolean } | null> {
const t0 = Date.now();
const maestro = await db.maestro.findUnique({
where: { MaestroID: maestroID },
select: {
Name: true,
Email: true,
ActivateStatus: true,
AccountType: true,
AvailableActivateDateTime: true,
AllowEditEnterCode: true,
},
});
if (!maestro) return null;
if (payload.name !== undefined && payload.name !== maestro.Name.trim()) {
const conflict = await db.maestro.findFirst({
where: { Name: payload.name, NOT: { MaestroID: maestroID } },
select: { MaestroID: true },
});
if (conflict) {
throw new ApiError("이미 사용 중인 이름입니다.", 409);
}
}
const updates: {
Name?: string;
Email?: string;
ActivateStatus?: number;
AccountType?: number;
AvailableActivateDateTime?: Date;
AllowEditEnterCode?: number;
} = {};
const logs: Array<{ type: string; remark: string }> = [];
if (payload.name !== undefined && payload.name !== maestro.Name.trim()) {
updates.Name = payload.name;
logs.push({
type: "update_maestro_name",
remark: `${maestro.Name.trim()} -> ${payload.name}`.slice(0, 100),
});
}
if (payload.email !== undefined && payload.email !== maestro.Email.trim()) {
updates.Email = payload.email;
logs.push({
type: "update_maestro_email",
remark: `${maestro.Email.trim()} -> ${payload.email}`.slice(0, 100),
});
}
if (
payload.activateStatus !== undefined &&
payload.activateStatus !== maestro.ActivateStatus
) {
updates.ActivateStatus = payload.activateStatus;
logs.push({
type: "update_maestro_status",
remark: `${maestro.ActivateStatus} -> ${payload.activateStatus}`,
});
}
if (
payload.accountType !== undefined &&
payload.accountType !== maestro.AccountType
) {
updates.AccountType = payload.accountType;
logs.push({
type: "update_maestro_account_type",
remark: `${maestro.AccountType} -> ${payload.accountType}`,
});
}
if (payload.availableActivateDateTime !== undefined) {
const newDate = new Date(payload.availableActivateDateTime);
if (!isNaN(newDate.getTime())) {
const prevMin = Math.floor(
maestro.AvailableActivateDateTime.getTime() / 60000
);
const newMin = Math.floor(newDate.getTime() / 60000);
if (prevMin !== newMin) {
updates.AvailableActivateDateTime = newDate;
const prevStr = maestro.AvailableActivateDateTime.toISOString().slice(
0,
10
);
const newStr = newDate.toISOString().slice(0, 10);
logs.push({
type: "update_maestro_available_date",
remark: `${prevStr} -> ${newStr}`,
});
}
}
}
if (
payload.allowEditEnterCode !== undefined &&
payload.allowEditEnterCode !== maestro.AllowEditEnterCode
) {
updates.AllowEditEnterCode = payload.allowEditEnterCode;
logs.push({
type: "update_maestro_allow_enter_code",
remark: `${maestro.AllowEditEnterCode} -> ${payload.allowEditEnterCode}`,
});
}
if (Object.keys(updates).length === 0) {
return { changed: false };
}
await db.$transaction([
db.maestro.update({ where: { MaestroID: maestroID }, data: updates }),
...logs.map((log) =>
db.maestro_log.create({
data: {
Type: log.type,
MaestroID: maestroID,
LogDateTime: new Date(),
Remark: log.remark,
},
})
),
]);
logger.info("maestros/[id]", "updated", {
id: maestroID,
fields: Object.keys(updates),
duration: Date.now() - t0,
});
return { changed: true };
}
const studentPageSizeOptions = [10, 20, 50] as const;
type StudentPageSize = (typeof studentPageSizeOptions)[number];
const studentSearchSchema = z.object({
page: z.coerce.number().int().min(1).catch(1),
pageSize: z.coerce
.number()
.int()
.refine((v) => studentPageSizeOptions.includes(v as StudentPageSize))
.catch(20),
q: z.string().trim().catch(""),
});
export type MaestroStudentsResult = {
items: Array<{
playerID: number;
name: string;
enterCode: string;
accountType: number | null;
}>;
page: number;
pageSize: number;
totalCount: number;
totalPages: number;
q: string;
};
export async function getMaestroStudents(
maestroID: number,
rawSearchParams: RawSearchParams = {}
): Promise<MaestroStudentsResult | null> {
const t0 = Date.now();
const maestroExists = await db.maestro.findUnique({
where: { MaestroID: maestroID },
select: { MaestroID: true },
});
if (!maestroExists) return null;
const params = studentSearchSchema.parse(searchParamsToRecord(rawSearchParams));
const skip = (params.page - 1) * params.pageSize;
const where: Prisma.playerWhereInput = {
MaestroID: maestroID,
...(params.q ? { Name: { contains: params.q } } : {}),
};
const [totalCount, players] = await Promise.all([
db.player.count({ where }),
db.player.findMany({
where,
orderBy: { PlayerID: "desc" },
skip,
take: params.pageSize,
select: {
PlayerID: true,
Name: true,
EnterCode: true,
AccountType: true,
},
}),
]);
const totalPages = Math.max(1, Math.ceil(totalCount / params.pageSize));
logger.debug("maestros/[id]/students", "fetched", {
id: maestroID,
q: params.q,
page: params.page,
totalCount,
duration: Date.now() - t0,
});
return {
items: players.map((p) => ({
playerID: p.PlayerID,
name: p.Name.trim(),
enterCode: p.EnterCode.trim(),
accountType: p.AccountType,
})),
page: params.page,
pageSize: params.pageSize,
totalCount,
totalPages,
q: params.q,
};
}
export async function getMaestros(
rawSearchParams: RawSearchParams = {}
): Promise<MaestroListResult> {
+16
View File
@@ -104,6 +104,22 @@ export function calculateExtendedAvailableDate(
return extendedDate;
}
export function toDatetimeLocal(value: Date | string | null | undefined): string {
const date = toDate(value);
if (!date) {
return "";
}
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
return `${year}-${month}-${day}T${hours}:${minutes}`;
}
function toDate(value: Date | string | null | undefined): Date | null {
if (!value) {
return null;