111 lines
2.6 KiB
TypeScript
111 lines
2.6 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { UserService } from '@/lib/services/database-service'
|
|
|
|
const userService = new UserService()
|
|
|
|
export async function PUT(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
try {
|
|
const { id: userId } = await params
|
|
const body = await request.json()
|
|
const { name, department, role, status } = body
|
|
|
|
if (!userId) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '用戶 ID 是必需的' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
if (!name || !department || !role || !status) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '請填寫所有必填欄位' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// 驗證狀態值
|
|
const validStatuses = ['active', 'inactive', 'invited']
|
|
if (!validStatuses.includes(status)) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '無效的狀態值' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// 驗證角色值
|
|
const validRoles = ['user', 'developer', 'admin']
|
|
if (!validRoles.includes(role)) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '無效的角色值' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
const result = await userService.updateUser(userId, {
|
|
name,
|
|
department,
|
|
role,
|
|
status
|
|
})
|
|
|
|
if (result.success) {
|
|
return NextResponse.json({
|
|
success: true,
|
|
message: '用戶資料更新成功',
|
|
data: result.user
|
|
})
|
|
} else {
|
|
return NextResponse.json(
|
|
{ success: false, error: result.error },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('更新用戶錯誤:', error)
|
|
return NextResponse.json(
|
|
{ success: false, error: '更新用戶時發生錯誤' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|
|
|
|
export async function DELETE(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
try {
|
|
const { id: userId } = await params
|
|
|
|
if (!userId) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '用戶 ID 是必需的' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
const result = await userService.deleteUser(userId)
|
|
|
|
if (result.success) {
|
|
return NextResponse.json({
|
|
success: true,
|
|
message: '用戶刪除成功'
|
|
})
|
|
} else {
|
|
return NextResponse.json(
|
|
{ success: false, error: result.error },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('刪除用戶錯誤:', error)
|
|
return NextResponse.json(
|
|
{ success: false, error: '刪除用戶時發生錯誤' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
} |