42 lines
2.0 KiB
TypeScript
42 lines
2.0 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { getServerSession } from 'next-auth'
|
|
import { authOptions } from '@/lib/auth'
|
|
import { resolveBrandCenterAccessForUser } from '@/lib/brand-center-access'
|
|
import { isSuperAdmin } from '@/lib/department-permission'
|
|
import { getTeamFunctions, saveTeamFunction, TeamFunctionError } from '@/lib/team-functions'
|
|
import { teamFunctionInputSchema } from '@/lib/team-function-contract'
|
|
|
|
export const dynamic = 'force-dynamic'
|
|
|
|
async function identity() {
|
|
const session = await getServerSession(authOptions)
|
|
if (!session?.user?.id) return null
|
|
const user = session.user
|
|
if (!(await resolveBrandCenterAccessForUser(user.id, { role: user.role, isSuperAdmin: user.isSuperAdmin }))) return null
|
|
return { userId: user.id, canEdit: await isSuperAdmin(user.id) }
|
|
}
|
|
|
|
function failure(error: unknown) {
|
|
if (error instanceof TeamFunctionError) return NextResponse.json({ error: error.message }, { status: error.status })
|
|
console.error('团队职能请求失败', error)
|
|
return NextResponse.json({ error: '团队职能暂时无法读取或保存,请重试。' }, { status: 500 })
|
|
}
|
|
|
|
export async function GET() {
|
|
try {
|
|
const access = await identity()
|
|
if (!access) return NextResponse.json({ error: '无权访问品牌中心团队职能。' }, { status: 403 })
|
|
return NextResponse.json(await getTeamFunctions(access.canEdit), { headers: { 'Cache-Control': 'private, no-store' } })
|
|
} catch (error) { return failure(error) }
|
|
}
|
|
|
|
export async function PUT(request: NextRequest) {
|
|
try {
|
|
const access = await identity()
|
|
if (!access?.canEdit) return NextResponse.json({ error: '仅超级管理员可以维护团队职能。' }, { status: 403 })
|
|
const parsed = teamFunctionInputSchema.safeParse(await request.json().catch(() => null))
|
|
if (!parsed.success) return NextResponse.json({ error: '请检查负责人、说明和职责条目的格式或长度。' }, { status: 400 })
|
|
return NextResponse.json(await saveTeamFunction(parsed.data, access.userId))
|
|
} catch (error) { return failure(error) }
|
|
}
|