116 lines
3.0 KiB
TypeScript
116 lines
3.0 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { getServerSession } from 'next-auth'
|
|
import { authOptions } from '@/lib/auth'
|
|
import { prisma } from '@/lib/prisma'
|
|
import { buildDepartmentDescendants, isDepartmentWithinScope } from '@/lib/departments'
|
|
|
|
// Restore material from trash (admin only)
|
|
export async function POST(req: NextRequest) {
|
|
try {
|
|
const session = await getServerSession(authOptions)
|
|
|
|
if (!session || (session.user as any).role !== 'ADMIN') {
|
|
return NextResponse.json(
|
|
{ error: '无权限' },
|
|
{ status: 403 }
|
|
)
|
|
}
|
|
|
|
// 从请求body中获取id
|
|
const body = await req.json()
|
|
const id = body.id
|
|
|
|
if (!id) {
|
|
return NextResponse.json(
|
|
{ error: '缺少素材ID' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
const operatorId = (session.user as any).id
|
|
const operator = await prisma.user.findUnique({
|
|
where: { id: operatorId },
|
|
select: {
|
|
id: true,
|
|
department: true,
|
|
managedDepartment: true,
|
|
isSuperAdmin: true,
|
|
},
|
|
})
|
|
|
|
if (!operator) {
|
|
return NextResponse.json(
|
|
{ error: '当前用户不存在' },
|
|
{ status: 404 }
|
|
)
|
|
}
|
|
|
|
const material = await prisma.material.findUnique({
|
|
where: { id },
|
|
include: {
|
|
user: {
|
|
select: {
|
|
id: true,
|
|
department: true,
|
|
},
|
|
},
|
|
},
|
|
})
|
|
|
|
if (!material) {
|
|
return NextResponse.json(
|
|
{ error: '素材不存在' },
|
|
{ status: 404 }
|
|
)
|
|
}
|
|
|
|
if (!operator.isSuperAdmin) {
|
|
const isOwnMaterial = material.userId === operatorId
|
|
|
|
if (!isOwnMaterial) {
|
|
const operatorScope = (operator.managedDepartment || '').trim()
|
|
const targetDepartment = (material.user?.department || '').trim()
|
|
|
|
if (!operatorScope) {
|
|
return NextResponse.json(
|
|
{ error: '您只能恢复自己上传的素材' },
|
|
{ status: 403 }
|
|
)
|
|
}
|
|
|
|
let hasAccess =
|
|
targetDepartment === operatorScope ||
|
|
targetDepartment.startsWith(`${operatorScope}-`)
|
|
|
|
if (!hasAccess) {
|
|
const departments = await prisma.department.findMany({ select: { name: true } })
|
|
const descendantMap = buildDepartmentDescendants(departments)
|
|
hasAccess = isDepartmentWithinScope(operatorScope, targetDepartment, descendantMap)
|
|
}
|
|
|
|
if (!hasAccess) {
|
|
return NextResponse.json(
|
|
{ error: '您只能恢复自己或所管理部门成员上传的素材' },
|
|
{ status: 403 }
|
|
)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Restore material: set deletedAt to null
|
|
await prisma.material.update({
|
|
where: { id },
|
|
data: { deletedAt: null },
|
|
})
|
|
|
|
return NextResponse.json({ message: '恢复成功' })
|
|
} catch (error) {
|
|
console.error('[Materials] RESTORE error:', error)
|
|
return NextResponse.json(
|
|
{ error: '恢复失败' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|
|
|