feat: align with upstream 1.5.9.9

This commit is contained in:
2026-09-12 18:21:11 +08:00
commit 34f0679117
805 changed files with 376275 additions and 0 deletions
+79
View File
@@ -0,0 +1,79 @@
import { createError, defineEventHandler, getRouterParam } from 'h3'
import { db } from '~/drizzle/db'
import { users } from '~/drizzle/schema'
import { eq } from 'drizzle-orm'
export default defineEventHandler(async (event) => {
try {
// 检查认证和权限
const user = event.context.user
if (!user || !['ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
throw createError({
statusCode: 403,
message: '没有权限访问'
})
}
const userId = getRouterParam(event, 'id')
// 检查用户是否存在
const existingUserResult = await db
.select()
.from(users)
.where(eq(users.id, parseInt(userId)))
.limit(1)
const existingUser = existingUserResult[0]
if (!existingUser) {
throw createError({
statusCode: 404,
message: '用户不存在'
})
}
// 1. 绝对禁止删除 ID 为 1 的用户 (系统初始超级管理员)
if (existingUser.id === 1) {
throw createError({
statusCode: 403,
message: '无法删除系统初始超级管理员'
})
}
// 2. 禁止删除自己 (增强类型安全)
// 使用 String 转换确保 ID 比较的准确性
if (String(existingUser.id) === String(user.id)) {
throw createError({
statusCode: 400,
message: '不能删除自己的账户'
})
}
// 3. 越级删除保护
// 如果目标用户是 SUPER_ADMIN,操作者必须是 SUPER_ADMIN
if (existingUser.role === 'SUPER_ADMIN' && user.role !== 'SUPER_ADMIN') {
throw createError({
statusCode: 403,
message: '权限不足:普通管理员无法删除超级管理员'
})
}
// 删除用户
await db.delete(users).where(eq(users.id, parseInt(userId)))
return {
success: true,
message: '用户删除成功'
}
} catch (error) {
console.error('删除用户失败:', error)
if (error.statusCode) {
throw error
}
throw createError({
statusCode: 500,
message: '删除用户失败:' + error.message
})
}
})
+73
View File
@@ -0,0 +1,73 @@
import { createError, defineEventHandler, getRouterParam } from 'h3'
import { eq } from 'drizzle-orm'
import { db } from '~/drizzle/db'
import { users } from '~/drizzle/schema'
import { resolveAvatarSource } from '~~/server/utils/user-avatar'
export default defineEventHandler(async (event) => {
const currentUser = event.context.user
if (!currentUser || !['ADMIN', 'SUPER_ADMIN'].includes(currentUser.role)) {
throw createError({
statusCode: 403,
message: '没有权限访问'
})
}
const userId = Number(getRouterParam(event, 'id'))
if (!Number.isInteger(userId) || userId <= 0) {
throw createError({
statusCode: 400,
message: '无效的用户ID'
})
}
const user = await db.query.users.findFirst({
where: eq(users.id, userId),
columns: {
id: true,
name: true,
username: true,
role: true,
grade: true,
class: true,
status: true,
statusChangedAt: true,
lastLogin: true,
lastLoginIp: true,
passwordChangedAt: true,
forcePasswordChange: true,
meowNickname: true,
meowBoundAt: true,
email: true,
emailVerified: true,
createdAt: true,
updatedAt: true,
avatarProvider: true,
avatarProviderUserId: true
},
with: {
identities: {
columns: {
provider: true,
providerUsername: true,
providerUserId: true,
avatar: true,
createdAt: true
}
}
}
})
if (!user) {
throw createError({
statusCode: 404,
message: '用户不存在'
})
}
const avatarSource = resolveAvatarSource(user, user.identities || [])
return {
...user,
avatar: avatarSource?.url ?? null
}
})
+262
View File
@@ -0,0 +1,262 @@
import { createError, defineEventHandler, getRouterParam, readBody } from 'h3'
import { db } from '~/drizzle/db'
import { users, userStatusLogs } from '~/drizzle/schema'
import { eq } from 'drizzle-orm'
import { updateUserPassword } from '~~/server/services/userService'
import { createSystemNotification } from '~~/server/services/notificationService'
import {
PASSWORD_AUDIT_ACTIONS,
getPasswordAuditContext
} from '~~/server/services/passwordSecurityService'
import { createApiError } from '~~/server/utils/apiError'
import { SERVER_ERROR_CODES } from '~~/server/config/constants'
import { getAdminPasswordViolation } from '~~/server/utils/admin-password-policy'
const normalizeRequiredText = (value: unknown) => String(value || '').trim()
const normalizeOptionalText = (value: unknown) => {
const normalized = String(value || '').trim()
return normalized || null
}
const roleNames: Record<string, string> = {
USER: '用户',
SONG_ADMIN: '歌曲管理员',
ADMIN: '管理员',
SUPER_ADMIN: '超级管理员'
}
export default defineEventHandler(async (event) => {
try {
// 检查认证和权限
const user = event.context.user
if (!user || !['ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
throw createError({
statusCode: 403,
message: '没有权限访问'
})
}
const userId = getRouterParam(event, 'id')
const userIdNum = Number.parseInt(String(userId), 10)
if (!Number.isInteger(userIdNum) || userIdNum <= 0) {
throw createError({
statusCode: 400,
message: '无效的用户ID'
})
}
const body = await readBody(event)
const { name, username, password, role, grade, class: userClass, status } = body || {}
const normalizedName = normalizeRequiredText(name)
const normalizedUsername = normalizeRequiredText(username)
// 验证必填字段
if (!normalizedName || !normalizedUsername) {
throw createError({
statusCode: 400,
message: '姓名和用户名为必填项'
})
}
// 检查用户是否存在
const existingUser = await db.select().from(users).where(eq(users.id, userIdNum)).limit(1)
if (existingUser.length === 0) {
throw createError({
statusCode: 404,
message: '用户不存在'
})
}
const targetUser = existingUser[0]!
// 1. 禁止修改系统初始超级管理员 (ID: 1)
if (targetUser.id === 1) {
throw createError({
statusCode: 403,
message: '无法修改系统初始超级管理员'
})
}
// 2. 禁止对自身进行任何用户管理操作(包括角色、资料、状态、密码等)
// 使用 String 转换确保 ID 比较的准确性
if (String(userId) === String(user.id)) {
throw createError({
statusCode: 400,
message: '禁止在用户管理中修改自己的账户'
})
}
// 3. 越级修改保护
// 如果目标用户是 SUPER_ADMIN,操作者必须是 SUPER_ADMIN
if (targetUser.role === 'SUPER_ADMIN' && user.role !== 'SUPER_ADMIN') {
throw createError({
statusCode: 403,
message: '权限不足:普通管理员无法修改超级管理员信息'
})
}
// 检查用户名是否被其他用户使用
if (normalizedUsername !== targetUser.username) {
const duplicateUser = await db
.select()
.from(users)
.where(eq(users.username, normalizedUsername))
.limit(1)
if (duplicateUser.length > 0) {
throw createError({
statusCode: 400,
message: '用户名已被其他用户使用'
})
}
}
// 角色权限控制
let validRole = targetUser.role
if (role) {
if (!['USER', 'ADMIN', 'SONG_ADMIN', 'SUPER_ADMIN'].includes(role)) {
throw createError({
statusCode: 400,
message: '无效的用户角色'
})
}
}
if (role && role !== targetUser.role) {
// 超级管理员可以设置任何角色
if (user.role === 'SUPER_ADMIN') {
validRole = role
}
// 管理员只能设置管理员以下的角色(USER, SONG_ADMIN)
else if (user.role === 'ADMIN') {
if (['USER', 'SONG_ADMIN'].includes(role)) {
validRole = role
} else {
throw createError({
statusCode: 403,
message: '管理员只能设置用户和歌曲管理员角色'
})
}
}
// 其他角色不能设置角色
else {
throw createError({
statusCode: 403,
message: '没有权限设置用户角色'
})
}
}
// 验证status字段的有效性
if (status && !['active', 'withdrawn', 'graduate'].includes(status)) {
throw createError({
statusCode: 400,
message: '用户状态只能是 active, withdrawn 或 graduate'
})
}
// 待审核用户不得通过编辑接口直接置为 active(须走注册审核流程)
if (targetUser.status === 'pending' && status === 'active') {
throw createApiError(400, SERVER_ERROR_CODES.USER_NOT_PENDING, '待审核用户需通过注册审核流程处理')
}
// 准备更新数据
const updateData = {
name: normalizedName,
username: normalizedUsername,
role: validRole,
grade: normalizeOptionalText(grade),
class: normalizeOptionalText(userClass),
...(status && status !== targetUser.status
? {
status,
statusChangedAt: new Date(),
statusChangedBy: user.id
}
: {})
}
// 如果提供了密码,则使用统一服务更新密码
if (password) {
const trimmedPassword = String(password).trim()
// 管理员重置为临时密码且 forceReset 强制用户登录后修改,仅做基础校验不要求完整复杂度
const violation = getAdminPasswordViolation(trimmedPassword)
if (violation) {
throw createApiError(400, violation.code, violation.message)
}
await updateUserPassword(targetUser.id, trimmedPassword, {
forceReset: true,
auditContext: {
action: PASSWORD_AUDIT_ACTIONS.RESET_PASSWORD,
actorId: user.id,
...getPasswordAuditContext(event)
}
})
}
// 更新用户其他信息
const updatedUser = await db
.update(users)
.set(updateData)
.where(eq(users.id, userIdNum))
.returning({
id: users.id,
name: users.name,
username: users.username,
role: users.role,
grade: users.grade,
class: users.class,
status: users.status,
statusChangedAt: users.statusChangedAt,
statusChangedBy: users.statusChangedBy,
lastLogin: users.lastLogin,
lastLoginIp: users.lastLoginIp,
passwordChangedAt: users.passwordChangedAt,
createdAt: users.createdAt,
updatedAt: users.updatedAt
})
// 如果状态发生变更,记录到状态变更日志
if (status && status !== targetUser.status) {
await db.insert(userStatusLogs).values({
userId: targetUser.id,
oldStatus: targetUser.status,
newStatus: status,
reason: `管理员${user.name || user.username}修改用户状态`,
operatorId: user.id
})
}
if (validRole !== targetUser.role) {
const oldRoleName = roleNames[targetUser.role] || targetUser.role
const newRoleName = roleNames[validRole] || validRole
const notification = await createSystemNotification(
targetUser.id,
'权限变更通知',
`您的账户权限已由系统更新:${oldRoleName} → ${newRoleName}`
)
if (!notification) {
console.warn(`未向用户 ${targetUser.id} 发送权限变更通知`)
}
}
return {
success: true,
user: updatedUser[0]!,
message: '用户更新成功'
}
} catch (error: any) {
console.error('更新用户失败:', error)
if (error.statusCode) {
throw error
}
throw createError({
statusCode: 500,
message: '更新用户失败: ' + error.message
})
}
})
@@ -0,0 +1,197 @@
import { defineEventHandler, getRouterParam, readBody } from 'h3'
import { db } from '~/drizzle/db'
import { users, userStatusLogs } from '~/drizzle/schema'
import { eq, and } from 'drizzle-orm'
import { getServerDate } from '~~/server/utils/serverTime'
import { createApiError } from '~~/server/utils/apiError'
import { SERVER_ERROR_CODES } from '~~/server/config/constants'
import { validateGradeClassPair } from '~~/server/utils/register-validation'
import { isGradeClassValid } from '~~/server/utils/grade-class-options'
import { SmtpService } from '~~/server/services/smtpService'
// 审核通过邮件通知(异步,失败不影响主流程)
async function notifyApproved(name, email) {
try {
const smtpService = SmtpService.getInstance()
if (await smtpService.ensureInitialized()) {
await smtpService.renderAndSend(email, 'register-approved', {
title: '注册审核已通过',
message: `${name},您的注册申请已通过审核,现在可以使用账号登录了。`
})
}
} catch (error) {
console.error('审核通过邮件发送失败:', error)
}
}
// 审核拒绝邮件通知(用户已删除,用快照 email 发信;异步,失败不影响主流程)
async function notifyRejected(name, email, reason) {
try {
const smtpService = SmtpService.getInstance()
if (await smtpService.ensureInitialized()) {
await smtpService.renderAndSend(email, 'register-rejected', {
title: '注册申请未通过审核',
message: `${name},您的注册申请未通过审核${reason ? `,原因:${reason}` : ''}。如有疑问请联系管理员。`
})
}
} catch (error) {
console.error('审核拒绝邮件发送失败:', error)
}
}
// 注册审核:approve 通过(可修改注册信息),reject 拒绝(删除账户并记录理由与用户快照)
export default defineEventHandler(async (event) => {
// 检查认证和权限
const operator = event.context.user
if (!operator || !['ADMIN', 'SUPER_ADMIN'].includes(operator.role)) {
throw createApiError(403, SERVER_ERROR_CODES.COMMON_INSUFFICIENT_PERMISSION, '没有权限访问')
}
const userId = getRouterParam(event, 'id')
const body = await readBody(event)
const { action, reason } = body
if (!action || !['approve', 'reject'].includes(action)) {
throw createApiError(400, SERVER_ERROR_CODES.COMMON_INVALID_PARAMS, 'action 必须为 approve 或 reject')
}
// 目标用户必须存在且处于待审核状态
const userIdNumber = Number(userId)
if (!Number.isInteger(userIdNumber) || userIdNumber <= 0) {
throw createApiError(400, SERVER_ERROR_CODES.COMMON_INVALID_PARAMS, '无效的用户 ID')
}
const targetResult = await db
.select({
id: users.id,
username: users.username,
name: users.name,
status: users.status,
email: users.email
})
.from(users)
.where(eq(users.id, userIdNumber))
.limit(1)
if (targetResult.length === 0) {
throw createApiError(404, SERVER_ERROR_CODES.COMMON_TARGET_NOT_FOUND, '用户不存在')
}
const targetUser = targetResult[0]
if (targetUser.status !== 'pending') {
throw createApiError(400, SERVER_ERROR_CODES.USER_NOT_PENDING, '仅待审核用户可执行审核操作')
}
const currentTime = getServerDate()
if (action === 'approve') {
// 年级与班级必须成对修改(或全部不修改)
const gradeClassError = validateGradeClassPair(body.grade, body.class)
if (gradeClassError) {
throw createApiError(400, SERVER_ERROR_CODES.COMMON_INVALID_PARAMS, gradeClassError.message)
}
// 提交了年级班级组合时须为配置内组合(与注册校验同源)
if (typeof body.grade === 'string' && typeof body.class === 'string' && body.grade.trim() && body.class.trim()) {
const grade = body.grade.trim()
const classValue = body.class.trim()
const isValid = await isGradeClassValid(grade, classValue)
if (!isValid) {
throw createApiError(
400,
SERVER_ERROR_CODES.COMMON_INVALID_PARAMS,
'所选年级班级不在可选项内,请检查配置'
)
}
}
// 审核通过,可同步修改注册信息(未提供的字段保持不变)
const updateData: Record<string, unknown> = {
status: 'active',
statusChangedAt: currentTime,
statusChangedBy: operator.id
}
if (typeof body.name === 'string') {
const trimmedName = body.name.trim()
if (!trimmedName) {
throw createApiError(400, SERVER_ERROR_CODES.COMMON_INVALID_PARAMS, '姓名不能为空')
}
updateData.name = trimmedName
}
if (typeof body.grade === 'string') {
updateData.grade = body.grade.trim() || null
}
if (typeof body.class === 'string') {
updateData.class = body.class.trim() || null
}
if (typeof body.remark === 'string') {
updateData.remark = body.remark.trim() || null
}
await db.transaction(async (tx) => {
// 并发防护:仅当用户仍处于 pending 时才通过(防止另一管理员已处理后重复写入)
const updated = await tx
.update(users)
.set(updateData)
.where(and(eq(users.id, userIdNumber), eq(users.status, 'pending')))
.returning({ id: users.id })
if (updated.length === 0) {
throw createApiError(409, SERVER_ERROR_CODES.USER_NOT_PENDING, '该用户已不在待审核状态,请刷新后重试')
}
await tx.insert(userStatusLogs).values({
userId: userIdNumber,
username: targetUser.username,
name: targetUser.name,
oldStatus: 'pending',
newStatus: 'active',
reason: typeof reason === 'string' && reason.trim() ? reason.trim() : '注册审核通过',
operatorId: operator.id,
createdAt: currentTime
})
})
// 审核通过邮件通知(异步,失败不影响主流程)
if (targetUser.email) {
notifyApproved(targetUser.name, targetUser.email)
}
return {
success: true,
message: '注册审核通过'
}
}
// 拒绝:删除账户,日志保存用户快照(用户删除后审计仍可追溯)
const rejectReason = typeof reason === 'string' && reason.trim() ? reason.trim() : '注册审核拒绝'
await db.transaction(async (tx) => {
// 并发防护:仅当用户仍处于 pending 时才删除(防止删除已被其他管理员处理的用户)
const deleted = await tx
.delete(users)
.where(and(eq(users.id, userIdNumber), eq(users.status, 'pending')))
.returning({ id: users.id })
if (deleted.length === 0) {
throw createApiError(409, SERVER_ERROR_CODES.USER_NOT_PENDING, '该用户已不在待审核状态,请刷新后重试')
}
await tx.insert(userStatusLogs).values({
userId: userIdNumber,
username: targetUser.username,
name: targetUser.name,
oldStatus: 'pending',
newStatus: 'rejected',
reason: rejectReason,
operatorId: operator.id,
createdAt: currentTime
})
})
// 审核拒绝邮件通知(用户已删除,用快照 email 发信)
if (targetUser.email) {
notifyRejected(targetUser.name, targetUser.email, rejectReason)
}
return {
success: true,
message: '注册申请已拒绝'
}
})
@@ -0,0 +1,112 @@
import { eq } from 'drizzle-orm'
import { db } from '~/drizzle/db'
import { users } from '~/drizzle/schema'
import { updateUserPassword } from '~~/server/services/userService'
import {
PASSWORD_AUDIT_ACTIONS,
getPasswordAuditContext,
recordPasswordAudit
} from '~~/server/services/passwordSecurityService'
import { createApiError } from '~~/server/utils/apiError'
import { getAdminPasswordViolation } from '~~/server/utils/admin-password-policy'
export default defineEventHandler(async (event) => {
// 检查认证和权限
const user = event.context.user
if (!user || !['ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
throw createError({
statusCode: 403,
message: '没有权限访问'
})
}
// 安全获取ID参数
const params = event.context.params || {}
const id = parseInt(params.id || '')
if (isNaN(id)) {
throw createError({
statusCode: 400,
message: '无效的用户ID'
})
}
const body = await readBody<Record<string, unknown> | null>(event)
const newPassword = typeof body?.newPassword === 'string' ? body.newPassword.trim() : ''
// 管理员重置为临时密码且 forceReset 强制用户登录后修改,仅做基础校验不要求完整复杂度
const violation = getAdminPasswordViolation(newPassword)
if (violation) {
throw createApiError(400, violation.code, violation.message)
}
try {
// 查询目标用户用于越级保护
const targetUsers = await db
.select({ id: users.id, role: users.role })
.from(users)
.where(eq(users.id, id))
.limit(1)
const targetUser = targetUsers[0]
if (!targetUser) {
throw createError({
statusCode: 404,
message: '用户不存在'
})
}
// 禁止对自身进行密码重置(通过用户管理界面)
if (id === user.id) {
throw createError({
statusCode: 400,
message: '禁止在用户管理中重置自己的密码'
})
}
// 禁止重置系统初始超级管理员 (ID: 1)
if (targetUser.id === 1) {
throw createError({
statusCode: 403,
message: '无法重置系统初始超级管理员的密码'
})
}
// 越级保护:目标用户是 SUPER_ADMIN 时,操作者必须是 SUPER_ADMIN
if (targetUser.role === 'SUPER_ADMIN' && user.role !== 'SUPER_ADMIN') {
throw createError({
statusCode: 403,
message: '权限不足:普通管理员无法重置超级管理员密码'
})
}
// 使用统一服务重置密码 (forceReset = true)
await updateUserPassword(id, newPassword, {
forceReset: true,
auditContext: {
action: PASSWORD_AUDIT_ACTIONS.RESET_PASSWORD,
actorId: user.id,
...getPasswordAuditContext(event)
}
})
return {
success: true,
message: '密码重置成功'
}
} catch (error) {
await recordPasswordAudit(
event,
id,
PASSWORD_AUDIT_ACTIONS.RESET_PASSWORD,
false,
error instanceof Error ? error.message : '管理员重置密码失败',
user.id
)
console.error('重置密码失败:', error)
if (error && typeof error === 'object' && 'statusCode' in error) throw error
throw createError({
statusCode: 500,
message: '重置密码失败'
})
}
})
+273
View File
@@ -0,0 +1,273 @@
import { db } from '~/drizzle/db'
import { schedules, songReplayRequests, songs, users, votes } from '~/drizzle/schema'
import { and, count, desc, eq, inArray } from 'drizzle-orm'
export default defineEventHandler(async (event) => {
try {
// 使用认证中间件提供的用户信息
const currentUser = event.context.user
if (!currentUser) {
throw createError({
statusCode: 401,
message: '未授权访问'
})
}
// 检查是否为管理员、歌曲管理员或超级管理员
const allowedRoles = ['ADMIN', 'SONG_ADMIN', 'SUPER_ADMIN']
if (!allowedRoles.includes(currentUser.role)) {
throw createError({
statusCode: 403,
message: '权限不足'
})
}
// 获取用户 ID
const userId = parseInt(getRouterParam(event, 'id') as string)
if (!userId || isNaN(userId)) {
throw createError({
statusCode: 400,
message: '无效的用户 ID'
})
}
// 验证用户是否存在
const userResult = await db
.select({
id: users.id,
name: users.name,
username: users.username,
grade: users.grade,
class: users.class
})
.from(users)
.where(eq(users.id, userId))
.limit(1)
const user = userResult[0]
if (!user) {
throw createError({
statusCode: 404,
message: '用户不存在'
})
}
// 获取用户投稿的歌曲
const submittedSongs = await db
.select({
id: songs.id,
title: songs.title,
artist: songs.artist,
semester: songs.semester,
durationSeconds: songs.durationSeconds,
createdAt: songs.createdAt,
played: songs.played
})
.from(songs)
.where(eq(songs.requesterId, userId))
.orderBy(desc(songs.createdAt))
// 获取投稿歌曲的投票数
const submittedSongIds = submittedSongs.map((song) => song.id)
const submittedVoteCountsMap = new Map()
if (submittedSongIds.length > 0) {
const submittedVoteCountsResult = await db
.select({
songId: votes.songId,
voteCount: count(votes.id)
})
.from(votes)
.where(inArray(votes.songId, submittedSongIds))
.groupBy(votes.songId)
submittedVoteCountsResult.forEach((item) => {
submittedVoteCountsMap.set(item.songId, item.voteCount)
})
}
// 获取用户投票的歌曲
const votedSongs = await db
.select({
id: votes.id,
createdAt: votes.createdAt,
songId: votes.songId,
songTitle: songs.title,
songArtist: songs.artist,
songSemester: songs.semester,
songPlayed: songs.played,
requesterName: users.name,
requesterGrade: users.grade,
requesterClass: users.class
})
.from(votes)
.leftJoin(songs, eq(votes.songId, songs.id))
.leftJoin(users, eq(songs.requesterId, users.id))
.where(eq(votes.userId, userId))
.orderBy(desc(votes.createdAt))
// 获取投票歌曲的投票数
const votedSongIds = votedSongs.map((vote) => vote.songId).filter((id) => id !== null)
const votedVoteCountsMap = new Map()
if (votedSongIds.length > 0) {
const votedVoteCountsResult = await db
.select({
songId: votes.songId,
voteCount: count(votes.id)
})
.from(votes)
.where(inArray(votes.songId, votedSongIds))
.groupBy(votes.songId)
votedVoteCountsResult.forEach((item) => {
votedVoteCountsMap.set(item.songId, item.voteCount)
})
}
// 获取投稿歌曲的排期状态
// 只查询已发布的排期,草稿不算作已排期
const submittedScheduleMap = new Map()
if (submittedSongIds.length > 0) {
const submittedScheduleResult = await db
.select({
songId: schedules.songId
})
.from(schedules)
.where(and(inArray(schedules.songId, submittedSongIds), eq(schedules.isDraft, false)))
submittedScheduleResult.forEach((item) => {
submittedScheduleMap.set(item.songId, true)
})
}
// 获取投票歌曲的排期状态
// 只查询已发布的排期,草稿不算作已排期
const votedScheduleMap = new Map()
if (votedSongIds.length > 0) {
const votedScheduleResult = await db
.select({
songId: schedules.songId
})
.from(schedules)
.where(and(inArray(schedules.songId, votedSongIds), eq(schedules.isDraft, false)))
votedScheduleResult.forEach((item) => {
votedScheduleMap.set(item.songId, true)
})
}
// 获取用户申请重播的歌曲
const replayRequestedSongs = await db
.select({
id: songReplayRequests.id,
createdAt: songReplayRequests.createdAt,
songId: songReplayRequests.songId,
songTitle: songs.title,
songArtist: songs.artist,
songSemester: songs.semester,
songPlayed: songs.played,
requesterName: users.name,
requesterGrade: users.grade,
requesterClass: users.class
})
.from(songReplayRequests)
.leftJoin(songs, eq(songReplayRequests.songId, songs.id))
.leftJoin(users, eq(songs.requesterId, users.id))
.where(eq(songReplayRequests.userId, userId))
.orderBy(desc(songReplayRequests.createdAt))
// 获取重播申请歌曲的总申请数
const replaySongIds = replayRequestedSongs.map((req) => req.songId).filter((id) => id !== null)
const replayRequestCountsMap = new Map()
if (replaySongIds.length > 0) {
const replayRequestCountsResult = await db
.select({
songId: songReplayRequests.songId,
requestCount: count(songReplayRequests.id)
})
.from(songReplayRequests)
.where(inArray(songReplayRequests.songId, replaySongIds))
.groupBy(songReplayRequests.songId)
replayRequestCountsResult.forEach((item) => {
replayRequestCountsMap.set(item.songId, item.requestCount)
})
}
// 获取重播申请歌曲的排期状态
const replayScheduleMap = new Map()
if (replaySongIds.length > 0) {
const replayScheduleResult = await db
.select({
songId: schedules.songId
})
.from(schedules)
.where(and(inArray(schedules.songId, replaySongIds), eq(schedules.isDraft, false)))
replayScheduleResult.forEach((item) => {
replayScheduleMap.set(item.songId, true)
})
}
return {
user: {
id: user.id,
name: user.name,
username: user.username,
grade: user.grade,
class: user.class
},
submittedSongs: submittedSongs.map((song) => ({
id: song.id,
title: song.title,
artist: song.artist,
semester: song.semester,
createdAt: song.createdAt,
played: song.played,
scheduled: submittedScheduleMap.has(song.id),
voteCount: submittedVoteCountsMap.get(song.id) || 0
})),
votedSongs: votedSongs.map((vote) => ({
id: vote.songId,
title: vote.songTitle,
artist: vote.songArtist,
semester: vote.songSemester,
played: vote.songPlayed,
scheduled: votedScheduleMap.has(vote.songId),
voteCount: votedVoteCountsMap.get(vote.songId) || 0,
votedAt: vote.createdAt,
requester: {
name: vote.requesterName,
grade: vote.requesterGrade,
class: vote.requesterClass
}
})),
replayRequestedSongs: replayRequestedSongs.map((req) => ({
id: req.songId,
title: req.songTitle,
artist: req.songArtist,
semester: req.songSemester,
played: req.songPlayed,
scheduled: replayScheduleMap.has(req.songId),
requestCount: replayRequestCountsMap.get(req.songId) || 0,
requestedAt: req.createdAt,
requester: {
name: req.requesterName,
grade: req.requesterGrade,
class: req.requesterClass
}
}))
}
} catch (error) {
console.error('获取用户歌曲信息失败:', error)
if (error.statusCode) {
throw error
}
throw createError({
statusCode: 500,
message: '服务器内部错误'
})
}
})
@@ -0,0 +1,123 @@
import { createError, defineEventHandler, getQuery, getRouterParam } from 'h3'
import { db } from '~/drizzle/db'
import { users, userStatusLogs } from '~/drizzle/schema'
import { count, desc, eq } from 'drizzle-orm'
import { getStatusText } from '~~/server/utils/user'
export default defineEventHandler(async (event) => {
try {
// 检查认证和权限
const user = event.context.user
if (!user || !['ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
throw createError({
statusCode: 403,
message: '没有权限访问'
})
}
const userId = getRouterParam(event, 'id')
const query = getQuery(event)
const { page = '1', limit = '20' } = query
// 验证用户 ID
const numUserId = parseInt(userId)
if (isNaN(numUserId) || numUserId <= 0) {
throw createError({
statusCode: 400,
message: '无效的用户 ID'
})
}
// 检查用户是否存在
const existingUser = await db
.select({
id: users.id,
name: users.name,
username: users.username
})
.from(users)
.where(eq(users.id, numUserId))
.limit(1)
if (existingUser.length === 0) {
throw createError({
statusCode: 404,
message: '用户不存在'
})
}
// 分页参数
const pageNum = Math.max(1, parseInt(page as string) || 1)
const limitNum = Math.max(1, parseInt(limit as string) || 20)
const skip = (pageNum - 1) * limitNum
// 获取总数
const totalResult = await db
.select({ count: count() })
.from(userStatusLogs)
.where(eq(userStatusLogs.userId, numUserId))
const total = totalResult[0].count
// 获取状态变更日志列表
const logs = await db
.select({
id: userStatusLogs.id,
oldStatus: userStatusLogs.oldStatus,
newStatus: userStatusLogs.newStatus,
reason: userStatusLogs.reason,
createdAt: userStatusLogs.createdAt,
operatorId: userStatusLogs.operatorId,
operatorName: users.name,
operatorUsername: users.username
})
.from(userStatusLogs)
.leftJoin(users, eq(userStatusLogs.operatorId, users.id))
.where(eq(userStatusLogs.userId, numUserId))
.orderBy(desc(userStatusLogs.createdAt))
.limit(limitNum)
.offset(skip)
// 计算分页信息
const totalPages = Math.ceil(total / limitNum)
const hasNextPage = pageNum < totalPages
const hasPrevPage = pageNum > 1
return {
success: true,
user: existingUser[0],
logs: logs.map((log) => ({
id: log.id,
oldStatus: log.oldStatus,
newStatus: log.newStatus,
oldStatusDisplay: getStatusText(log.oldStatus || ''),
newStatusDisplay: getStatusText(log.newStatus || ''),
reason: log.reason,
createdAt: log.createdAt,
operator: {
id: log.operatorId,
name: log.operatorName || '未知操作员',
username: log.operatorUsername || 'unknown'
}
})),
pagination: {
total,
page: pageNum,
limit: limitNum,
totalPages,
hasNextPage,
hasPrevPage
}
}
} catch (error) {
console.error('获取用户状态变更日志失败:', error)
if (error.statusCode) {
throw error
}
throw createError({
statusCode: 500,
message: '获取用户状态变更日志失败:' + error.message
})
}
})
+132
View File
@@ -0,0 +1,132 @@
import { createError, defineEventHandler, getRouterParam, readBody } from 'h3'
import { db } from '~/drizzle/db'
import { users, userStatusLogs } from '~/drizzle/schema'
import { eq } from 'drizzle-orm'
import { getBeijingTime } from '~/utils/timeUtils'
import { getStatusText } from '~~/server/utils/user'
import { createApiError } from '~~/server/utils/apiError'
import { SERVER_ERROR_CODES } from '~~/server/config/constants'
export default defineEventHandler(async (event) => {
try {
// 检查认证和权限
const user = event.context.user
if (!user || !['ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
throw createError({
statusCode: 403,
message: '没有权限访问'
})
}
const userId = getRouterParam(event, 'id')
const body = await readBody(event)
const { status, reason } = body
// 验证必填字段
if (!status || !['active', 'withdrawn', 'graduate'].includes(status)) {
throw createError({
statusCode: 400,
message: '状态必须为 active, withdrawn 或 graduate'
})
}
if (!reason || reason.trim().length === 0) {
throw createError({
statusCode: 400,
message: '变更原因为必填项'
})
}
// 检查用户是否存在
const existingUser = await db
.select({
id: users.id,
name: users.name,
username: users.username,
status: users.status,
role: users.role
})
.from(users)
.where(eq(users.id, parseInt(userId)))
.limit(1)
if (existingUser.length === 0) {
throw createError({
statusCode: 404,
message: '用户不存在'
})
}
const targetUser = existingUser[0]
// 待审核用户不得通过状态接口直接置为 active(须走注册审核流程)
if (targetUser.status === 'pending' && status === 'active') {
throw createApiError(400, SERVER_ERROR_CODES.USER_NOT_PENDING, '待审核用户需通过注册审核流程处理')
}
// 检查是否为学生用户
if (targetUser.role !== 'USER') {
throw createError({
statusCode: 400,
message: '只能修改学生用户的状态'
})
}
// 检查状态是否有变化
if (targetUser.status === status) {
throw createError({
statusCode: 400,
message: '用户状态未发生变化'
})
}
const currentTime = getBeijingTime()
const oldStatus = targetUser.status
// 开始事务
await db.transaction(async (tx) => {
// 更新用户状态
await tx
.update(users)
.set({
status: status,
statusChangedAt: currentTime,
statusChangedBy: user.id
})
.where(eq(users.id, parseInt(userId)))
// 记录状态变更日志
await tx.insert(userStatusLogs).values({
userId: parseInt(userId),
oldStatus: oldStatus,
newStatus: status,
reason: reason.trim(),
operatorId: user.id,
createdAt: currentTime
})
})
return {
success: true,
message: `用户状态已更新为${getStatusText(status)}`,
data: {
userId: parseInt(userId),
oldStatus,
newStatus: status,
changedAt: currentTime,
changedBy: user.name
}
}
} catch (error) {
console.error('更新用户状态失败:', error)
if (error.statusCode) {
throw error
}
throw createError({
statusCode: 500,
message: '更新用户状态失败: ' + error.message
})
}
})
@@ -0,0 +1,181 @@
import { db } from '~/drizzle/db'
import { users } from '~/drizzle/schema'
import { inArray } from 'drizzle-orm'
export default defineEventHandler(async (event) => {
try {
// 验证请求方法
if (event.node.req.method !== 'POST') {
throw createError({
statusCode: 405,
message: 'Method Not Allowed'
})
}
// 获取请求体
const body = await readBody(event)
const { userIds, targetGrade, keepClass } = body
// 验证必填字段
if (!userIds || !Array.isArray(userIds) || userIds.length === 0) {
throw createError({
statusCode: 400,
message: 'userIds is required and must be a non-empty array'
})
}
// 对输入的 userIds 进行去重和类型转换
const uniqueUserIds = [
...new Set(userIds.map((id) => parseInt(id)).filter((id) => !isNaN(id) && id > 0))
]
if (uniqueUserIds.length === 0) {
throw createError({
statusCode: 400,
message: '没有有效的用户ID'
})
}
if (!targetGrade || typeof targetGrade !== 'string') {
throw createError({
statusCode: 400,
message: 'targetGrade is required and must be a string'
})
}
if (typeof keepClass !== 'boolean') {
throw createError({
statusCode: 400,
message: 'keepClass is required and must be a boolean'
})
}
// 使用认证中间件提供的用户信息
const currentUser = event.context.user
if (!currentUser) {
throw createError({
statusCode: 401,
message: 'Authentication required'
})
}
// 检查权限 - 只有管理员和超级管理员可以执行批量更新
if (!['ADMIN', 'SUPER_ADMIN'].includes(currentUser.role)) {
throw createError({
statusCode: 403,
message: 'Insufficient permissions'
})
}
// 验证用户ID是否存在
const existingUsers = await db
.select({
id: users.id,
name: users.name,
username: users.username,
grade: users.grade,
class: users.class,
role: users.role
})
.from(users)
.where(inArray(users.id, uniqueUserIds))
const existingUserIds = existingUsers.map((user) => user.id)
const nonExistentUserIds = uniqueUserIds.filter((id) => !existingUserIds.includes(id))
let updated = 0
let failed = 0
const errors: Array<{ userId: number | string; error: string }> = []
// 记录不存在的用户ID
if (nonExistentUserIds.length > 0) {
failed += nonExistentUserIds.length
nonExistentUserIds.forEach((id) => {
errors.push({ userId: id, error: '用户不存在' })
})
}
// 过滤出有权限修改的用户
const validExistingUserIds: number[] = []
for (const user of existingUsers) {
if (user.id === 1) {
failed++
errors.push({ userId: user.id, error: '无法修改系统初始超级管理员' })
continue
}
if (user.id === currentUser.id) {
failed++
errors.push({ userId: user.id, error: '禁止在用户管理中批量更新自己的账户' })
continue
}
if (user.role === 'SUPER_ADMIN' && currentUser.role !== 'SUPER_ADMIN') {
failed++
errors.push({ userId: user.id, error: '权限不足:普通管理员无法修改超级管理员信息' })
continue
}
validExistingUserIds.push(user.id)
}
// 批量更新存在的用户
if (validExistingUserIds.length > 0) {
try {
const updateData: any = {
grade: targetGrade,
updatedAt: new Date()
}
// 如果不保持班级不变,可以在这里添加班级更新逻辑
// 当前实现中keepClass固定为true,所以不更新班级
const updateResult = await db
.update(users)
.set(updateData)
.where(inArray(users.id, validExistingUserIds))
.returning({ id: users.id })
updated = updateResult.length
} catch (error) {
console.error('批量更新失败:', error)
failed += validExistingUserIds.length
validExistingUserIds.forEach((id) => {
errors.push({ userId: id, error: '批量更新操作失败' })
})
}
}
// 记录操作日志(可选,如果需要的话)
try {
// 这里可以添加操作日志记录
// 由于不修改数据库结构,暂时跳过日志记录
} catch (logError) {
console.error('记录操作日志失败:', logError)
// 日志记录失败不影响主要操作
}
return {
success: errors.length === 0 || updated > 0,
updated,
failed,
errors,
details: {
totalRequested: uniqueUserIds.length,
existingUsers: existingUsers.length,
nonExistentUsers: nonExistentUserIds.length,
targetGrade,
keepClass
}
}
} catch (error) {
console.error('批量年级更新API错误:', error)
if (error.statusCode) {
throw error
}
throw createError({
statusCode: 500,
message: 'Internal Server Error'
})
}
})
+222
View File
@@ -0,0 +1,222 @@
import { createError, defineEventHandler, readBody } from 'h3'
import { db } from '~/drizzle/db'
import { users, userStatusLogs } from '~/drizzle/schema'
import { and, eq, inArray } from 'drizzle-orm'
import { getBeijingTime } from '~/utils/timeUtils'
import { getStatusText } from '~~/server/utils/user'
import { createApiError } from '~~/server/utils/apiError'
import { SERVER_ERROR_CODES } from '~~/server/config/constants'
export default defineEventHandler(async (event) => {
try {
// 检查认证和权限
const user = event.context.user
if (!user || !['ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
throw createError({
statusCode: 403,
message: '没有权限访问'
})
}
const body = await readBody(event)
const { userIds, status, reason, sourceStatus } = body
const sourceStatusFilter = typeof sourceStatus === 'string' ? sourceStatus.trim() : ''
// 验证必填字段
if (!Array.isArray(userIds) || userIds.length === 0) {
throw createError({
statusCode: 400,
message: '用户ID列表不能为空'
})
}
if (!status || !['active', 'withdrawn', 'graduate'].includes(status)) {
throw createError({
statusCode: 400,
message: '状态必须为 active, withdrawn 或 graduate'
})
}
// 源状态白名单含 pending(支持按待审核筛选批量处理;同时使下方 pending→active 拦截可达)
if (sourceStatusFilter && !['active', 'pending', 'withdrawn', 'graduate'].includes(sourceStatusFilter)) {
throw createError({
statusCode: 400,
message: '前置状态必须为 active, pending, withdrawn 或 graduate'
})
}
if (sourceStatusFilter === status) {
throw createError({
statusCode: 400,
message: '前置状态不能与目标状态相同'
})
}
// 待审核用户不得通过批量状态接口直接置为 active(须走注册审核流程)
if (sourceStatusFilter === 'pending' && status === 'active') {
throw createApiError(400, SERVER_ERROR_CODES.USER_NOT_PENDING, '待审核用户需通过注册审核流程处理')
}
if (!reason || reason.trim().length === 0) {
throw createError({
statusCode: 400,
message: '变更原因为必填项'
})
}
// 验证用户ID格式
const validUserIds = [
...new Set(
userIds
.filter((id) => {
const numId = parseInt(id)
return !isNaN(numId) && numId > 0
})
.map((id) => parseInt(id))
)
]
if (validUserIds.length === 0) {
throw createError({
statusCode: 400,
message: '没有有效的用户ID'
})
}
// 检查用户是否存在
const existingUsers = await db
.select({
id: users.id,
name: users.name,
username: users.username,
status: users.status,
role: users.role
})
.from(users)
.where(inArray(users.id, validUserIds))
const existingUserIds = existingUsers.map((u) => u.id)
const nonExistentUserIds = validUserIds.filter((id) => !existingUserIds.includes(id))
// 筛选出状态需要变更的用户,并加入越权保护,同时记录失败原因
const usersToUpdate = []
const errors: Array<{ userId: number | string; error: string }> = []
if (nonExistentUserIds.length > 0) {
nonExistentUserIds.forEach((id) => {
errors.push({ userId: id, error: '用户不存在' })
})
}
for (const u of existingUsers) {
if (u.id === 1) {
errors.push({ userId: u.id, error: '无法修改系统初始超级管理员' })
continue
}
if (u.id === user.id) {
errors.push({ userId: u.id, error: '禁止在用户管理中批量更新自己的账户' })
continue
}
if (u.role === 'SUPER_ADMIN' && user.role !== 'SUPER_ADMIN') {
errors.push({ userId: u.id, error: '权限不足:普通管理员无法修改超级管理员信息' })
continue
}
if (u.role !== 'USER' && user.role !== 'SUPER_ADMIN') {
errors.push({ userId: u.id, error: '权限不足:普通管理员无法批量修改其他管理员状态' })
continue
}
if (sourceStatusFilter && u.status !== sourceStatusFilter) {
errors.push({
userId: u.id,
error: `前置状态不匹配:当前为${getStatusText(u.status)},仅更新${getStatusText(sourceStatusFilter)}`
})
continue
}
// 待审核用户不得通过批量状态接口直接置为 active(须走注册审核流程;即使未传 sourceStatus 也按实际状态拦截)
if (status === 'active' && u.status === 'pending') {
errors.push({ userId: u.id, error: '待审核用户需通过注册审核流程处理' })
continue
}
if (u.status === status) {
errors.push({ userId: u.id, error: '用户状态无需变更' })
continue
}
usersToUpdate.push(u)
}
if (usersToUpdate.length === 0) {
return {
success: false,
message: '没有可更新的合法用户',
errors,
data: {
totalRequested: validUserIds.length,
totalUpdated: 0,
updatedUsers: [],
sourceStatus: sourceStatusFilter || null
}
}
}
const currentTime = getBeijingTime()
const results = []
// 开始事务
await db.transaction(async (tx) => {
for (const targetUser of usersToUpdate) {
// 更新用户状态
await tx
.update(users)
.set({
status: status,
statusChangedAt: currentTime,
statusChangedBy: user.id
})
.where(eq(users.id, targetUser.id))
// 记录状态变更日志
await tx.insert(userStatusLogs).values({
userId: targetUser.id,
oldStatus: targetUser.status,
newStatus: status,
reason: reason.trim(),
operatorId: user.id,
createdAt: currentTime
})
results.push({
userId: targetUser.id,
name: targetUser.name,
username: targetUser.username,
oldStatus: targetUser.status,
newStatus: status
})
}
})
return {
success: true,
message: `成功更新 ${results.length} 个用户的状态为${getStatusText(status)}`,
errors,
data: {
totalRequested: validUserIds.length,
totalUpdated: results.length,
updatedUsers: results,
sourceStatus: sourceStatusFilter || null,
changedAt: currentTime,
changedBy: user.name
}
}
} catch (error) {
console.error('批量更新用户状态失败:', error)
if (error.statusCode) {
throw error
}
throw createError({
statusCode: 500,
message: '批量更新用户状态失败: ' + error.message
})
}
})
+243
View File
@@ -0,0 +1,243 @@
import { z } from 'zod'
import { db } from '~/drizzle/db'
import { users, userStatusLogs } from '~/drizzle/schema'
import { and, eq, inArray, ne } from 'drizzle-orm'
// 请求体验证模式
const batchUpdateSchema = z.object({
updates: z
.array(
z.object({
userId: z.number().int().positive(),
grade: z.string().optional(),
class: z.string().optional(),
username: z.string().optional(),
status: z.enum(['active', 'withdrawn', 'graduate']).optional()
})
)
.min(1)
.max(100) // 限制批量更新数量
})
export default defineEventHandler(async (event) => {
try {
// 使用认证中间件提供的用户信息
const currentUser = event.context.user
if (!currentUser) {
throw createError({
statusCode: 401,
message: 'Authentication required'
})
}
// 检查权限 - 只有管理员和超级管理员可以执行批量更新
if (!['ADMIN', 'SUPER_ADMIN'].includes(currentUser.role)) {
throw createError({
statusCode: 403,
message: 'Insufficient permissions'
})
}
// 验证请求体
const body = await readBody(event)
const validationResult = batchUpdateSchema.safeParse(body)
if (!validationResult.success) {
throw createError({
statusCode: 400,
message: '请求参数无效: ' + validationResult.error.issues.map((e) => e.message).join(', ')
})
}
const { updates } = validationResult.data
// 获取所有要更新的用户ID
const userIds = updates.map((update) => update.userId)
// 验证用户是否存在
const existingUsers = await db
.select({
id: users.id,
name: users.name,
username: users.username,
role: users.role,
status: users.status
})
.from(users)
.where(inArray(users.id, userIds))
// 检查是否所有用户都存在
const existingUserIds = new Set(existingUsers.map((user) => user.id))
const missingUserIds = userIds.filter((id) => !existingUserIds.has(id))
if (missingUserIds.length > 0) {
throw createError({
statusCode: 400,
message: `以下用户ID不存在: ${missingUserIds.join(', ')}`
})
}
// 执行批量更新
const updateResults = []
const errors = []
const userMap = new Map(existingUsers.map((u) => [u.id, u]))
for (const update of updates) {
try {
const targetUser = userMap.get(update.userId)
if (!targetUser) continue
// 保护系统初始超级管理员
if (targetUser.id === 1) {
errors.push({
userId: update.userId,
error: '无法修改系统初始超级管理员'
})
continue
}
// 禁止批量更新包含当前操作者自身
if (update.userId === currentUser.id) {
errors.push({
userId: update.userId,
error: '禁止在用户管理中批量更新自己的账户'
})
continue
}
// 越级修改保护
if (targetUser.role === 'SUPER_ADMIN' && currentUser.role !== 'SUPER_ADMIN') {
errors.push({
userId: update.userId,
error: '权限不足:普通管理员无法修改超级管理员信息'
})
continue
}
// 构建更新数据
const updateData: any = {}
if (update.grade !== undefined && update.grade.trim()) {
updateData.grade = update.grade.trim()
}
if (update.class !== undefined && update.class.trim()) {
updateData.class = update.class.trim()
}
// 处理用户名更新
if (update.username !== undefined && update.username.trim()) {
const newUsername = update.username.trim()
// 检查用户名是否已存在(排除当前用户)
const existingUser = await db
.select({ id: users.id })
.from(users)
.where(and(eq(users.username, newUsername), ne(users.id, update.userId)))
.limit(1)
if (existingUser.length > 0) {
errors.push({
userId: update.userId,
error: `用户名 "${newUsername}" 已存在`
})
continue
}
updateData.username = newUsername
}
if (update.status !== undefined) {
const currentUserStatus = existingUsers.find((u) => u.id === update.userId)?.status
if (update.status !== currentUserStatus) {
updateData.status = update.status
updateData.statusChangedAt = new Date()
updateData.statusChangedBy = currentUser.id
}
}
// 如果没有要更新的字段,跳过
if (Object.keys(updateData).length === 0) {
continue
}
let updatedUser
// 使用事务确保更新和日志记录的原子性
await db.transaction(async (tx) => {
// 更新用户信息
const updatedUserResult = await tx
.update(users)
.set(updateData)
.where(eq(users.id, update.userId))
.returning({
id: users.id,
name: users.name,
username: users.username,
grade: users.grade,
class: users.class,
status: users.status
})
updatedUser = updatedUserResult[0]
// 记录状态变更日志
if (updateData.status) {
const currentUserStatus = existingUsers.find((u) => u.id === update.userId)?.status
await tx.insert(userStatusLogs).values({
userId: update.userId,
oldStatus: currentUserStatus,
newStatus: updateData.status,
reason: `管理员${currentUser.name || currentUser.username}批量更新用户状态`,
operatorId: currentUser.id,
createdAt: new Date()
})
}
})
updateResults.push(updatedUser)
} catch (error) {
console.error(`处理用户 ${update.userId} 更新时出错:`, error)
errors.push({
userId: update.userId,
error: error.message || '未知错误'
})
}
}
// 返回结果
const response = {
success: true,
message: `批量更新完成,成功更新 ${updateResults.length} 个用户`,
data: {
updated: updateResults,
errors: errors,
summary: {
total: updates.length,
success: updateResults.length,
failed: errors.length
}
}
}
// 如果有部分失败,调整消息
if (errors.length > 0) {
response.message = `批量更新部分完成,成功更新 ${updateResults.length} 个用户,${errors.length} 个用户更新失败`
}
return response
} catch (error) {
console.error('批量更新用户失败:', error)
// 如果是已知错误,直接抛出
if (error.statusCode) {
throw error
}
// 未知错误
throw createError({
statusCode: 500,
message: '批量更新用户失败: ' + error.message
})
}
})
+210
View File
@@ -0,0 +1,210 @@
import bcrypt from 'bcryptjs'
import { db } from '~/drizzle/db'
import { users } from '~/drizzle/schema'
import { eq, inArray } from 'drizzle-orm'
import { getAdminPasswordViolation } from '~~/server/utils/admin-password-policy'
interface UserData {
name: string
username: string
password: string
role?: string
status?: 'active' | 'withdrawn' | 'graduate'
grade?: string | null
class?: string | null
}
interface ValidUserData extends UserData {
index: number
}
const normalizeRequiredText = (value: unknown) => String(value || '').trim()
const normalizeOptionalText = (value: unknown) => {
const normalized = String(value || '').trim()
return normalized || null
}
export default defineEventHandler(async (event) => {
// 检查认证和权限
const user = event.context.user
if (!user || !['ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
throw createError({
statusCode: 403,
message: '没有权限访问'
})
}
const body = await readBody(event)
if (!body.users || !Array.isArray(body.users) || body.users.length === 0) {
throw createError({
statusCode: 400,
message: '无效的用户数据'
})
}
const results = {
created: 0,
failed: 0,
total: body.users.length,
errors: [] as Array<{ index: number; username?: string; name?: string; reason: string }>
}
// 1. 预处理数据:过滤必填字段,提取要查询的用户名
const validUsers: ValidUserData[] = []
const usernamesToQuery: string[] = []
const usernamesInBatch = new Set<string>()
for (let i = 0; i < body.users.length; i++) {
const userData = body.users[i]
const normalizedUserData = {
...userData,
name: normalizeRequiredText(userData.name),
username: normalizeRequiredText(userData.username),
grade: normalizeOptionalText(userData.grade),
class: normalizeOptionalText(userData.class)
}
if (
!normalizedUserData.name ||
!normalizedUserData.username ||
typeof userData.password !== 'string' ||
!userData.password
) {
results.failed++
results.errors.push({
index: i,
username: userData.username,
name: userData.name,
reason: '缺少必填字段(姓名、账号或密码)'
})
continue
}
const passwordViolation = getAdminPasswordViolation(userData.password)
if (passwordViolation) {
results.failed++
results.errors.push({
index: i,
username: normalizedUserData.username,
name: normalizedUserData.name,
reason: passwordViolation.message
})
continue
}
if (usernamesInBatch.has(normalizedUserData.username)) {
results.failed++
results.errors.push({
index: i,
username: normalizedUserData.username,
name: normalizedUserData.name,
reason: '批处理中存在重复的账号'
})
continue
}
usernamesInBatch.add(normalizedUserData.username)
// 限制单次查询 inArray 的长度,如果需要的话。前端分批已经是 50,所以没问题
validUsers.push({ index: i, ...normalizedUserData })
usernamesToQuery.push(normalizedUserData.username)
}
if (validUsers.length === 0) {
return results
}
// 2. 批量查询已存在的用户名,减少数据库交互
let existingUsernames = new Set<string>()
try {
const existingUsersList = await db
.select({ username: users.username })
.from(users)
.where(inArray(users.username, usernamesToQuery))
existingUsernames = new Set(existingUsersList.map((u) => u.username))
} catch (error: any) {
console.error('批量查询用户失败:', error)
throw createError({
statusCode: 500,
message: '数据库查询错误'
})
}
// 3. 过滤掉已存在的用户
const usersToInsertData: ValidUserData[] = []
for (const userData of validUsers) {
if (existingUsernames.has(userData.username)) {
results.failed++
results.errors.push({
index: userData.index,
username: userData.username,
name: userData.name,
reason: '账号已存在'
})
continue
}
usersToInsertData.push(userData)
}
if (usersToInsertData.length === 0) {
return results
}
try {
// 4. 并发加密密码 (由于使用 bcrypt.hash 异步方法,使用 Promise.all 并发处理可以显著提速)
const hashedPasswords = await Promise.all(
usersToInsertData.map((userData) => bcrypt.hash(userData.password, 10))
)
// 5. 准备批量插入的数据
const insertValues = usersToInsertData.map((userData, idx) => {
// 角色权限控制
let validRole = 'USER' // 默认角色
if (userData.role) {
const rolePermissions: Record<string, string[]> = {
SUPER_ADMIN: ['USER', 'ADMIN', 'SONG_ADMIN', 'SUPER_ADMIN'],
ADMIN: ['USER', 'SONG_ADMIN']
}
const allowedRoles = rolePermissions[user.role]
if (allowedRoles?.includes(userData.role)) {
validRole = userData.role
}
}
// 状态验证
let validStatus = 'active'
if (userData.status && ['active', 'withdrawn', 'graduate'].includes(userData.status)) {
validStatus = userData.status
}
return {
name: userData.name,
username: userData.username,
password: hashedPasswords[idx]!,
role: validRole,
status: validStatus as 'active' | 'withdrawn' | 'graduate',
grade: userData.grade,
class: userData.class
}
})
// 6. 执行批量插入
await db.insert(users).values(insertValues)
results.created += insertValues.length
} catch (error: any) {
console.error(`批量插入用户失败:`, error)
// 如果批量插入整体失败,则全部标记为失败
for (const userData of usersToInsertData) {
results.failed++
results.errors.push({
index: userData.index,
username: userData.username,
name: userData.name,
reason: error.message || '数据库批量写入失败'
})
}
}
return results
})
+193
View File
@@ -0,0 +1,193 @@
import { createError, defineEventHandler, getQuery } from 'h3'
import { db } from '~/drizzle/db'
import { users } from '~/drizzle/schema'
import { and, asc, desc, count, eq, ilike, inArray, isNull, notInArray, or, sql } from 'drizzle-orm'
import { resolveAvatarSource } from '~~/server/utils/user-avatar'
import { ARCHIVED_USER_STATUSES, resolveArchivedFilter } from '~~/server/utils/user-archive'
const UNSET_FILTER_VALUE = '__UNSET__'
export default defineEventHandler(async (event) => {
try {
// 检查用户是否为管理员
const user = event.context.user
if (!user || !['ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
throw createError({
statusCode: 403,
message: '只有系统管理员可以访问用户列表'
})
}
const query = getQuery(event)
const { grade, class: className, search, page = '1', limit = '50', role, status, sortBy = 'id', sortOrder = 'asc', archived } = query
// 构建筛选条件
const whereConditions = []
// 年级筛选
if (grade && typeof grade === 'string' && grade.trim()) {
const gradeFilter = grade.trim()
whereConditions.push(
gradeFilter === UNSET_FILTER_VALUE
? or(isNull(users.grade), eq(users.grade, ''))
: eq(users.grade, gradeFilter)
)
}
// 班级筛选
if (className && typeof className === 'string' && className.trim()) {
const classFilter = className.trim()
whereConditions.push(
classFilter === UNSET_FILTER_VALUE
? or(isNull(users.class), eq(users.class, ''))
: eq(users.class, classFilter)
)
}
// 角色筛选
if (role && typeof role === 'string' && role.trim()) {
whereConditions.push(eq(users.role, role.trim()))
}
// 状态筛选
if (status && typeof status === 'string' && status.trim()) {
const statusFilter = status.trim()
if (['active', 'pending', 'withdrawn', 'graduate'].includes(statusFilter)) {
whereConditions.push(eq(users.status, statusFilter as 'active' | 'pending' | 'withdrawn' | 'graduate'))
}
}
// 归档筛选:archived=1 仅查已归档(graduate/withdrawn);archived=0 排除已归档;缺省不限制
const archivedFilter = resolveArchivedFilter(archived)
if (archivedFilter === 'archived') {
whereConditions.push(inArray(users.status, [...ARCHIVED_USER_STATUSES]))
} else if (archivedFilter === 'unarchived') {
whereConditions.push(notInArray(users.status, [...ARCHIVED_USER_STATUSES]))
}
// 搜索功能(姓名、用户名或IP地址)
if (search && typeof search === 'string' && search.trim()) {
const searchTerm = search.trim()
whereConditions.push(
or(
ilike(users.name, `%${searchTerm}%`),
ilike(users.username, `%${searchTerm}%`),
ilike(users.lastLoginIp, `%${searchTerm}%`)
)
)
}
const whereClause = whereConditions.length > 0 ? and(...whereConditions) : undefined
// 分页参数
const pageNum = Math.max(1, parseInt(page as string) || 1)
const limitNum = Math.min(Math.max(1, parseInt(limit as string) || 50), 1000)
const skip = (pageNum - 1) * limitNum
// 获取总数
const totalResult = await db.select({ count: count() }).from(users).where(whereClause)
const total = totalResult[0]?.count || 0
// 排序逻辑
let orderByClause
if (sortBy === 'name') {
// 对中文名进行拼音排序 (使用 GBK 编码转换 hack,适用于大多数常见汉字)
orderByClause = sortOrder === 'desc'
? sql`convert_to(${users.name}, 'GBK') DESC`
: sql`convert_to(${users.name}, 'GBK') ASC`
} else if (sortBy === 'lastLogin') {
// 确保未登录用户(NULL)排在最后
orderByClause = sortOrder === 'desc'
? sql`${users.lastLogin} DESC NULLS LAST`
: asc(users.lastLogin)
} else if (sortBy === 'createdAt') {
orderByClause = sortOrder === 'desc' ? desc(users.createdAt) : asc(users.createdAt)
} else {
// 默认按 id 排序
orderByClause = sortOrder === 'desc' ? desc(users.id) : asc(users.id)
}
// 获取用户列表
const usersList = await db.query.users.findMany({
where: whereClause,
orderBy: orderByClause,
limit: limitNum,
offset: skip,
columns: {
id: true,
name: true,
username: true,
role: true,
grade: true,
class: true,
status: true,
statusChangedAt: true,
lastLogin: true,
lastLoginIp: true,
passwordChangedAt: true,
forcePasswordChange: true,
meowNickname: true,
meowBoundAt: true,
email: true,
emailVerified: true,
remark: true,
createdAt: true,
updatedAt: true,
avatarProvider: true,
avatarProviderUserId: true
},
with: {
identities: {
columns: {
provider: true,
providerUsername: true,
providerUserId: true,
avatar: true,
createdAt: true
}
}
}
})
// 处理用户列表,添加头像字段
const formattedUsers = usersList.map((user) => {
const avatarSource = resolveAvatarSource(user, user.identities || [])
return {
...user,
avatar: avatarSource?.url ?? null
}
})
// 计算分页信息
const totalPages = Math.ceil(total / limitNum)
const hasNextPage = pageNum < totalPages
const hasPrevPage = pageNum > 1
return {
success: true,
users: formattedUsers,
pagination: {
total,
page: pageNum,
limit: limitNum,
totalPages,
hasNextPage,
hasPrevPage
},
filters: {
grade: grade || null,
class: className || null,
role: role || null,
status: status || null,
search: search || null
}
}
} catch (error: any) {
console.error('获取用户列表失败:', error)
throw createError({
statusCode: 500,
message: '获取用户列表失败: ' + error.message
})
}
})
+134
View File
@@ -0,0 +1,134 @@
import bcrypt from 'bcryptjs'
import { db } from '~/drizzle/db'
import { users } from '~/drizzle/schema'
import { eq } from 'drizzle-orm'
import { createApiError } from '~~/server/utils/apiError'
import { getAdminPasswordViolation } from '~~/server/utils/admin-password-policy'
const normalizeRequiredText = (value: unknown) => String(value || '').trim()
const normalizeOptionalText = (value: unknown) => {
const normalized = String(value || '').trim()
return normalized || null
}
export default defineEventHandler(async (event) => {
// 检查认证和权限
const user = event.context.user
if (!user || !['ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
throw createError({
statusCode: 403,
message: '没有权限访问'
})
}
const body = await readBody(event)
const normalizedName = normalizeRequiredText(body.name)
const normalizedUsername = normalizeRequiredText(body.username)
const initialPassword = typeof body.password === 'string' ? body.password : ''
// 验证必填字段
if (!normalizedName || !normalizedUsername || !initialPassword) {
throw createError({
statusCode: 400,
message: '姓名、用户名和密码不能为空'
})
}
const violation = getAdminPasswordViolation(initialPassword)
if (violation) {
throw createApiError(400, violation.code, violation.message)
}
try {
// 检查用户名是否已存在
const existingUserResult = await db
.select()
.from(users)
.where(eq(users.username, normalizedUsername))
.limit(1)
const existingUser = existingUserResult[0]
if (existingUser) {
throw createError({
statusCode: 400,
message: '用户名已存在'
})
}
// 加密密码
const hashedPassword = await bcrypt.hash(initialPassword, 10)
// 角色权限控制
let validRole = 'USER'
if (body.role && ['USER', 'ADMIN', 'SONG_ADMIN', 'SUPER_ADMIN'].includes(body.role)) {
// 超级管理员可以创建任何角色的用户
if (user.role === 'SUPER_ADMIN') {
validRole = body.role
}
// 管理员只能创建管理员以下的角色(USER, SONG_ADMIN)
else if (user.role === 'ADMIN') {
if (['USER', 'SONG_ADMIN'].includes(body.role)) {
validRole = body.role
} else {
throw createError({
statusCode: 403,
message: '管理员只能创建用户和歌曲管理员角色'
})
}
}
// 其他角色不能创建用户
else {
throw createError({
statusCode: 403,
message: '没有权限创建用户'
})
}
}
// 状态验证
let validStatus = 'active'
if (body.status && ['active', 'withdrawn', 'graduate'].includes(body.status)) {
validStatus = body.status
}
// 创建用户
const newUserResult = await db
.insert(users)
.values({
name: normalizedName,
username: normalizedUsername,
password: hashedPassword,
role: validRole,
status: validStatus as 'active' | 'withdrawn' | 'graduate',
grade: normalizeOptionalText(body.grade),
class: normalizeOptionalText(body.class)
})
.returning({
id: users.id,
name: users.name,
username: users.username,
role: users.role,
status: users.status,
grade: users.grade,
class: users.class,
createdAt: users.createdAt,
updatedAt: users.updatedAt
})
const newUser = newUserResult[0]
return {
success: true,
user: newUser,
message: '用户创建成功'
}
} catch (error: any) {
console.error('创建用户失败:', error)
if (error?.statusCode) {
throw error
}
throw createError({
statusCode: 500,
message: '创建用户失败'
})
}
})
+40
View File
@@ -0,0 +1,40 @@
import { db } from '~/drizzle/db'
import { users } from '~/drizzle/schema'
import { asc } from 'drizzle-orm'
export default defineEventHandler(async (event) => {
// 检查认证和权限
const user = event.context.user
if (!user || !['ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
throw createError({
statusCode: 403,
message: '没有权限访问'
})
}
try {
// 获取所有用户
const usersList = await db
.select({
id: users.id,
name: users.name,
username: users.username,
role: users.role,
grade: users.grade,
class: users.class,
lastLoginAt: users.lastLoginAt,
lastLoginIp: users.lastLoginIp,
passwordChangedAt: users.passwordChangedAt
})
.from(users)
.orderBy(asc(users.id))
return usersList
} catch (error) {
console.error('获取用户列表失败:', error)
throw createError({
statusCode: 500,
message: '获取用户列表失败'
})
}
})
+103
View File
@@ -0,0 +1,103 @@
import { createError, defineEventHandler, getQuery } from 'h3'
import { db } from '~/drizzle/db'
import { users, gradeClass } from '~/drizzle/schema'
import { and, count, inArray, ne, notInArray } from 'drizzle-orm'
import { smartSort } from '~~/server/utils/grade-class-core'
import { ARCHIVED_USER_STATUSES, resolveArchivedFilter } from '~~/server/utils/user-archive'
export default defineEventHandler(async (event) => {
try {
// 检查用户是否为管理员
const user = event.context.user
if (!user || !['ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
throw createError({
statusCode: 403,
message: '只有系统管理员可以访问此选项'
})
}
// 归档筛选:archived=1 仅查已归档(graduate/withdrawn);archived=0 排除已归档;缺省不限制
const query = getQuery(event)
const archivedFilter = resolveArchivedFilter(query.archived)
// 用户树需要全量轻字段,避免用分页列表推导时统计不完整;排除待审核用户(未通过审核不计入组织树/筛选)
const treeConditions = [ne(users.status, 'pending')]
if (archivedFilter === 'archived') {
treeConditions.push(inArray(users.status, [...ARCHIVED_USER_STATUSES]))
} else if (archivedFilter === 'unarchived') {
treeConditions.push(notInArray(users.status, [...ARCHIVED_USER_STATUSES]))
}
const treeUsers = await db
.select({
id: users.id,
name: users.name,
username: users.username,
grade: users.grade,
class: users.class,
role: users.role,
status: users.status
})
.from(users)
.where(and(...treeConditions))
// 已归档用户总数(graduate/withdrawn 状态),供前端"已归档用户"入口徽标
const archivedCountResult = await db
.select({ count: count() })
.from(users)
.where(inArray(users.status, [...ARCHIVED_USER_STATUSES]))
const archivedCount = archivedCountResult[0]?.count || 0
// 年级班级选项:配置优先;未配置时回退到全部用户聚合(含 withdrawn/graduate 与仅有班级项),
// 与组织结构树口径一致,避免筛选下拉缺项
const configRows = await db
.select({ grade: gradeClass.grade, class: gradeClass.class })
.from(gradeClass)
let grades: string[]
let classes: { grade: string | null; class: string }[]
if (configRows.length > 0) {
const options = configRows
.filter((item) => Boolean(item.grade?.trim()) && Boolean(item.class?.trim()))
.sort((a, b) => {
const gradeResult = smartSort(a.grade, b.grade)
return gradeResult || smartSort(a.class, b.class)
})
grades = [...new Set(options.map((item) => item.grade))].sort(smartSort)
classes = options.map((item) => ({ grade: item.grade, class: item.class }))
} else {
const gradesSet = new Set<string>()
const classesMap = new Map<string, { grade: string | null; class: string }>()
for (const treeUser of treeUsers) {
const gradeValue = treeUser.grade?.trim() || ''
const classValue = treeUser.class?.trim() || ''
if (gradeValue) gradesSet.add(gradeValue)
if (classValue) {
const classKey = `${gradeValue}:${classValue}`
if (!classesMap.has(classKey)) {
classesMap.set(classKey, { grade: gradeValue || null, class: classValue })
}
}
}
grades = Array.from(gradesSet).sort(smartSort)
classes = Array.from(classesMap.values()).sort((a, b) =>
a.class.localeCompare(b.class, 'zh-CN', { numeric: true })
)
}
return {
success: true,
grades,
classes,
treeUsers,
archivedCount
}
} catch (error) {
console.error('获取用户筛选选项失败:', error)
throw createError({
statusCode: 500,
message: '获取选项失败'
})
}
})
+199
View File
@@ -0,0 +1,199 @@
import { createError, defineEventHandler, getQuery } from 'h3'
import { db } from '~/drizzle/db'
import { users, userStatusLogs } from '~/drizzle/schema'
import { and, count, desc, eq, ilike, inArray, or, sql } from 'drizzle-orm'
import { getStatusText } from '~~/server/utils/user'
export default defineEventHandler(async (event) => {
try {
// 检查认证和权限
const user = event.context.user
if (!user || !['ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
throw createError({
statusCode: 403,
message: '没有权限访问'
})
}
const query = getQuery(event)
const { page = '1', limit = '50', search, status, operatorId } = query
// 构建筛选条件
const whereConditions = []
// 状态筛选
if (status && typeof status === 'string' && status.trim()) {
whereConditions.push(eq(userStatusLogs.newStatus, status.trim()))
}
// 操作员筛选
if (operatorId && typeof operatorId === 'string' && operatorId.trim()) {
const numOperatorId = parseInt(operatorId.trim())
if (!isNaN(numOperatorId)) {
whereConditions.push(eq(userStatusLogs.operatorId, numOperatorId))
}
}
const whereClause = whereConditions.length > 0 ? and(...whereConditions) : undefined
// 分页参数
const pageNum = Math.max(1, parseInt(page as string) || 1)
const limitNum = Math.max(1, parseInt(limit as string) || 50)
const skip = (pageNum - 1) * limitNum
// 构建基础查询
let baseQuery = db
.select({
id: userStatusLogs.id,
userId: userStatusLogs.userId,
// 优先快照列(用户删除后审计可追溯);存量旧日志快照为 NULL 时回退 join 的用户名
userName: sql`COALESCE(${userStatusLogs.name}, ${users.name})`,
userUsername: sql`COALESCE(${userStatusLogs.username}, ${users.username})`,
oldStatus: userStatusLogs.oldStatus,
newStatus: userStatusLogs.newStatus,
reason: userStatusLogs.reason,
createdAt: userStatusLogs.createdAt,
operatorId: userStatusLogs.operatorId
})
.from(userStatusLogs)
.leftJoin(users, eq(userStatusLogs.userId, users.id))
// 如果有搜索条件,需要额外的join来搜索操作员信息
if (search && typeof search === 'string' && search.trim()) {
const searchTerm = search.trim()
// 这里需要重新构建查询以支持搜索用户名和操作员名
baseQuery = db
.select({
id: userStatusLogs.id,
userId: userStatusLogs.userId,
userName: sql`COALESCE(${userStatusLogs.name}, ${users.name})`,
userUsername: sql`COALESCE(${userStatusLogs.username}, ${users.username})`,
oldStatus: userStatusLogs.oldStatus,
newStatus: userStatusLogs.newStatus,
reason: userStatusLogs.reason,
createdAt: userStatusLogs.createdAt,
operatorId: userStatusLogs.operatorId
})
.from(userStatusLogs)
.leftJoin(users, eq(userStatusLogs.userId, users.id))
.where(
and(
whereClause,
or(
ilike(userStatusLogs.name, `%${searchTerm}%`),
ilike(userStatusLogs.username, `%${searchTerm}%`),
// 存量旧日志快照列为 NULL,回退 join 的用户名列以便可搜
ilike(users.name, `%${searchTerm}%`),
ilike(users.username, `%${searchTerm}%`),
ilike(userStatusLogs.reason, `%${searchTerm}%`)
)
)
)
} else if (whereClause) {
baseQuery = baseQuery.where(whereClause)
}
// 获取总数
const totalQuery = db
.select({ count: count() })
.from(userStatusLogs)
.leftJoin(users, eq(userStatusLogs.userId, users.id))
let totalResult
if (search && typeof search === 'string' && search.trim()) {
const searchTerm = search.trim()
totalResult = await totalQuery.where(
and(
whereClause,
or(
ilike(userStatusLogs.name, `%${searchTerm}%`),
ilike(userStatusLogs.username, `%${searchTerm}%`),
ilike(users.name, `%${searchTerm}%`),
ilike(users.username, `%${searchTerm}%`),
ilike(userStatusLogs.reason, `%${searchTerm}%`)
)
)
)
} else if (whereClause) {
totalResult = await totalQuery.where(whereClause)
} else {
totalResult = await totalQuery
}
const total = totalResult[0].count
// 获取状态变更日志列表
const logs = await baseQuery
.orderBy(desc(userStatusLogs.createdAt))
.limit(limitNum)
.offset(skip)
// 获取操作员信息(用于显示操作员名称)
const operatorIds = [...new Set(logs.map((log) => log.operatorId).filter((id) => id))]
const operators = await db
.select({
id: users.id,
name: users.name,
username: users.username
})
.from(users)
.where(inArray(users.id, operatorIds))
const operatorMap = new Map()
for (const op of operators) {
operatorMap.set(op.id, op)
}
// 计算分页信息
const totalPages = Math.ceil(total / limitNum)
const hasNextPage = pageNum < totalPages
const hasPrevPage = pageNum > 1
return {
success: true,
logs: logs.map((log) => ({
id: log.id,
user: {
id: log.userId,
name: log.userName || '未知用户',
username: log.userUsername || 'unknown'
},
oldStatus: log.oldStatus,
newStatus: log.newStatus,
oldStatusDisplay: getStatusText(log.oldStatus || ''),
newStatusDisplay: getStatusText(log.newStatus || ''),
reason: log.reason,
createdAt: log.createdAt,
operator: {
id: log.operatorId,
name: operatorMap.get(log.operatorId)?.name || '未知操作员',
username: operatorMap.get(log.operatorId)?.username || 'unknown'
}
})),
pagination: {
total,
page: pageNum,
limit: limitNum,
totalPages,
hasNextPage,
hasPrevPage
},
filters: {
search: search || null,
status: status || null,
operatorId: operatorId || null
}
}
} catch (error) {
console.error('获取状态变更日志失败:', error)
if (error.statusCode) {
throw error
}
throw createError({
statusCode: 500,
message: '获取状态变更日志失败: ' + error.message
})
}
})