初次提交
This commit is contained in:
@@ -0,0 +1,181 @@
|
||||
import { db } from '~/drizzle/db'
|
||||
import { playTimes, schedules, songs, songReplayRequests } from '~/drizzle/schema'
|
||||
import { and, eq, gte, lte, inArray } from 'drizzle-orm'
|
||||
import { createSongSelectedNotification } from '~~/server/services/notificationService'
|
||||
import { cacheService } from '~~/server/services/cacheService'
|
||||
import { getClientIP } from '~~/server/utils/ip-utils'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// 检查用户认证和权限
|
||||
const user = event.context.user
|
||||
|
||||
if (!user) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
message: '未授权访问'
|
||||
})
|
||||
}
|
||||
|
||||
if (!['SONG_ADMIN', 'ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
message: '只有歌曲管理员及以上权限才能发布排期'
|
||||
})
|
||||
}
|
||||
|
||||
const body = await readBody(event)
|
||||
|
||||
// 验证必要参数
|
||||
if (!body.playDate || !body.songs || !Array.isArray(body.songs)) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '参数无效:需要 playDate 和 songs 数组'
|
||||
})
|
||||
}
|
||||
|
||||
const clientIP = getClientIP(event)
|
||||
const startTime = Date.now()
|
||||
|
||||
try {
|
||||
// 解析日期
|
||||
const inputDateStr =
|
||||
typeof body.playDate === 'string' ? body.playDate : body.playDate.toISOString()
|
||||
// 确保使用当天的开始时间(UTC)
|
||||
const playDate = new Date(inputDateStr + 'T00:00:00.000Z')
|
||||
const startOfDay = new Date(inputDateStr + 'T00:00:00.000Z')
|
||||
const endOfDay = new Date(inputDateStr + 'T23:59:59.999Z')
|
||||
const playTimeId = body.playTimeId ? parseInt(body.playTimeId) : null
|
||||
|
||||
// 获取所有涉及的歌曲详情(用于通知)
|
||||
const songIds = body.songs.map((s: any) => s.songId)
|
||||
if (songIds.length === 0) {
|
||||
// 如果列表为空,说明是清空排期,直接执行删除逻辑即可
|
||||
}
|
||||
|
||||
const songDetails =
|
||||
songIds.length > 0 ? await db.select().from(songs).where(inArray(songs.id, songIds)) : []
|
||||
|
||||
const songMap = new Map(songDetails.map((s: any) => [s.id, s]))
|
||||
|
||||
// 需要发送通知的列表
|
||||
const notificationsToSend: Array<{
|
||||
requesterId: number
|
||||
songId: number
|
||||
songInfo: { title: string; artist: string; playDate: Date }
|
||||
}> = []
|
||||
|
||||
// 开始事务
|
||||
await db.transaction(async (tx) => {
|
||||
// 1. 构建查询条件:指定日期 + (可选)指定时段
|
||||
const whereConditions = [
|
||||
gte(schedules.playDate, startOfDay),
|
||||
lte(schedules.playDate, endOfDay)
|
||||
]
|
||||
|
||||
if (playTimeId) {
|
||||
whereConditions.push(eq(schedules.playTimeId, playTimeId))
|
||||
}
|
||||
|
||||
// 2. 查找该时间段内已发布的排期(用于避免重复发送通知)
|
||||
const existingPublished = await tx
|
||||
.select({
|
||||
songId: schedules.songId
|
||||
})
|
||||
.from(schedules)
|
||||
.where(and(...whereConditions, eq(schedules.isDraft, false)))
|
||||
|
||||
const existingPublishedSongIds = new Set(existingPublished.map((s) => s.songId))
|
||||
|
||||
// 3. 删除该时间段内的所有排期(包括草稿和已发布)
|
||||
await tx.delete(schedules).where(and(...whereConditions))
|
||||
|
||||
// 4. 插入新的排期并处理通知
|
||||
const publishedAt = new Date()
|
||||
|
||||
for (const item of body.songs) {
|
||||
const song = songMap.get(item.songId)
|
||||
if (!song) {
|
||||
console.warn(`找不到歌曲 ID: ${item.songId},跳过排期`)
|
||||
continue
|
||||
}
|
||||
|
||||
// 插入排期
|
||||
await tx.insert(schedules).values({
|
||||
songId: item.songId,
|
||||
playDate: playDate,
|
||||
sequence: item.sequence,
|
||||
playTimeId: playTimeId,
|
||||
isDraft: false, // 直接发布
|
||||
publishedAt: publishedAt,
|
||||
updatedAt: publishedAt
|
||||
})
|
||||
|
||||
// 如果该歌曲之前未在此时间段发布过,则发送通知并更新重播状态
|
||||
if (!existingPublishedSongIds.has(item.songId)) {
|
||||
// 添加到通知列表,稍后发送
|
||||
notificationsToSend.push({
|
||||
requesterId: song.requesterId,
|
||||
songId: song.id,
|
||||
songInfo: {
|
||||
title: song.title,
|
||||
artist: song.artist,
|
||||
playDate: playDate
|
||||
}
|
||||
})
|
||||
|
||||
// 更新重播申请状态
|
||||
await tx
|
||||
.update(songReplayRequests)
|
||||
.set({ status: 'FULFILLED' })
|
||||
.where(
|
||||
and(eq(songReplayRequests.songId, song.id), eq(songReplayRequests.status, 'PENDING'))
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// 事务成功提交后,清除缓存
|
||||
try {
|
||||
await cacheService.clearSchedulesCache()
|
||||
await cacheService.clearSongsCache()
|
||||
console.log(`[Cache] 排期缓存和歌曲列表缓存已清除(批量发布排期)`)
|
||||
} catch (cacheError) {
|
||||
console.error('[Cache] 清除缓存失败:', cacheError)
|
||||
}
|
||||
|
||||
// 异步发送通知(不阻塞响应)
|
||||
Promise.allSettled(
|
||||
notificationsToSend.map((n) =>
|
||||
createSongSelectedNotification(n.requesterId, n.songId, n.songInfo, clientIP)
|
||||
)
|
||||
)
|
||||
.then((results) => {
|
||||
const successCount = results.filter((r) => r.status === 'fulfilled').length
|
||||
console.log(
|
||||
`[Notification] 批量发布通知发送完成: ${successCount}/${notificationsToSend.length} 成功`
|
||||
)
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('[Notification] 批量发送通知时发生未捕获错误:', err)
|
||||
})
|
||||
|
||||
console.log(`[Performance] 批量发布排期耗时: ${Date.now() - startTime}ms`)
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: '排期发布成功'
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('批量发布排期失败:', {
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
userId: user.id,
|
||||
ip: clientIP
|
||||
})
|
||||
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: error.message || '发布排期失败'
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,246 @@
|
||||
import { db } from '~/drizzle/db'
|
||||
import { playTimes, schedules, songs, songReplayRequests } from '~/drizzle/schema'
|
||||
import { and, desc, eq, gte, lte } from 'drizzle-orm'
|
||||
import { cacheService } from '~~/server/services/cacheService'
|
||||
import { getClientIP } from '~~/server/utils/ip-utils'
|
||||
|
||||
// 输入验证函数
|
||||
function validateInput(body: any) {
|
||||
const errors: string[] = []
|
||||
|
||||
// 验证songId
|
||||
if (!body.songId) {
|
||||
errors.push('歌曲ID不能为空')
|
||||
} else if (typeof body.songId !== 'number' || body.songId <= 0) {
|
||||
errors.push('歌曲ID必须是正整数')
|
||||
}
|
||||
|
||||
// 验证playDate
|
||||
if (!body.playDate) {
|
||||
errors.push('播放日期不能为空')
|
||||
} else {
|
||||
const dateStr = typeof body.playDate === 'string' ? body.playDate : body.playDate.toString()
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/
|
||||
if (!dateRegex.test(dateStr)) {
|
||||
errors.push('播放日期格式必须为YYYY-MM-DD')
|
||||
} else {
|
||||
const date = new Date(dateStr)
|
||||
if (isNaN(date.getTime())) {
|
||||
errors.push('播放日期格式无效')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 验证sequence(可选)
|
||||
if (body.sequence !== undefined && body.sequence !== null) {
|
||||
if (typeof body.sequence !== 'number' || body.sequence <= 0) {
|
||||
errors.push('序号必须是正整数')
|
||||
}
|
||||
}
|
||||
|
||||
// 验证playTimeId(可选)
|
||||
if (body.playTimeId !== undefined && body.playTimeId !== null) {
|
||||
if (typeof body.playTimeId !== 'number' || body.playTimeId <= 0) {
|
||||
errors.push('播放时间ID必须是正整数')
|
||||
}
|
||||
}
|
||||
|
||||
return errors
|
||||
}
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const startTime = Date.now()
|
||||
const clientIP = getClientIP(event)
|
||||
|
||||
try {
|
||||
// 检查用户认证和权限
|
||||
const user = event.context.user
|
||||
|
||||
if (!user) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
message: '未授权访问'
|
||||
})
|
||||
}
|
||||
|
||||
if (!['SONG_ADMIN', 'ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
message: '权限不足'
|
||||
})
|
||||
}
|
||||
|
||||
const body = await readBody(event)
|
||||
|
||||
// 输入验证
|
||||
const validationErrors = validateInput(body)
|
||||
if (validationErrors.length > 0) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: validationErrors.join('; ')
|
||||
})
|
||||
}
|
||||
|
||||
// 使用数据库事务确保数据一致性
|
||||
const result = await db.transaction(async (tx) => {
|
||||
// 检查歌曲是否存在
|
||||
const songResult = await tx.select().from(songs).where(eq(songs.id, body.songId)).limit(1)
|
||||
|
||||
const song = songResult[0]
|
||||
|
||||
if (!song) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
message: '歌曲不存在'
|
||||
})
|
||||
}
|
||||
|
||||
// 检查播放时间ID是否有效(如果提供)
|
||||
if (body.playTimeId) {
|
||||
const playTimeResult = await tx
|
||||
.select()
|
||||
.from(playTimes)
|
||||
.where(eq(playTimes.id, body.playTimeId))
|
||||
.limit(1)
|
||||
|
||||
if (playTimeResult.length === 0) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
message: '播放时间不存在'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 检查是否已经为该歌曲创建过排期或草稿,如果有则删除旧的
|
||||
const existingScheduleResult = await tx
|
||||
.select()
|
||||
.from(schedules)
|
||||
.where(eq(schedules.songId, body.songId))
|
||||
.limit(1)
|
||||
|
||||
const existingSchedule = existingScheduleResult[0]
|
||||
if (existingSchedule) {
|
||||
// 删除现有排期或草稿
|
||||
await tx.delete(schedules).where(eq(schedules.id, existingSchedule.id))
|
||||
|
||||
// 恢复该歌曲的重播申请状态为 PENDING
|
||||
// 只恢复状态为 FULFILLED 的申请
|
||||
const updatedRequests = await tx
|
||||
.update(songReplayRequests)
|
||||
.set({
|
||||
status: 'PENDING',
|
||||
updatedAt: new Date()
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(songReplayRequests.songId, body.songId),
|
||||
eq(songReplayRequests.status, 'FULFILLED')
|
||||
)
|
||||
)
|
||||
.returning()
|
||||
|
||||
if (updatedRequests.length > 0) {
|
||||
console.log(
|
||||
`恢复了 ${updatedRequests.length} 个重播申请状态为 PENDING(草稿保存时删除旧排期)`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 获取序号,如果未提供则查找当天最大序号+1
|
||||
let sequence = body.sequence || 1
|
||||
|
||||
if (!body.sequence) {
|
||||
// 解析输入的日期字符串
|
||||
const inputDateStr =
|
||||
typeof body.playDate === 'string' ? body.playDate : body.playDate.toISOString()
|
||||
|
||||
// 创建当天的开始和结束时间
|
||||
const startOfDay = new Date(inputDateStr + 'T00:00:00.000Z')
|
||||
const endOfDay = new Date(inputDateStr + 'T23:59:59.999Z')
|
||||
|
||||
// 查找当天的所有排期和草稿(包括草稿状态的)
|
||||
const sameDaySchedules = await tx
|
||||
.select()
|
||||
.from(schedules)
|
||||
.where(and(gte(schedules.playDate, startOfDay), lte(schedules.playDate, endOfDay)))
|
||||
.orderBy(desc(schedules.sequence))
|
||||
.limit(1)
|
||||
|
||||
if (sameDaySchedules.length > 0) {
|
||||
sequence = (sameDaySchedules[0].sequence || 0) + 1
|
||||
}
|
||||
}
|
||||
|
||||
// 解析输入的日期字符串,确保日期正确
|
||||
const inputDateStr =
|
||||
typeof body.playDate === 'string' ? body.playDate : body.playDate.toISOString()
|
||||
|
||||
// 直接使用输入的日期字符串,添加时间部分以避免时区问题
|
||||
const playDate = new Date(inputDateStr + 'T00:00:00.000Z')
|
||||
|
||||
// 创建草稿排期
|
||||
const scheduleResult = await tx
|
||||
.insert(schedules)
|
||||
.values({
|
||||
songId: body.songId,
|
||||
playDate: playDate,
|
||||
sequence: sequence,
|
||||
playTimeId: body.playTimeId || null,
|
||||
isDraft: true, // 标记为草稿
|
||||
publishedAt: null // 草稿状态下没有发布时间
|
||||
})
|
||||
.returning()
|
||||
|
||||
return {
|
||||
schedule: scheduleResult[0],
|
||||
song: {
|
||||
id: song.id,
|
||||
title: song.title,
|
||||
artist: song.artist,
|
||||
requesterId: song.requesterId
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// 清除相关缓存(在事务外执行,避免影响事务性能)
|
||||
try {
|
||||
await cacheService.clearSchedulesCache()
|
||||
await cacheService.clearSongsCache()
|
||||
console.log('[Cache] 排期缓存和歌曲列表缓存已清除(保存草稿)')
|
||||
} catch (cacheError) {
|
||||
console.error('[Cache] 清除缓存失败:', cacheError)
|
||||
// 缓存清除失败不应该影响主要操作的成功
|
||||
}
|
||||
|
||||
const responseData = {
|
||||
...result.schedule,
|
||||
song: result.song,
|
||||
isDraft: true,
|
||||
publishedAt: null,
|
||||
message: '排期草稿保存成功'
|
||||
}
|
||||
|
||||
console.log(`[Performance] 保存排期草稿耗时: ${Date.now() - startTime}ms`)
|
||||
|
||||
return responseData
|
||||
} catch (error: any) {
|
||||
console.error('保存排期草稿失败:', {
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
userId: event.context.user?.id,
|
||||
ip: clientIP,
|
||||
duration: Date.now() - startTime
|
||||
})
|
||||
|
||||
// 根据错误类型返回适当的错误信息
|
||||
if (error.statusCode) {
|
||||
throw error // 重新抛出已经格式化的错误
|
||||
}
|
||||
|
||||
// 对于未知错误,返回具体的错误信息
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: error.message || '服务器内部错误,请稍后重试'
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,407 @@
|
||||
import { db } from '~/drizzle/db'
|
||||
import {
|
||||
playTimes,
|
||||
schedules,
|
||||
songs,
|
||||
users,
|
||||
votes,
|
||||
songCollaborators,
|
||||
songReplayRequests
|
||||
} from '~/drizzle/schema'
|
||||
import { and, asc, count, eq, gte, lt, inArray, desc } from 'drizzle-orm'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// 检查用户身份验证和权限
|
||||
const user = event.context.user
|
||||
|
||||
if (!user) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
message: '未授权访问'
|
||||
})
|
||||
}
|
||||
|
||||
if (!['SONG_ADMIN', 'ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
message: '只有歌曲管理员及以上权限才能访问完整排期数据'
|
||||
})
|
||||
}
|
||||
|
||||
const query = getQuery(event)
|
||||
const { date, playTimeId, includeDrafts = 'true' } = query
|
||||
|
||||
try {
|
||||
// 构建查询条件
|
||||
const conditions = []
|
||||
|
||||
// 日期过滤
|
||||
if (date) {
|
||||
const targetDate = new Date(date as string)
|
||||
const startOfDay = new Date(
|
||||
targetDate.getFullYear(),
|
||||
targetDate.getMonth(),
|
||||
targetDate.getDate()
|
||||
)
|
||||
const endOfDay = new Date(
|
||||
targetDate.getFullYear(),
|
||||
targetDate.getMonth(),
|
||||
targetDate.getDate() + 1
|
||||
)
|
||||
|
||||
conditions.push(and(gte(schedules.playDate, startOfDay), lt(schedules.playDate, endOfDay)))
|
||||
}
|
||||
|
||||
// 播放时间过滤
|
||||
if (playTimeId) {
|
||||
conditions.push(eq(schedules.playTimeId, parseInt(playTimeId as string)))
|
||||
}
|
||||
|
||||
// 草稿包含过滤 - 默认包含草稿和已发布的排期
|
||||
if (includeDrafts === 'false') {
|
||||
conditions.push(eq(schedules.isDraft, false))
|
||||
} else if (includeDrafts === 'only') {
|
||||
conditions.push(eq(schedules.isDraft, true))
|
||||
}
|
||||
// 如果 includeDrafts === 'true' 或未指定,则包含两者(无需过滤)
|
||||
|
||||
const whereCondition = conditions.length > 0 ? and(...conditions) : undefined
|
||||
|
||||
// 获取完整的排期数据,包括草稿
|
||||
const schedulesData = await db
|
||||
.select({
|
||||
id: schedules.id,
|
||||
createdAt: schedules.createdAt,
|
||||
updatedAt: schedules.updatedAt,
|
||||
playDate: schedules.playDate,
|
||||
sequence: schedules.sequence,
|
||||
played: schedules.played,
|
||||
playTimeId: schedules.playTimeId,
|
||||
isDraft: schedules.isDraft,
|
||||
publishedAt: schedules.publishedAt,
|
||||
songId: schedules.songId,
|
||||
songTitle: songs.title,
|
||||
songArtist: songs.artist,
|
||||
songRequesterId: songs.requesterId,
|
||||
songPlayed: songs.played,
|
||||
songCover: songs.cover,
|
||||
songMusicPlatform: songs.musicPlatform,
|
||||
songMusicId: songs.musicId,
|
||||
songSemester: songs.semester,
|
||||
songCreatedAt: songs.createdAt,
|
||||
requesterName: users.name,
|
||||
requesterGrade: users.grade,
|
||||
requesterClass: users.class,
|
||||
playTimeName: playTimes.name,
|
||||
playTimeStartTime: playTimes.startTime,
|
||||
playTimeEndTime: playTimes.endTime,
|
||||
playTimeEnabled: playTimes.enabled
|
||||
})
|
||||
.from(schedules)
|
||||
.innerJoin(songs, eq(schedules.songId, songs.id))
|
||||
.leftJoin(users, eq(songs.requesterId, users.id))
|
||||
.leftJoin(playTimes, eq(schedules.playTimeId, playTimes.id))
|
||||
.where(whereCondition)
|
||||
.orderBy(asc(schedules.playDate), asc(schedules.sequence), asc(schedules.createdAt))
|
||||
|
||||
// 获取所有用户用于姓名消歧
|
||||
const allUsers = await db
|
||||
.select({
|
||||
id: users.id,
|
||||
name: users.name,
|
||||
grade: users.grade,
|
||||
class: users.class
|
||||
})
|
||||
.from(users)
|
||||
|
||||
// 创建姓名到用户的映射用于消歧
|
||||
const nameToUsers = new Map()
|
||||
allUsers.forEach((user) => {
|
||||
if (user.name) {
|
||||
if (!nameToUsers.has(user.name)) {
|
||||
nameToUsers.set(user.name, [])
|
||||
}
|
||||
nameToUsers.get(user.name).push(user)
|
||||
}
|
||||
})
|
||||
|
||||
// 获取每首歌的投票数
|
||||
const songIds = schedulesData.map((s) => s.songId)
|
||||
const voteCounts =
|
||||
songIds.length > 0
|
||||
? await Promise.all(
|
||||
songIds.map(async (songId) => {
|
||||
const voteCountResult = await db
|
||||
.select({ count: count() })
|
||||
.from(votes)
|
||||
.where(eq(votes.songId, songId))
|
||||
return { songId, count: voteCountResult[0].count }
|
||||
})
|
||||
)
|
||||
: []
|
||||
|
||||
const voteCountMap = new Map(voteCounts.map((v) => [v.songId, v.count]))
|
||||
|
||||
// 获取联合投稿人信息
|
||||
const collaboratorsMap = new Map()
|
||||
|
||||
if (songIds.length > 0) {
|
||||
const collaboratorsData = await db
|
||||
.select({
|
||||
songId: songCollaborators.songId,
|
||||
user: {
|
||||
id: users.id,
|
||||
name: users.name,
|
||||
grade: users.grade,
|
||||
class: users.class
|
||||
}
|
||||
})
|
||||
.from(songCollaborators)
|
||||
.leftJoin(users, eq(songCollaborators.userId, users.id))
|
||||
.where(
|
||||
and(inArray(songCollaborators.songId, songIds), eq(songCollaborators.status, 'ACCEPTED'))
|
||||
)
|
||||
|
||||
collaboratorsData.forEach((c) => {
|
||||
if (!collaboratorsMap.has(c.songId)) {
|
||||
collaboratorsMap.set(c.songId, [])
|
||||
}
|
||||
if (c.user) {
|
||||
collaboratorsMap.get(c.songId).push(c.user)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 获取重播申请信息
|
||||
const replayRequestCountsMap = new Map()
|
||||
const replayRequestersMap = new Map()
|
||||
|
||||
if (songIds.length > 0) {
|
||||
// 获取每首歌的重播申请数量(统计 PENDING 和 FULFILLED 状态)
|
||||
const replayCountsData = await db
|
||||
.select({
|
||||
songId: songReplayRequests.songId,
|
||||
count: count(songReplayRequests.id)
|
||||
})
|
||||
.from(songReplayRequests)
|
||||
.where(
|
||||
and(
|
||||
inArray(songReplayRequests.songId, songIds),
|
||||
inArray(songReplayRequests.status, ['PENDING', 'FULFILLED'])
|
||||
)
|
||||
)
|
||||
.groupBy(songReplayRequests.songId)
|
||||
|
||||
replayCountsData.forEach((r) => {
|
||||
replayRequestCountsMap.set(r.songId, r.count)
|
||||
})
|
||||
|
||||
// 获取重播申请人列表(前5个)
|
||||
const replayRequestersData = await db
|
||||
.select({
|
||||
songId: songReplayRequests.songId,
|
||||
user: {
|
||||
id: users.id,
|
||||
name: users.name,
|
||||
grade: users.grade,
|
||||
class: users.class
|
||||
},
|
||||
status: songReplayRequests.status,
|
||||
createdAt: songReplayRequests.createdAt
|
||||
})
|
||||
.from(songReplayRequests)
|
||||
.innerJoin(users, eq(songReplayRequests.userId, users.id))
|
||||
.where(
|
||||
and(
|
||||
inArray(songReplayRequests.songId, songIds),
|
||||
inArray(songReplayRequests.status, ['PENDING', 'FULFILLED'])
|
||||
)
|
||||
)
|
||||
.orderBy(desc(songReplayRequests.createdAt))
|
||||
|
||||
replayRequestersData.forEach((r) => {
|
||||
if (!replayRequestersMap.has(r.songId)) {
|
||||
replayRequestersMap.set(r.songId, [])
|
||||
}
|
||||
// 只保留前5个
|
||||
if (replayRequestersMap.get(r.songId).length < 5) {
|
||||
replayRequestersMap.get(r.songId).push({
|
||||
id: r.user.id,
|
||||
name: r.user.name || '未知用户',
|
||||
grade: r.user.grade,
|
||||
class: r.user.class,
|
||||
status: r.status
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 格式化响应数据
|
||||
const formattedSchedules = schedulesData.map((schedule) => {
|
||||
const dateOnly = schedule.playDate
|
||||
|
||||
// 处理投稿人姓名消歧
|
||||
let requesterName = schedule.requesterName || 'Unknown User'
|
||||
|
||||
const sameNameUsers = nameToUsers.get(requesterName)
|
||||
if (sameNameUsers && sameNameUsers.length > 1) {
|
||||
if (schedule.requesterGrade) {
|
||||
const sameGradeUsers = sameNameUsers.filter(
|
||||
(u: { id: number; name: string | null; grade: string | null; class: string | null }) =>
|
||||
u.grade === schedule.requesterGrade
|
||||
)
|
||||
|
||||
if (sameGradeUsers.length > 1 && schedule.requesterClass) {
|
||||
requesterName = `${requesterName}(${schedule.requesterGrade} ${schedule.requesterClass})`
|
||||
} else {
|
||||
requesterName = `${requesterName}(${schedule.requesterGrade})`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 辅助函数:格式化显示名称 (用于联合投稿人)
|
||||
const formatDisplayName = (userObj: any) => {
|
||||
if (!userObj || !userObj.name) return '未知用户'
|
||||
let displayName = userObj.name
|
||||
|
||||
const sameNameUsers = nameToUsers.get(displayName)
|
||||
if (sameNameUsers && sameNameUsers.length > 1) {
|
||||
if (userObj.grade) {
|
||||
const sameGradeUsers = sameNameUsers.filter((u: any) => u.grade === userObj.grade)
|
||||
if (sameGradeUsers.length > 1 && userObj.class) {
|
||||
displayName = `${displayName}(${userObj.grade} ${userObj.class})`
|
||||
} else {
|
||||
displayName = `${displayName}(${userObj.grade})`
|
||||
}
|
||||
}
|
||||
}
|
||||
return displayName
|
||||
}
|
||||
|
||||
const collaborators = collaboratorsMap.get(schedule.songId) || []
|
||||
const formattedCollaborators = collaborators.map((c: any) => ({
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
displayName: formatDisplayName(c),
|
||||
grade: c.grade,
|
||||
class: c.class
|
||||
}))
|
||||
|
||||
// 获取重播申请信息
|
||||
const replayRequestCount = replayRequestCountsMap.get(schedule.songId) || 0
|
||||
const replayRequesters = replayRequestersMap.get(schedule.songId) || []
|
||||
const formattedReplayRequesters = replayRequesters.map((r: any) => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
displayName: formatDisplayName(r),
|
||||
grade: r.grade,
|
||||
class: r.class,
|
||||
status: r.status
|
||||
}))
|
||||
|
||||
// 判断是否为重播:有重播申请(PENDING 或 FULFILLED)
|
||||
const isReplaySong = replayRequestCount > 0
|
||||
|
||||
return {
|
||||
id: schedule.id,
|
||||
createdAt: schedule.createdAt,
|
||||
updatedAt: schedule.updatedAt,
|
||||
playDate: dateOnly.toISOString().split('T')[0],
|
||||
sequence: schedule.sequence || 1,
|
||||
played: schedule.played || false,
|
||||
playTimeId: schedule.playTimeId,
|
||||
// 草稿状态信息
|
||||
isDraft: schedule.isDraft || false,
|
||||
publishedAt: schedule.publishedAt,
|
||||
status: schedule.isDraft ? 'draft' : 'published',
|
||||
playTime: schedule.playTimeName
|
||||
? {
|
||||
id: schedule.playTimeId,
|
||||
name: schedule.playTimeName,
|
||||
startTime: schedule.playTimeStartTime,
|
||||
endTime: schedule.playTimeEndTime,
|
||||
enabled: schedule.playTimeEnabled
|
||||
}
|
||||
: null,
|
||||
song: {
|
||||
id: schedule.songId,
|
||||
title: schedule.songTitle,
|
||||
artist: schedule.songArtist,
|
||||
requester: requesterName,
|
||||
requesterId: schedule.songRequesterId,
|
||||
requesterGrade: schedule.requesterGrade || null,
|
||||
requesterClass: schedule.requesterClass || null,
|
||||
collaborators: formattedCollaborators,
|
||||
voteCount: voteCountMap.get(schedule.songId) || 0,
|
||||
played: schedule.songPlayed || false,
|
||||
cover: schedule.songCover || null,
|
||||
musicPlatform: schedule.songMusicPlatform || null,
|
||||
musicId: schedule.songMusicId || null,
|
||||
semester: schedule.songSemester || null,
|
||||
createdAt: schedule.songCreatedAt,
|
||||
// 重播申请信息
|
||||
replayRequestCount: isReplaySong ? replayRequestCount : 0,
|
||||
replayRequesters: isReplaySong ? formattedReplayRequesters : [],
|
||||
isReplay: isReplaySong // 只有已播放过且有重播申请的才标记为重播
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// 按日期分组以便更好地组织
|
||||
const groupedByDate = {}
|
||||
formattedSchedules.forEach((schedule) => {
|
||||
const date = schedule.playDate
|
||||
if (!groupedByDate[date]) {
|
||||
groupedByDate[date] = {
|
||||
date,
|
||||
schedules: [],
|
||||
totalCount: 0,
|
||||
draftCount: 0,
|
||||
publishedCount: 0
|
||||
}
|
||||
}
|
||||
|
||||
groupedByDate[date].schedules.push(schedule)
|
||||
groupedByDate[date].totalCount++
|
||||
|
||||
if (schedule.isDraft) {
|
||||
groupedByDate[date].draftCount++
|
||||
} else {
|
||||
groupedByDate[date].publishedCount++
|
||||
}
|
||||
})
|
||||
|
||||
// 转换为数组并按日期排序
|
||||
const dateGroups = Object.values(groupedByDate).sort(
|
||||
(a: any, b: any) => new Date(a.date).getTime() - new Date(b.date).getTime()
|
||||
)
|
||||
|
||||
// 汇总统计
|
||||
const summary = {
|
||||
totalSchedules: formattedSchedules.length,
|
||||
draftCount: formattedSchedules.filter((s) => s.isDraft).length,
|
||||
publishedCount: formattedSchedules.filter((s) => !s.isDraft).length,
|
||||
dateRange: {
|
||||
startDate: dateGroups.length > 0 ? dateGroups[0].date : null,
|
||||
endDate: dateGroups.length > 0 ? dateGroups[dateGroups.length - 1].date : null
|
||||
},
|
||||
playTimeFilter: playTimeId ? parseInt(playTimeId as string) : null,
|
||||
includeDrafts: includeDrafts as string
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
summary,
|
||||
schedules: formattedSchedules,
|
||||
groupedByDate: dateGroups
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('获取完整排期数据失败:', error)
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: error.message || '获取完整排期数据失败'
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,137 @@
|
||||
import { and, eq, gte, inArray, lte } from 'drizzle-orm'
|
||||
import { db } from '~/drizzle/db'
|
||||
import { schedules, songs } from '~/drizzle/schema'
|
||||
import { cacheService } from '~~/server/services/cacheService'
|
||||
import { createSystemNotification } from '~~/server/services/notificationService'
|
||||
import { getClientIP } from '~~/server/utils/ip-utils'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = event.context.user
|
||||
if (!user || !['SONG_ADMIN', 'ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: '需要歌曲管理员及以上权限'
|
||||
})
|
||||
}
|
||||
|
||||
const body = await readBody(event)
|
||||
const fromDate = typeof body?.fromDate === 'string' ? body.fromDate.trim() : ''
|
||||
const toDate = typeof body?.toDate === 'string' ? body.toDate.trim() : ''
|
||||
|
||||
if (fromDate === toDate) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '目标日期不能与当前日期相同'
|
||||
})
|
||||
}
|
||||
|
||||
const fromStart = new Date(`${fromDate}T00:00:00.000Z`)
|
||||
const fromEnd = new Date(`${fromDate}T23:59:59.999Z`)
|
||||
const toPlayDate = new Date(`${toDate}T00:00:00.000Z`)
|
||||
const toStart = new Date(`${toDate}T00:00:00.000Z`)
|
||||
const toEnd = new Date(`${toDate}T23:59:59.999Z`)
|
||||
|
||||
if (
|
||||
Number.isNaN(fromStart.getTime()) ||
|
||||
Number.isNaN(fromEnd.getTime()) ||
|
||||
Number.isNaN(toPlayDate.getTime()) ||
|
||||
Number.isNaN(toStart.getTime()) ||
|
||||
Number.isNaN(toEnd.getTime()) ||
|
||||
fromStart.toISOString().split('T')[0] !== fromDate ||
|
||||
toPlayDate.toISOString().split('T')[0] !== toDate
|
||||
) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '日期无效,请使用 YYYY-MM-DD 格式并确保日期有效'
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
const clientIP = getClientIP(event)
|
||||
const moveResult = await db.transaction(async (tx) => {
|
||||
const existingOnToDate = await tx
|
||||
.select({ id: schedules.id })
|
||||
.from(schedules)
|
||||
.where(and(gte(schedules.playDate, toStart), lte(schedules.playDate, toEnd)))
|
||||
.limit(1)
|
||||
|
||||
if (existingOnToDate.length > 0) {
|
||||
throw createError({
|
||||
statusCode: 409,
|
||||
message: '目标日期已存在排期,无法迁移。请先清空目标日期的排期。'
|
||||
})
|
||||
}
|
||||
|
||||
const sourceSchedules = await tx
|
||||
.select({
|
||||
id: schedules.id,
|
||||
songId: schedules.songId,
|
||||
requesterId: songs.requesterId,
|
||||
songTitle: songs.title
|
||||
})
|
||||
.from(schedules)
|
||||
.innerJoin(songs, eq(schedules.songId, songs.id))
|
||||
.where(and(gte(schedules.playDate, fromStart), lte(schedules.playDate, fromEnd)))
|
||||
|
||||
if (sourceSchedules.length === 0) {
|
||||
return {
|
||||
movedCount: 0,
|
||||
movedSongs: []
|
||||
}
|
||||
}
|
||||
|
||||
const scheduleIds = sourceSchedules.map((item) => item.id)
|
||||
const updateTime = new Date()
|
||||
const movedSchedules = await tx
|
||||
.update(schedules)
|
||||
.set({
|
||||
playDate: toPlayDate,
|
||||
updatedAt: updateTime
|
||||
})
|
||||
.where(inArray(schedules.id, scheduleIds))
|
||||
.returning({
|
||||
id: schedules.id
|
||||
})
|
||||
|
||||
return {
|
||||
movedCount: movedSchedules.length,
|
||||
movedSongs: sourceSchedules
|
||||
}
|
||||
})
|
||||
|
||||
const notificationsToSend = moveResult.movedSongs.map((item) => {
|
||||
const message = `您投稿的歌曲《${item.songTitle}》原定于 ${fromDate} 播放,已调整至 ${toDate}。`
|
||||
return createSystemNotification(item.requesterId, '排期调整通知', message, clientIP)
|
||||
})
|
||||
|
||||
if (notificationsToSend.length > 0) {
|
||||
Promise.allSettled(notificationsToSend).catch((error) => {
|
||||
console.error('[Notification] 发送排期迁移通知失败:', error)
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
await cacheService.clearSchedulesCache()
|
||||
await cacheService.clearSongsCache()
|
||||
console.log('[Cache] 排期缓存和歌曲列表缓存已清除(迁移排期日期)')
|
||||
} catch (cacheError) {
|
||||
console.error('[Cache] 清除缓存失败:', cacheError)
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
fromDate,
|
||||
toDate,
|
||||
movedCount: moveResult.movedCount
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (error?.statusCode === 409) {
|
||||
throw error
|
||||
}
|
||||
console.error('迁移排期日期失败:', error)
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: error.message || '迁移排期日期失败'
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,291 @@
|
||||
import { db } from '~/drizzle/db'
|
||||
import { playTimes, schedules, songs, users, votes, songReplayRequests } from '~/drizzle/schema'
|
||||
import { and, asc, count, eq } from 'drizzle-orm'
|
||||
import { createSongSelectedNotification } from '~~/server/services/notificationService'
|
||||
import { cacheService } from '~~/server/services/cacheService'
|
||||
import { getBeijingTimestamp } from '~/utils/timeUtils'
|
||||
import { getClientIP } from '~~/server/utils/ip-utils'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// 检查用户认证和权限
|
||||
const user = event.context.user
|
||||
|
||||
if (!user) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
message: '未授权访问'
|
||||
})
|
||||
}
|
||||
|
||||
if (!['SONG_ADMIN', 'ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
message: '只有歌曲管理员及以上权限才能发布排期'
|
||||
})
|
||||
}
|
||||
|
||||
const body = await readBody(event)
|
||||
|
||||
if (!body.scheduleId) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: '排期ID不能为空'
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
// 检查草稿是否存在
|
||||
const draftResult = await db
|
||||
.select({
|
||||
id: schedules.id,
|
||||
songId: schedules.songId,
|
||||
playDate: schedules.playDate,
|
||||
sequence: schedules.sequence,
|
||||
playTimeId: schedules.playTimeId,
|
||||
isDraft: schedules.isDraft,
|
||||
publishedAt: schedules.publishedAt,
|
||||
song: {
|
||||
id: songs.id,
|
||||
title: songs.title,
|
||||
artist: songs.artist,
|
||||
requesterId: songs.requesterId
|
||||
}
|
||||
})
|
||||
.from(schedules)
|
||||
.innerJoin(songs, eq(schedules.songId, songs.id))
|
||||
.where(
|
||||
and(
|
||||
eq(schedules.id, body.scheduleId),
|
||||
eq(schedules.isDraft, true) // 确保是草稿状态
|
||||
)
|
||||
)
|
||||
.limit(1)
|
||||
|
||||
const draft = draftResult[0]
|
||||
|
||||
if (!draft) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
message: '找不到指定的排期草稿'
|
||||
})
|
||||
}
|
||||
|
||||
// 更新草稿为已发布状态
|
||||
const publishedAt = new Date(getBeijingTimestamp())
|
||||
|
||||
const publishResult = await db
|
||||
.update(schedules)
|
||||
.set({
|
||||
isDraft: false,
|
||||
publishedAt: publishedAt,
|
||||
updatedAt: publishedAt
|
||||
})
|
||||
.where(eq(schedules.id, body.scheduleId))
|
||||
.returning()
|
||||
|
||||
const publishedSchedule = publishResult[0]
|
||||
|
||||
if (!publishedSchedule) {
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: '发布排期失败'
|
||||
})
|
||||
}
|
||||
|
||||
// 获取客户端IP地址
|
||||
const clientIP = getClientIP(event)
|
||||
|
||||
// 发布后发送通知(这是与草稿保存的主要区别)
|
||||
await createSongSelectedNotification(
|
||||
draft.song.requesterId,
|
||||
draft.song.id,
|
||||
{
|
||||
title: draft.song.title,
|
||||
artist: draft.song.artist,
|
||||
playDate: draft.playDate
|
||||
},
|
||||
clientIP
|
||||
)
|
||||
|
||||
// 将该歌曲的所有待处理重播申请标记为已完成
|
||||
const updatedRequests = await db
|
||||
.update(songReplayRequests)
|
||||
.set({
|
||||
status: 'FULFILLED',
|
||||
updatedAt: new Date()
|
||||
})
|
||||
.where(
|
||||
and(eq(songReplayRequests.songId, draft.song.id), eq(songReplayRequests.status, 'PENDING'))
|
||||
)
|
||||
.returning()
|
||||
|
||||
if (updatedRequests.length > 0) {
|
||||
console.log(`发布排期:将 ${updatedRequests.length} 个重播申请标记为 FULFILLED`)
|
||||
}
|
||||
|
||||
// 清除相关缓存
|
||||
try {
|
||||
await cacheService.clearSchedulesCache()
|
||||
await cacheService.clearSongsCache()
|
||||
console.log('[Cache] 排期缓存和歌曲列表缓存已清除(发布排期)')
|
||||
} catch (cacheError) {
|
||||
console.error('[Cache] 清除缓存失败:', cacheError)
|
||||
}
|
||||
|
||||
// 重新缓存完整的排期列表
|
||||
try {
|
||||
// 获取所有已发布的排期数据
|
||||
const schedulesData = await db
|
||||
.select({
|
||||
id: schedules.id,
|
||||
playDate: schedules.playDate,
|
||||
sequence: schedules.sequence,
|
||||
played: schedules.played,
|
||||
playTimeId: schedules.playTimeId,
|
||||
isDraft: schedules.isDraft,
|
||||
publishedAt: schedules.publishedAt,
|
||||
songId: schedules.songId,
|
||||
songTitle: songs.title,
|
||||
songArtist: songs.artist,
|
||||
songRequesterId: songs.requesterId,
|
||||
songPlayed: songs.played,
|
||||
songCover: songs.cover,
|
||||
songMusicPlatform: songs.musicPlatform,
|
||||
songMusicId: songs.musicId,
|
||||
songSemester: songs.semester,
|
||||
requesterName: users.name,
|
||||
requesterGrade: users.grade,
|
||||
requesterClass: users.class,
|
||||
playTimeName: playTimes.name,
|
||||
playTimeStartTime: playTimes.startTime,
|
||||
playTimeEndTime: playTimes.endTime,
|
||||
playTimeEnabled: playTimes.enabled
|
||||
})
|
||||
.from(schedules)
|
||||
.innerJoin(songs, eq(schedules.songId, songs.id))
|
||||
.innerJoin(users, eq(songs.requesterId, users.id))
|
||||
.leftJoin(playTimes, eq(schedules.playTimeId, playTimes.id))
|
||||
.where(eq(schedules.isDraft, false)) // 只缓存已发布的排期
|
||||
.orderBy(asc(schedules.playDate))
|
||||
|
||||
// 获取所有用户的姓名列表,用于检测同名用户
|
||||
const allUsers = await db
|
||||
.select({
|
||||
id: users.id,
|
||||
name: users.name,
|
||||
grade: users.grade,
|
||||
class: users.class
|
||||
})
|
||||
.from(users)
|
||||
|
||||
// 创建姓名到用户数组的映射
|
||||
const nameToUsers = new Map()
|
||||
allUsers.forEach((user) => {
|
||||
if (user.name) {
|
||||
if (!nameToUsers.has(user.name)) {
|
||||
nameToUsers.set(user.name, [])
|
||||
}
|
||||
nameToUsers.get(user.name).push(user)
|
||||
}
|
||||
})
|
||||
|
||||
// 获取每首歌的投票数
|
||||
const songIds = schedulesData.map((s) => s.songId)
|
||||
const voteCounts = await Promise.all(
|
||||
songIds.map(async (songId) => {
|
||||
const voteCountResult = await db
|
||||
.select({ count: count() })
|
||||
.from(votes)
|
||||
.where(eq(votes.songId, songId))
|
||||
return { songId, count: voteCountResult[0].count }
|
||||
})
|
||||
)
|
||||
|
||||
const voteCountMap = new Map(voteCounts.map((v) => [v.songId, v.count]))
|
||||
|
||||
// 转换数据格式
|
||||
const formattedSchedules = schedulesData.map((schedule) => {
|
||||
const dateOnly = schedule.playDate
|
||||
|
||||
// 处理投稿人姓名,如果是同名用户则添加后缀
|
||||
let requesterName = schedule.requesterName || '未知用户'
|
||||
|
||||
const sameNameUsers = nameToUsers.get(requesterName)
|
||||
if (sameNameUsers && sameNameUsers.length > 1) {
|
||||
if (schedule.requesterGrade) {
|
||||
const sameGradeUsers = sameNameUsers.filter(
|
||||
(u: {
|
||||
id: number
|
||||
name: string | null
|
||||
grade: string | null
|
||||
class: string | null
|
||||
}) => u.grade === schedule.requesterGrade
|
||||
)
|
||||
|
||||
if (sameGradeUsers.length > 1 && schedule.requesterClass) {
|
||||
requesterName = `${requesterName}(${schedule.requesterGrade} ${schedule.requesterClass})`
|
||||
} else {
|
||||
requesterName = `${requesterName}(${schedule.requesterGrade})`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: schedule.id,
|
||||
playDate: dateOnly.toISOString().split('T')[0],
|
||||
sequence: schedule.sequence || 1,
|
||||
played: schedule.played || false,
|
||||
playTimeId: schedule.playTimeId,
|
||||
isDraft: schedule.isDraft,
|
||||
publishedAt: schedule.publishedAt,
|
||||
playTime: schedule.playTimeName
|
||||
? {
|
||||
id: schedule.playTimeId,
|
||||
name: schedule.playTimeName,
|
||||
startTime: schedule.playTimeStartTime,
|
||||
endTime: schedule.playTimeEndTime,
|
||||
enabled: schedule.playTimeEnabled
|
||||
}
|
||||
: null,
|
||||
song: {
|
||||
id: schedule.songId,
|
||||
title: schedule.songTitle,
|
||||
artist: schedule.songArtist,
|
||||
requester: requesterName,
|
||||
voteCount: voteCountMap.get(schedule.songId) || 0,
|
||||
played: schedule.songPlayed || false,
|
||||
cover: schedule.songCover || null,
|
||||
musicPlatform: schedule.songMusicPlatform || null,
|
||||
musicId: schedule.songMusicId || null,
|
||||
semester: schedule.songSemester || null
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const completeSchedules = formattedSchedules
|
||||
|
||||
// 重新缓存完整的排期列表
|
||||
if (completeSchedules && completeSchedules.length > 0) {
|
||||
await cacheService.setSchedulesList(completeSchedules)
|
||||
console.log(`[Cache] 已发布排期列表已重新缓存,数量: ${completeSchedules.length}`)
|
||||
} else {
|
||||
console.log('[Cache] 没有已发布排期数据需要缓存')
|
||||
}
|
||||
} catch (cacheError) {
|
||||
console.warn('[Cache] 重新缓存完整排期列表失败,但不影响排期发布:', cacheError)
|
||||
}
|
||||
|
||||
return {
|
||||
...draft,
|
||||
isDraft: false,
|
||||
publishedAt: publishedAt,
|
||||
message: '排期发布成功,通知已发送'
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('发布排期失败:', error)
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: error.message || '发布排期失败'
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,115 @@
|
||||
import { db, eq, schedules, songs, songReplayRequests, and } from '~/drizzle/db'
|
||||
import { cacheService } from '~~/server/services/cacheService'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// 验证管理员权限
|
||||
const user = event.context.user
|
||||
if (!user || !['SONG_ADMIN', 'ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: '需要歌曲管理员及以上权限'
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await readBody(event)
|
||||
const { scheduleId } = body
|
||||
|
||||
if (!scheduleId) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: '缺少排期ID'
|
||||
})
|
||||
}
|
||||
|
||||
const scheduleIdNumber = Number(scheduleId)
|
||||
|
||||
console.log(`准备删除排期 ID=${scheduleIdNumber}`)
|
||||
|
||||
// 先检查排期是否存在,并获取歌曲ID
|
||||
const existingSchedule = await db
|
||||
.select({
|
||||
id: schedules.id,
|
||||
songId: schedules.songId,
|
||||
songTitle: songs.title,
|
||||
songArtist: songs.artist
|
||||
})
|
||||
.from(schedules)
|
||||
.leftJoin(songs, eq(schedules.songId, songs.id))
|
||||
.where(eq(schedules.id, scheduleIdNumber))
|
||||
.limit(1)
|
||||
.then((rows) => rows[0])
|
||||
|
||||
if (!existingSchedule) {
|
||||
console.log(`排期不存在 ID=${scheduleIdNumber}`)
|
||||
return {
|
||||
success: false,
|
||||
message: '排期不存在或已被删除'
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`找到排期 ID=${scheduleIdNumber}, 歌曲=${existingSchedule.songTitle || '未知歌曲'}`)
|
||||
|
||||
// 删除排期
|
||||
const deletedSchedule = await db
|
||||
.delete(schedules)
|
||||
.where(eq(schedules.id, scheduleIdNumber))
|
||||
.returning()
|
||||
|
||||
console.log(`成功删除排期 ID=${scheduleIdNumber}`)
|
||||
|
||||
// 恢复该歌曲的重播申请状态为 PENDING
|
||||
// 只恢复状态不是 PENDING 的申请(可能是 FULFILLED 或其他状态)
|
||||
if (existingSchedule.songId) {
|
||||
const updatedRequests = await db
|
||||
.update(songReplayRequests)
|
||||
.set({
|
||||
status: 'PENDING',
|
||||
updatedAt: new Date()
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(songReplayRequests.songId, existingSchedule.songId),
|
||||
// 不恢复已拒绝的申请
|
||||
eq(songReplayRequests.status, 'FULFILLED')
|
||||
)
|
||||
)
|
||||
.returning()
|
||||
|
||||
if (updatedRequests.length > 0) {
|
||||
console.log(`恢复了 ${updatedRequests.length} 个重播申请状态为 PENDING`)
|
||||
}
|
||||
}
|
||||
|
||||
// 清除相关缓存
|
||||
try {
|
||||
await cacheService.clearSchedulesCache()
|
||||
await cacheService.clearSongsCache() // 清除歌曲列表缓存,确保scheduled状态更新
|
||||
console.log('[Cache] 排期缓存和歌曲列表缓存已清除(移除排期)')
|
||||
} catch (cacheError) {
|
||||
console.error('[Cache] 清除缓存失败:', cacheError)
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
schedule: deletedSchedule
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('移除排期失败:', error)
|
||||
|
||||
// 处理数据库特定错误
|
||||
if (error.message?.includes('not found') || error.message?.includes('does not exist')) {
|
||||
return {
|
||||
success: false,
|
||||
message: '排期不存在或已被删除'
|
||||
}
|
||||
}
|
||||
|
||||
// 确保返回一个成功=false的响应,而不是抛出错误
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || '移除排期失败',
|
||||
error: error.code || 'UNKNOWN_ERROR'
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
import { db, eq } from '~/drizzle/db'
|
||||
import { schedules } from '~/drizzle/schema'
|
||||
import { cacheService } from '~~/server/services/cacheService'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// 验证用户认证和权限
|
||||
const user = event.context.user
|
||||
if (!user || !['SONG_ADMIN', 'ADMIN', 'SUPER_ADMIN'].includes(user.role)) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: '需要歌曲管理员及以上权限'
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await readBody(event)
|
||||
const { schedules } = body
|
||||
|
||||
if (!schedules || !Array.isArray(schedules) || schedules.length === 0) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: '缺少排期数据'
|
||||
})
|
||||
}
|
||||
|
||||
// 批量更新排期顺序
|
||||
const results = await Promise.all(
|
||||
schedules.map(async (item) => {
|
||||
return db
|
||||
.update(schedules)
|
||||
.set({ sequence: item.sequence })
|
||||
.where(eq(schedules.id, Number(item.id)))
|
||||
})
|
||||
)
|
||||
|
||||
// 清除排期相关缓存
|
||||
try {
|
||||
await cacheService.clearSchedulesCache()
|
||||
await cacheService.clearSongsCache()
|
||||
console.log('[Cache] 排期缓存和歌曲列表缓存已清除(更新排期顺序)')
|
||||
} catch (cacheError) {
|
||||
console.error('[Cache] 清除缓存失败:', cacheError)
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
count: results.length
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('更新排期顺序失败:', error)
|
||||
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: error.message || '更新排期顺序失败'
|
||||
})
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user