60 lines
1.9 KiB
TypeScript
60 lines
1.9 KiB
TypeScript
import type { NextRequest } from 'next/server'
|
|
import { NextResponse } from 'next/server'
|
|
import { getServerSession } from 'next-auth'
|
|
import { authOptions } from '@/lib/auth'
|
|
import { isDepartmentAdmin, isSystemAdmin } from '@/lib/department-permission'
|
|
import { getMaterialUploadStats } from '@/lib/admin-material-stats'
|
|
|
|
interface StatsSessionUser {
|
|
role?: string | null
|
|
managedDepartment?: string | null
|
|
department?: string | null
|
|
}
|
|
|
|
export async function GET(request: NextRequest) {
|
|
try {
|
|
const session = await getServerSession(authOptions)
|
|
const sessionUser = session?.user as StatsSessionUser | undefined
|
|
|
|
const role = sessionUser?.role
|
|
const canViewAllDepartments = isSystemAdmin(role)
|
|
const canViewDepartmentScope = isDepartmentAdmin(role)
|
|
const canViewStats = canViewAllDepartments || canViewDepartmentScope
|
|
const scopeDepartmentName = canViewDepartmentScope
|
|
? String(sessionUser?.managedDepartment || sessionUser?.department || '').trim()
|
|
: null
|
|
|
|
if (!session?.user || !canViewStats) {
|
|
return NextResponse.json({ error: '无权限' }, { status: 403 })
|
|
}
|
|
|
|
if (canViewDepartmentScope && !scopeDepartmentName) {
|
|
return NextResponse.json({ error: '当前账号未绑定部门,无法查看统计数据' }, { status: 400 })
|
|
}
|
|
|
|
const { searchParams } = new URL(request.url)
|
|
const startDate = searchParams.get('startDate')
|
|
const endDate = searchParams.get('endDate')
|
|
const departmentKey = searchParams.get('departmentKey')
|
|
|
|
const stats = await getMaterialUploadStats({
|
|
startDate,
|
|
endDate,
|
|
departmentKey,
|
|
scopeDepartmentName,
|
|
})
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
data: stats,
|
|
meta: {
|
|
canViewAllDepartments,
|
|
scopeDepartmentName,
|
|
},
|
|
})
|
|
} catch (error) {
|
|
console.error('[Admin Data Stats] GET error:', error)
|
|
return NextResponse.json({ error: '获取数据统计失败' }, { status: 500 })
|
|
}
|
|
}
|