Files
ai-showcase-platform/app/api/admin/users/route.ts

135 lines
3.7 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { UserService } from '@/lib/services/database-service'
const userService = new UserService()
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const page = parseInt(searchParams.get('page') || '1')
const limit = parseInt(searchParams.get('limit') || '10')
const search = searchParams.get('search') || ''
const department = searchParams.get('department') || ''
const role = searchParams.get('role') || ''
const status = searchParams.get('status') || ''
// 構建查詢條件
let whereConditions = ['is_active = TRUE']
let params: any[] = []
if (search) {
whereConditions.push('(name LIKE ? OR email LIKE ?)')
params.push(`%${search}%`, `%${search}%`)
}
if (department && department !== 'all') {
whereConditions.push('department = ?')
params.push(department)
}
if (role && role !== 'all') {
whereConditions.push('role = ?')
params.push(role)
}
if (status && status !== 'all') {
if (status === 'active') {
whereConditions.push('last_login IS NOT NULL AND last_login >= DATE_SUB(NOW(), INTERVAL 30 DAY)')
} else if (status === 'inactive') {
whereConditions.push('last_login IS NULL OR last_login < DATE_SUB(NOW(), INTERVAL 30 DAY)')
}
}
const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(' AND ')}` : ''
// 使用 UserService 的方法
const { users, total } = await userService.findAll({
search,
department,
role,
status,
page,
limit
})
const stats = await userService.getUserStats()
return NextResponse.json({
success: true,
data: {
users,
pagination: {
page,
limit,
total,
totalPages: Math.ceil(total / limit)
},
stats: {
totalUsers: stats?.total_users || 0,
activeUsers: stats?.active_users || 0,
adminCount: stats?.admin_count || 0,
developerCount: stats?.developer_count || 0,
inactiveUsers: stats?.inactive_users || 0,
newThisMonth: stats?.new_this_month || 0
}
}
})
} catch (error) {
console.error('獲取用戶列表錯誤:', error)
return NextResponse.json(
{ error: '獲取用戶列表時發生錯誤' },
{ status: 500 }
)
}
}
export async function POST(request: NextRequest) {
try {
const { email, role } = await request.json()
if (!email || !role) {
return NextResponse.json(
{ error: '請提供電子郵件和角色' },
{ status: 400 }
)
}
// 檢查郵箱是否已存在
const existingUser = await userService.findByEmail(email)
if (existingUser) {
return NextResponse.json(
{ error: '該電子郵件地址已被使用' },
{ status: 400 }
)
}
// 生成邀請 token
const { v4: uuidv4 } = require('uuid')
const invitationToken = uuidv4()
// 創建邀請記錄(這裡可以存儲到邀請表或臨時表)
// 暫時返回邀請連結
const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'
const invitationLink = `${baseUrl}/register?token=${invitationToken}&email=${encodeURIComponent(email)}&role=${encodeURIComponent(role)}`
return NextResponse.json({
success: true,
message: '用戶邀請已創建',
data: {
invitationLink,
token: invitationToken,
email,
role
}
})
} catch (error) {
console.error('創建用戶邀請錯誤:', error)
return NextResponse.json(
{ error: '創建用戶邀請時發生錯誤' },
{ status: 500 }
)
}
}