初次提交
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
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,
|
||||
statusMessage: '没有权限访问'
|
||||
})
|
||||
}
|
||||
|
||||
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,
|
||||
statusMessage: '用户不存在'
|
||||
})
|
||||
}
|
||||
|
||||
// 1. 绝对禁止删除 ID 为 1 的用户 (系统初始超级管理员)
|
||||
if (existingUser.id === 1) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: '无法删除系统初始超级管理员'
|
||||
})
|
||||
}
|
||||
|
||||
// 2. 禁止删除自己 (增强类型安全)
|
||||
// 使用 String 转换确保 ID 比较的准确性
|
||||
if (String(existingUser.id) === String(user.id)) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: '不能删除自己的账户'
|
||||
})
|
||||
}
|
||||
|
||||
// 3. 越级删除保护
|
||||
// 如果目标用户是 SUPER_ADMIN,操作者必须是 SUPER_ADMIN
|
||||
if (existingUser.role === 'SUPER_ADMIN' && user.role !== 'SUPER_ADMIN') {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: '权限不足:普通管理员无法删除超级管理员'
|
||||
})
|
||||
}
|
||||
|
||||
// 删除用户
|
||||
await db.delete(users).where(eq(users.id, parseInt(userId)))
|
||||
|
||||
// 清除相关缓存
|
||||
try {
|
||||
const { cache } = await import('~~/server/utils/cache-helpers')
|
||||
await cache.deletePattern('songs:*')
|
||||
await cache.deletePattern('schedules:*')
|
||||
await cache.deletePattern('stats:*')
|
||||
// 清除该用户的认证缓存
|
||||
await cache.delete(`auth:user:${existingUser.id}`)
|
||||
console.log('[Cache] 歌曲、排期、统计和用户认证缓存已清除(用户删除)')
|
||||
} catch (cacheError) {
|
||||
console.warn('[Cache] 清除缓存失败:', cacheError)
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: '用户删除成功'
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('删除用户失败:', error)
|
||||
|
||||
if (error.statusCode) {
|
||||
throw error
|
||||
}
|
||||
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: '删除用户失败: ' + error.message
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,214 @@
|
||||
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'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
// 检查认证和权限
|
||||
const user = event.context.user
|
||||
if (!user || !['ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: '没有权限访问'
|
||||
})
|
||||
}
|
||||
|
||||
const userId = getRouterParam(event, 'id')
|
||||
const body = await readBody(event)
|
||||
const { name, username, password, role, grade, class: userClass, status } = body
|
||||
|
||||
// 验证必填字段
|
||||
if (!name || !username) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: '姓名和用户名为必填项'
|
||||
})
|
||||
}
|
||||
|
||||
// 验证姓名和用户名只能包含汉字
|
||||
const chineseRegex = /^[\u4e00-\u9fa5]+$/
|
||||
if (!chineseRegex.test(name) || !chineseRegex.test(username)) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: '姓名和用户名只能包含汉字'
|
||||
})
|
||||
}
|
||||
|
||||
// 检查用户是否存在
|
||||
const existingUser = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.id, parseInt(userId)))
|
||||
.limit(1)
|
||||
|
||||
if (existingUser.length === 0) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: '用户不存在'
|
||||
})
|
||||
}
|
||||
|
||||
const targetUser = existingUser[0]
|
||||
|
||||
// 1. 禁止修改系统初始超级管理员 (ID: 1)
|
||||
if (targetUser.id === 1) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: '无法修改系统初始超级管理员'
|
||||
})
|
||||
}
|
||||
|
||||
// 2. 禁止对自身进行任何用户管理操作(包括角色、资料、状态、密码等)
|
||||
// 使用 String 转换确保 ID 比较的准确性
|
||||
if (String(userId) === String(user.id)) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: '禁止在用户管理中修改自己的账户'
|
||||
})
|
||||
}
|
||||
|
||||
// 3. 越级修改保护
|
||||
// 如果目标用户是 SUPER_ADMIN,操作者必须是 SUPER_ADMIN
|
||||
if (targetUser.role === 'SUPER_ADMIN' && user.role !== 'SUPER_ADMIN') {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: '权限不足:普通管理员无法修改超级管理员信息'
|
||||
})
|
||||
}
|
||||
|
||||
// 检查用户名是否被其他用户使用
|
||||
if (username !== targetUser.username) {
|
||||
const duplicateUser = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.username, username))
|
||||
.limit(1)
|
||||
|
||||
if (duplicateUser.length > 0) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: '用户名已被其他用户使用'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 角色权限控制
|
||||
let validRole = 'USER'
|
||||
if (role && ['USER', 'TEACHER', 'ADMIN', 'SONG_ADMIN', 'SUPER_ADMIN'].includes(role)) {
|
||||
// 超级管理员可以设置任何角色
|
||||
if (user.role === 'SUPER_ADMIN') {
|
||||
validRole = role
|
||||
}
|
||||
// 管理员只能设置管理员以下的角色(USER, SONG_ADMIN)
|
||||
else if (user.role === 'ADMIN') {
|
||||
if (['USER', 'TEACHER', 'SONG_ADMIN'].includes(role)) {
|
||||
validRole = role
|
||||
} else {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: '管理员只能设置用户、教师和歌曲管理员角色'
|
||||
})
|
||||
}
|
||||
}
|
||||
// 其他角色不能设置角色
|
||||
else {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: '没有权限设置用户角色'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 验证status字段的有效性
|
||||
if (status && !['active', 'withdrawn', 'graduate'].includes(status)) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: '用户状态只能是 active, withdrawn 或 graduate'
|
||||
})
|
||||
}
|
||||
|
||||
// 准备更新数据
|
||||
const updateData = {
|
||||
name,
|
||||
username,
|
||||
role: validRole,
|
||||
grade,
|
||||
class: userClass
|
||||
}
|
||||
|
||||
// 如果提供了status,则更新状态相关字段
|
||||
if (status && status !== existingUser[0].status) {
|
||||
updateData.status = status
|
||||
updateData.statusChangedAt = new Date()
|
||||
updateData.statusChangedBy = user.id
|
||||
}
|
||||
|
||||
// 如果提供了密码,则使用统一服务更新密码
|
||||
if (password) {
|
||||
await updateUserPassword(parseInt(userId), password, true)
|
||||
}
|
||||
|
||||
// 更新用户其他信息
|
||||
const updatedUser = await db
|
||||
.update(users)
|
||||
.set(updateData)
|
||||
.where(eq(users.id, parseInt(userId)))
|
||||
.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 !== existingUser[0].status) {
|
||||
await db.insert(userStatusLogs).values({
|
||||
userId: parseInt(userId),
|
||||
oldStatus: existingUser[0].status,
|
||||
newStatus: status,
|
||||
reason: `管理员${user.name || user.username}修改用户状态`,
|
||||
operatorId: user.id
|
||||
})
|
||||
}
|
||||
|
||||
// 清除相关缓存
|
||||
try {
|
||||
const { cache } = await import('~~/server/utils/cache-helpers')
|
||||
await cache.deletePattern('songs:*')
|
||||
// 清除该用户的认证缓存(角色或权限可能已变更)
|
||||
await cache.delete(`auth:user:${parseInt(userId)}`)
|
||||
console.log('[Cache] 歌曲和用户认证缓存已清除(用户更新)')
|
||||
} catch (cacheError) {
|
||||
console.warn('[Cache] 清除缓存失败:', cacheError)
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
user: updatedUser[0],
|
||||
message: '用户更新成功'
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('更新用户失败:', error)
|
||||
|
||||
if (error.statusCode) {
|
||||
throw error
|
||||
}
|
||||
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: '更新用户失败: ' + error.message
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,122 @@
|
||||
import { db } from '~/drizzle/db'
|
||||
import { users } from '~/drizzle/schema'
|
||||
import { eq } 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: '没有权限访问'
|
||||
})
|
||||
}
|
||||
|
||||
// 安全获取ID参数
|
||||
const params = event.context.params || {}
|
||||
const id = parseInt(params.id || '')
|
||||
|
||||
if (isNaN(id)) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '无效的用户ID'
|
||||
})
|
||||
}
|
||||
|
||||
// 处理PUT请求 - 更新用户
|
||||
if (event.method === 'PUT') {
|
||||
const body = await readBody(event)
|
||||
|
||||
if (!body.name) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '姓名不能为空'
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
const updatedUserResult = await db
|
||||
.update(users)
|
||||
.set({
|
||||
name: body.name,
|
||||
role: body.role,
|
||||
grade: body.grade,
|
||||
class: body.class
|
||||
})
|
||||
.where(eq(users.id, id))
|
||||
.returning({
|
||||
id: users.id,
|
||||
name: users.name,
|
||||
role: users.role,
|
||||
createdAt: users.createdAt,
|
||||
updatedAt: users.updatedAt,
|
||||
grade: users.grade,
|
||||
class: users.class,
|
||||
username: users.username,
|
||||
passwordChangedAt: users.passwordChangedAt
|
||||
})
|
||||
const updatedUser = updatedUserResult[0]
|
||||
|
||||
return updatedUser
|
||||
} catch (error) {
|
||||
console.error('更新用户失败:', error)
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: '更新用户失败'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 处理DELETE请求 - 删除用户
|
||||
if (event.method === 'DELETE') {
|
||||
try {
|
||||
const existingUserResult = await db.select().from(users).where(eq(users.id, id)).limit(1)
|
||||
if (existingUserResult.length === 0) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
message: '用户不存在'
|
||||
})
|
||||
}
|
||||
const existingUser = existingUserResult[0]
|
||||
|
||||
// 1. 禁止删除 ID 为 1 的用户 (系统初始超级管理员)
|
||||
if (existingUser.id === 1) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
message: '无法删除系统初始超级管理员'
|
||||
})
|
||||
}
|
||||
|
||||
// 2. 确保不能删除自己
|
||||
if (String(existingUser.id) === String(user.id)) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '不能删除当前登录的用户'
|
||||
})
|
||||
}
|
||||
|
||||
// 3. 越级删除保护
|
||||
if (existingUser.role === 'SUPER_ADMIN' && user.role !== 'SUPER_ADMIN') {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
message: '权限不足:普通管理员无法删除超级管理员'
|
||||
})
|
||||
}
|
||||
|
||||
await db.delete(users).where(eq(users.id, id))
|
||||
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error('删除用户失败:', error)
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: '删除用户失败'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
throw createError({
|
||||
statusCode: 405,
|
||||
message: '不支持的请求方法'
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,56 @@
|
||||
import { updateUserPassword } from '~~/server/services/userService'
|
||||
|
||||
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(event)
|
||||
|
||||
if (!body.newPassword) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '新密码不能为空'
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
// 禁止对自身进行密码重置(通过用户管理界面)
|
||||
if (id === user.id) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '禁止在用户管理中重置自己的密码'
|
||||
})
|
||||
}
|
||||
|
||||
// 使用统一服务重置密码 (forceReset = true)
|
||||
await updateUserPassword(id, body.newPassword, true)
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: '密码重置成功'
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('重置密码失败:', error)
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: '重置密码失败'
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,272 @@
|
||||
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,
|
||||
statusMessage: '未授权访问'
|
||||
})
|
||||
}
|
||||
|
||||
// 检查是否为管理员、歌曲管理员或超级管理员
|
||||
const allowedRoles = ['ADMIN', 'SONG_ADMIN', 'SUPER_ADMIN']
|
||||
if (!allowedRoles.includes(currentUser.role)) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: '权限不足'
|
||||
})
|
||||
}
|
||||
|
||||
// 获取用户ID
|
||||
const userId = parseInt(getRouterParam(event, 'id') as string)
|
||||
if (!userId || isNaN(userId)) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: '无效的用户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,
|
||||
statusMessage: '用户不存在'
|
||||
})
|
||||
}
|
||||
|
||||
// 获取用户投稿的歌曲
|
||||
const submittedSongs = await db
|
||||
.select({
|
||||
id: songs.id,
|
||||
title: songs.title,
|
||||
artist: songs.artist,
|
||||
semester: songs.semester,
|
||||
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,
|
||||
statusMessage: '服务器内部错误'
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -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,
|
||||
statusMessage: '没有权限访问'
|
||||
})
|
||||
}
|
||||
|
||||
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,
|
||||
statusMessage: '无效的用户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,
|
||||
statusMessage: '用户不存在'
|
||||
})
|
||||
}
|
||||
|
||||
// 分页参数
|
||||
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,
|
||||
statusMessage: '获取用户状态变更日志失败: ' + error.message
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,134 @@
|
||||
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'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
// 检查认证和权限
|
||||
const user = event.context.user
|
||||
if (!user || !['ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: '没有权限访问'
|
||||
})
|
||||
}
|
||||
|
||||
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,
|
||||
statusMessage: '状态必须为 active, withdrawn 或 graduate'
|
||||
})
|
||||
}
|
||||
|
||||
if (!reason || reason.trim().length === 0) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: '变更原因为必填项'
|
||||
})
|
||||
}
|
||||
|
||||
// 检查用户是否存在
|
||||
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,
|
||||
statusMessage: '用户不存在'
|
||||
})
|
||||
}
|
||||
|
||||
const targetUser = existingUser[0]
|
||||
|
||||
// 检查是否为学生用户
|
||||
if (targetUser.role !== 'USER') {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: '只能修改学生用户的状态'
|
||||
})
|
||||
}
|
||||
|
||||
// 检查状态是否有变化
|
||||
if (targetUser.status === status) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: '用户状态未发生变化'
|
||||
})
|
||||
}
|
||||
|
||||
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
|
||||
})
|
||||
})
|
||||
|
||||
// 清除相关缓存
|
||||
try {
|
||||
const { cache } = await import('~~/server/utils/cache-helpers')
|
||||
await cache.delete(`auth:user:${parseInt(userId)}`)
|
||||
console.log('[Cache] 用户认证缓存已清除(状态更新)')
|
||||
} catch (cacheError) {
|
||||
console.warn('[Cache] 清除缓存失败:', cacheError)
|
||||
}
|
||||
|
||||
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,
|
||||
statusMessage: '更新用户状态失败: ' + error.message
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,155 @@
|
||||
import { db } from '~/drizzle/db'
|
||||
import { CacheService } from '~~/server/services/cacheService'
|
||||
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,
|
||||
statusMessage: '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,
|
||||
statusMessage: 'userIds is required and must be a non-empty array'
|
||||
})
|
||||
}
|
||||
|
||||
if (!targetGrade || typeof targetGrade !== 'string') {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: 'targetGrade is required and must be a string'
|
||||
})
|
||||
}
|
||||
|
||||
if (typeof keepClass !== 'boolean') {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: 'keepClass is required and must be a boolean'
|
||||
})
|
||||
}
|
||||
|
||||
// 使用认证中间件提供的用户信息
|
||||
const currentUser = event.context.user
|
||||
|
||||
if (!currentUser) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: 'Authentication required'
|
||||
})
|
||||
}
|
||||
|
||||
// 检查权限 - 只有管理员和超级管理员可以执行批量更新
|
||||
if (!['ADMIN', 'SUPER_ADMIN'].includes(currentUser.role)) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: 'Insufficient permissions'
|
||||
})
|
||||
}
|
||||
|
||||
// 验证用户ID是否存在
|
||||
const existingUsers = await db
|
||||
.select({
|
||||
id: users.id,
|
||||
name: users.name,
|
||||
username: users.username,
|
||||
grade: users.grade,
|
||||
class: users.class
|
||||
})
|
||||
.from(users)
|
||||
.where(inArray(users.id, userIds))
|
||||
|
||||
const existingUserIds = existingUsers.map((user) => user.id)
|
||||
const nonExistentUserIds = userIds.filter((id) => !existingUserIds.includes(id))
|
||||
|
||||
let updated = 0
|
||||
let failed = 0
|
||||
const errors: string[] = []
|
||||
|
||||
// 记录不存在的用户ID
|
||||
if (nonExistentUserIds.length > 0) {
|
||||
failed += nonExistentUserIds.length
|
||||
errors.push(`用户ID ${nonExistentUserIds.join(', ')} 不存在`)
|
||||
}
|
||||
|
||||
// 批量更新存在的用户
|
||||
if (existingUserIds.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, existingUserIds))
|
||||
.returning({ id: users.id })
|
||||
|
||||
updated = updateResult.length
|
||||
} catch (error) {
|
||||
console.error('批量更新失败:', error)
|
||||
failed += existingUserIds.length
|
||||
errors.push('批量更新操作失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 如果有用户更新成功,清除相关缓存
|
||||
if (updated > 0) {
|
||||
try {
|
||||
const cacheService = CacheService.getInstance()
|
||||
await cacheService.clearSongsCache()
|
||||
console.log('批量年级更新后缓存清除成功')
|
||||
} catch (cacheError) {
|
||||
console.error('批量年级更新后缓存清除失败:', cacheError)
|
||||
}
|
||||
}
|
||||
|
||||
// 记录操作日志(可选,如果需要的话)
|
||||
try {
|
||||
// 这里可以添加操作日志记录
|
||||
// 由于不修改数据库结构,暂时跳过日志记录
|
||||
} catch (logError) {
|
||||
console.error('记录操作日志失败:', logError)
|
||||
// 日志记录失败不影响主要操作
|
||||
}
|
||||
|
||||
return {
|
||||
success: errors.length === 0 || updated > 0,
|
||||
updated,
|
||||
failed,
|
||||
errors,
|
||||
details: {
|
||||
totalRequested: userIds.length,
|
||||
existingUsers: existingUsers.length,
|
||||
nonExistentUsers: nonExistentUserIds.length,
|
||||
targetGrade,
|
||||
keepClass
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('批量年级更新API错误:', error)
|
||||
|
||||
if (error.statusCode) {
|
||||
throw error
|
||||
}
|
||||
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: 'Internal Server Error'
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,158 @@
|
||||
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'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
// 检查认证和权限
|
||||
const user = event.context.user
|
||||
if (!user || !['ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: '没有权限访问'
|
||||
})
|
||||
}
|
||||
|
||||
const body = await readBody(event)
|
||||
const { userIds, status, reason } = body
|
||||
|
||||
// 验证必填字段
|
||||
if (!Array.isArray(userIds) || userIds.length === 0) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: '用户ID列表不能为空'
|
||||
})
|
||||
}
|
||||
|
||||
if (!status || !['active', 'withdrawn', 'graduate'].includes(status)) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: '状态必须为 active, withdrawn 或 graduate'
|
||||
})
|
||||
}
|
||||
|
||||
if (!reason || reason.trim().length === 0) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: '变更原因为必填项'
|
||||
})
|
||||
}
|
||||
|
||||
// 验证用户ID格式
|
||||
const validUserIds = userIds
|
||||
.filter((id) => {
|
||||
const numId = parseInt(id)
|
||||
return !isNaN(numId) && numId > 0
|
||||
})
|
||||
.map((id) => parseInt(id))
|
||||
|
||||
if (validUserIds.length === 0) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: '没有有效的用户ID'
|
||||
})
|
||||
}
|
||||
|
||||
// 检查用户是否存在且为学生角色
|
||||
const existingUsers = await db
|
||||
.select({
|
||||
id: users.id,
|
||||
name: users.name,
|
||||
username: users.username,
|
||||
status: users.status,
|
||||
role: users.role
|
||||
})
|
||||
.from(users)
|
||||
.where(and(inArray(users.id, validUserIds), eq(users.role, 'USER')))
|
||||
|
||||
if (existingUsers.length === 0) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: '没有找到可更新的学生用户'
|
||||
})
|
||||
}
|
||||
|
||||
// 筛选出状态需要变更的用户
|
||||
const usersToUpdate = existingUsers.filter((u) => u.status !== status)
|
||||
|
||||
if (usersToUpdate.length === 0) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: '所选用户的状态均无需变更'
|
||||
})
|
||||
}
|
||||
|
||||
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
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// 清除相关缓存
|
||||
try {
|
||||
const { cache } = await import('~~/server/utils/cache-helpers')
|
||||
for (const userId of usersToUpdate.map((u) => u.id)) {
|
||||
await cache.delete(`auth:user:${userId}`)
|
||||
}
|
||||
console.log('[Cache] 批量用户认证缓存已清除(状态更新)')
|
||||
} catch (cacheError) {
|
||||
console.warn('[Cache] 清除缓存失败:', cacheError)
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `成功更新 ${results.length} 个用户的状态为${getStatusText(status)}`,
|
||||
data: {
|
||||
totalRequested: validUserIds.length,
|
||||
totalUpdated: results.length,
|
||||
updatedUsers: results,
|
||||
changedAt: currentTime,
|
||||
changedBy: user.name
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('批量更新用户状态失败:', error)
|
||||
|
||||
if (error.statusCode) {
|
||||
throw error
|
||||
}
|
||||
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: '批量更新用户状态失败: ' + error.message
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,234 @@
|
||||
import { z } from 'zod'
|
||||
import { db } from '~/drizzle/db'
|
||||
import { CacheService } from '~~/server/services/cacheService'
|
||||
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,
|
||||
statusMessage: 'Authentication required'
|
||||
})
|
||||
}
|
||||
|
||||
// 检查权限 - 只有管理员和超级管理员可以执行批量更新
|
||||
if (!['ADMIN', 'SUPER_ADMIN'].includes(currentUser.role)) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: 'Insufficient permissions'
|
||||
})
|
||||
}
|
||||
|
||||
// 验证请求体
|
||||
const body = await readBody(event)
|
||||
const validationResult = batchUpdateSchema.safeParse(body)
|
||||
|
||||
if (!validationResult.success) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage:
|
||||
'请求参数无效: ' + validationResult.error.errors.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(and(inArray(users.id, userIds), eq(users.role, 'USER')))
|
||||
|
||||
// 检查是否所有用户都存在且为学生
|
||||
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,
|
||||
statusMessage: `以下用户ID不存在或不是学生: ${missingUserIds.join(', ')}`
|
||||
})
|
||||
}
|
||||
|
||||
// 执行批量更新
|
||||
const updateResults = []
|
||||
const errors = []
|
||||
|
||||
for (const update of updates) {
|
||||
try {
|
||||
// 禁止批量更新包含当前操作者自身
|
||||
if (update.userId === currentUser.id) {
|
||||
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} 个用户更新失败`
|
||||
}
|
||||
|
||||
// 如果有用户更新成功,清除相关缓存
|
||||
if (updateResults.length > 0) {
|
||||
try {
|
||||
const cacheService = CacheService.getInstance()
|
||||
await cacheService.clearSongsCache()
|
||||
console.log('批量用户更新后缓存清除成功')
|
||||
} catch (cacheError) {
|
||||
console.error('批量用户更新后缓存清除失败:', cacheError)
|
||||
}
|
||||
}
|
||||
|
||||
return response
|
||||
} catch (error) {
|
||||
console.error('批量更新用户失败:', error)
|
||||
|
||||
// 如果是已知错误,直接抛出
|
||||
if (error.statusCode) {
|
||||
throw error
|
||||
}
|
||||
|
||||
// 未知错误
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: '批量更新用户失败: ' + error.message
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,120 @@
|
||||
import bcrypt from 'bcryptjs'
|
||||
import { db } from '~/drizzle/db'
|
||||
import { users } from '~/drizzle/schema'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { cacheService } from '../../../services/cacheService'
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// 批量添加用户
|
||||
for (let i = 0; i < body.users.length; i++) {
|
||||
const userData = body.users[i]
|
||||
|
||||
try {
|
||||
// 验证必填字段
|
||||
if (!userData.name || !userData.username || !userData.password) {
|
||||
results.failed++
|
||||
continue
|
||||
}
|
||||
|
||||
const chineseRegex = /^[\u4e00-\u9fa5]+$/
|
||||
if (!chineseRegex.test(userData.name) || !chineseRegex.test(userData.username)) {
|
||||
results.failed++
|
||||
continue
|
||||
}
|
||||
|
||||
// 检查用户名是否已存在
|
||||
const existingUser = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.username, userData.username))
|
||||
.limit(1)
|
||||
|
||||
if (existingUser.length > 0) {
|
||||
results.failed++
|
||||
continue
|
||||
}
|
||||
|
||||
// 加密密码
|
||||
const hashedPassword = await bcrypt.hash(userData.password, 10)
|
||||
|
||||
// 角色权限控制
|
||||
let validRole = 'USER' // 默认角色
|
||||
if (userData.role) {
|
||||
if (user.role === 'SUPER_ADMIN') {
|
||||
// 超级管理员可以设置任何角色
|
||||
const allowedRoles = ['USER', 'TEACHER', 'ADMIN', 'SONG_ADMIN', 'SUPER_ADMIN']
|
||||
if (allowedRoles.includes(userData.role)) {
|
||||
validRole = userData.role
|
||||
}
|
||||
} else if (user.role === 'ADMIN') {
|
||||
// 普通管理员只能设置 USER 和 SONG_ADMIN 角色
|
||||
const allowedRoles = ['USER', 'TEACHER', 'SONG_ADMIN']
|
||||
if (allowedRoles.includes(userData.role)) {
|
||||
validRole = userData.role
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 状态验证
|
||||
let validStatus = 'active'
|
||||
if (userData.status && ['active', 'withdrawn', 'graduate'].includes(userData.status)) {
|
||||
validStatus = userData.status
|
||||
}
|
||||
|
||||
// 创建用户
|
||||
const newUser = await db
|
||||
.insert(users)
|
||||
.values({
|
||||
name: userData.name,
|
||||
username: userData.username,
|
||||
password: hashedPassword,
|
||||
role: validRole,
|
||||
status: validStatus as 'active' | 'withdrawn' | 'graduate',
|
||||
grade: userData.grade,
|
||||
class: userData.class
|
||||
})
|
||||
.returning()
|
||||
|
||||
results.created++
|
||||
} catch (error) {
|
||||
console.error(`用户创建失败:`, error)
|
||||
results.failed++
|
||||
}
|
||||
}
|
||||
|
||||
// 如果有用户创建成功,清除相关缓存
|
||||
if (results.created > 0) {
|
||||
try {
|
||||
await cacheService.clearSongsCache()
|
||||
console.log('批量用户创建后缓存清除成功')
|
||||
} catch (cacheError) {
|
||||
console.error('批量用户创建后缓存清除失败:', cacheError)
|
||||
}
|
||||
}
|
||||
|
||||
return results
|
||||
})
|
||||
@@ -0,0 +1,151 @@
|
||||
import { createError, defineEventHandler, getQuery } from 'h3'
|
||||
import { db } from '~/drizzle/db'
|
||||
import { users } from '~/drizzle/schema'
|
||||
import { and, asc, desc, count, eq, ilike, or, sql } from 'drizzle-orm'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
// 获取查询参数
|
||||
const query = getQuery(event)
|
||||
const { grade, class: className, search, page = '1', limit = '50', role, status, sortBy = 'id', sortOrder = 'asc' } = query
|
||||
|
||||
// 构建筛选条件
|
||||
const whereConditions = []
|
||||
|
||||
// 年级筛选
|
||||
if (grade && typeof grade === 'string' && grade.trim()) {
|
||||
whereConditions.push(eq(users.grade, grade.trim()))
|
||||
}
|
||||
|
||||
// 班级筛选
|
||||
if (className && typeof className === 'string' && className.trim()) {
|
||||
whereConditions.push(eq(users.class, className.trim()))
|
||||
}
|
||||
|
||||
// 角色筛选
|
||||
if (role && typeof role === 'string' && role.trim()) {
|
||||
whereConditions.push(eq(users.role, role.trim()))
|
||||
}
|
||||
|
||||
// 状态筛选
|
||||
if (status && typeof status === 'string' && status.trim()) {
|
||||
whereConditions.push(eq(users.status, status.trim()))
|
||||
}
|
||||
|
||||
// 搜索功能(姓名、用户名或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.max(1, parseInt(limit as string) || 50)
|
||||
const skip = (pageNum - 1) * limitNum
|
||||
|
||||
// 获取总数
|
||||
const totalResult = await db.select({ count: count() }).from(users).where(whereClause)
|
||||
const total = totalResult[0].count
|
||||
|
||||
// 排序逻辑
|
||||
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,
|
||||
createdAt: true,
|
||||
updatedAt: true
|
||||
},
|
||||
with: {
|
||||
identities: {
|
||||
columns: {
|
||||
provider: true,
|
||||
providerUsername: true
|
||||
},
|
||||
where: (identities, { eq }) => eq(identities.provider, 'github')
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// 处理用户列表,添加头像字段
|
||||
const formattedUsers = usersList.map((user) => ({
|
||||
...user,
|
||||
avatar: user.identities?.[0]?.providerUsername
|
||||
? `https://github.com/${user.identities[0].providerUsername}.png`
|
||||
: 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) {
|
||||
console.error('获取用户列表失败:', error)
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: '获取用户列表失败: ' + error.message
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,134 @@
|
||||
import bcrypt from 'bcryptjs'
|
||||
import { db } from '~/drizzle/db'
|
||||
import { users } from '~/drizzle/schema'
|
||||
import { eq } 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: '没有权限访问'
|
||||
})
|
||||
}
|
||||
|
||||
const body = await readBody(event)
|
||||
|
||||
// 验证必填字段
|
||||
if (!body.name || !body.username || !body.password) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '姓名、账号名和密码不能为空'
|
||||
})
|
||||
}
|
||||
|
||||
// 验证姓名和用户名只能包含汉字
|
||||
const chineseRegex = /^[\u4e00-\u9fa5]+$/
|
||||
if (!chineseRegex.test(body.name) || !chineseRegex.test(body.username)) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '姓名和账号名只能包含汉字'
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
// 检查用户名是否已存在
|
||||
const existingUserResult = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.username, body.username))
|
||||
.limit(1)
|
||||
const existingUser = existingUserResult[0]
|
||||
|
||||
if (existingUser) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '账号名已存在'
|
||||
})
|
||||
}
|
||||
|
||||
// 加密密码
|
||||
const hashedPassword = await bcrypt.hash(body.password, 10)
|
||||
|
||||
// 角色权限控制
|
||||
let validRole = 'USER'
|
||||
if (body.role && ['USER', 'TEACHER', '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', 'TEACHER', '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: body.name,
|
||||
username: body.username,
|
||||
password: hashedPassword,
|
||||
role: validRole,
|
||||
status: validStatus as 'active' | 'withdrawn' | 'graduate',
|
||||
grade: body.grade,
|
||||
class: 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]
|
||||
|
||||
// 清除相关缓存
|
||||
try {
|
||||
const { cache } = await import('~~/server/utils/cache-helpers')
|
||||
await cache.deletePattern('songs:*')
|
||||
await cache.deletePattern('stats:*')
|
||||
console.log('[Cache] 歌曲和统计缓存已清除(用户创建)')
|
||||
} catch (cacheError) {
|
||||
console.warn('[Cache] 清除缓存失败:', cacheError)
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
user: newUser,
|
||||
message: '用户创建成功'
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('创建用户失败:', error)
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: '创建用户失败'
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -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: '获取用户列表失败'
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,197 @@
|
||||
import { createError, defineEventHandler, getQuery } from 'h3'
|
||||
import { db } from '~/drizzle/db'
|
||||
import { users, userStatusLogs } from '~/drizzle/schema'
|
||||
import { and, count, desc, eq, ilike, or } 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,
|
||||
statusMessage: '没有权限访问'
|
||||
})
|
||||
}
|
||||
|
||||
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,
|
||||
userName: users.name,
|
||||
userUsername: users.username,
|
||||
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.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: users.name,
|
||||
userUsername: users.username,
|
||||
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.userId, users.id))
|
||||
.where(
|
||||
and(
|
||||
whereClause,
|
||||
or(
|
||||
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(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(eq(users.id, operatorIds[0])) // 这里需要用inArray,但先简化处理
|
||||
|
||||
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 || log.operatorName || '未知操作员',
|
||||
username: operatorMap.get(log.operatorId)?.username || log.operatorUsername || '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,
|
||||
statusMessage: '获取状态变更日志失败: ' + error.message
|
||||
})
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user