2026-05-25 15:13:49 +08:00

108 lines
2.7 KiB
TypeScript

/**
* 系统完整性检查和修复API
*
* GET - 检查系统数据完整性
* POST - 修复系统数据完整性问题
*
* @module api/system/integrity
*/
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { isCurrentSuperAdmin } from '@/lib/admin-permissions'
import {
checkSystemIntegrity,
repairSystemIntegrity,
ensureBuiltinTemplates,
} from '@/lib/system-integrity'
/**
* GET /api/system/integrity
*
* 检查系统数据完整性
* 需要管理员权限
*/
export async function GET() {
try {
const session = await getServerSession(authOptions)
if (!session || (session.user as any)?.role !== 'ADMIN') {
return NextResponse.json({ error: '需要管理员权限' }, { status: 403 })
}
const result = await checkSystemIntegrity()
return NextResponse.json({
success: true,
...result,
})
} catch (error) {
console.error('[SystemIntegrity] 检查失败:', error)
return NextResponse.json(
{
success: false,
error: error instanceof Error ? error.message : '检查失败',
},
{ status: 500 }
)
}
}
/**
* POST /api/system/integrity
*
* 修复系统数据完整性问题
* 需要管理员权限
*
* 请求体(可选):
* {
* "createMissingBuiltinTemplates": true, // 是否创建缺失的内置模板
* "fixOrphanedMaterials": true, // 是否修复孤儿素材
* "quickFix": false // 快速修复模式(只确保内置模板存在)
* }
*/
export async function POST(req: NextRequest) {
try {
const session = await getServerSession(authOptions)
if (!session || !(await isCurrentSuperAdmin(session))) {
return NextResponse.json({ error: '仅最高权限账号可修复系统完整性问题' }, { status: 403 })
}
let body: any = {}
try {
body = await req.json()
} catch {
// 允许空请求体
}
const { quickFix = false, ...options } = body
if (quickFix) {
// 快速修复模式:只确保内置模板存在
const result = await ensureBuiltinTemplates()
return NextResponse.json({
success: result.errors.length === 0,
mode: 'quickFix',
...result,
})
}
// 完整修复模式
const result = await repairSystemIntegrity(options)
return NextResponse.json({
mode: 'full',
...result,
})
} catch (error) {
console.error('[SystemIntegrity] 修复失败:', error)
return NextResponse.json(
{
success: false,
error: error instanceof Error ? error.message : '修复失败',
},
{ status: 500 }
)
}
}