新增管理者介面

This commit is contained in:
2025-10-07 12:34:49 +08:00
parent 4482f6c3c7
commit b5bcc3d7a4
9 changed files with 1636 additions and 2 deletions

View File

@@ -0,0 +1,73 @@
import { NextRequest, NextResponse } from 'next/server'
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const { data, filename } = body
console.log(`🔍 後台管理 - 匯出 CSV: ${filename}`)
// 準備 CSV 數據
const headers = [
'ID',
'標題',
'遇到的困擾',
'期望的解決方式',
'預期效果',
'是否公開',
'電子郵件',
'狀態',
'類別',
'優先級',
'點讚數',
'創建時間',
'更新時間',
'用戶會話'
]
// 轉換數據為 CSV 格式
const csvRows = [headers.join(',')]
data.forEach((wish: any) => {
const row = [
wish.id,
`"${wish.title.replace(/"/g, '""')}"`,
`"${wish.current_pain.replace(/"/g, '""')}"`,
`"${wish.expected_solution.replace(/"/g, '""')}"`,
`"${(wish.expected_effect || '').replace(/"/g, '""')}"`,
wish.is_public ? '是' : '否',
`"${(wish.email || '').replace(/"/g, '""')}"`,
wish.status === 'active' ? '活躍' : '非活躍',
`"${(wish.category || '未分類').replace(/"/g, '""')}"`,
wish.priority,
wish.like_count,
`"${new Date(wish.created_at).toLocaleString('zh-TW')}"`,
`"${new Date(wish.updated_at).toLocaleString('zh-TW')}"`,
`"${wish.user_session.replace(/"/g, '""')}"`
]
csvRows.push(row.join(','))
})
const csvContent = csvRows.join('\n')
const csvBuffer = Buffer.from(csvContent, 'utf-8')
console.log(`✅ 成功生成 CSV 文件: ${data.length} 筆數據`)
// 返回文件
return new NextResponse(csvBuffer, {
status: 200,
headers: {
'Content-Type': 'text/csv; charset=utf-8',
'Content-Disposition': `attachment; filename="${encodeURIComponent(filename)}"`,
'Content-Length': csvBuffer.length.toString()
}
})
} catch (error) {
console.error('CSV 匯出錯誤:', error)
return NextResponse.json(
{ success: false, error: 'Failed to export CSV' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,84 @@
import { NextRequest, NextResponse } from 'next/server'
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const { data, filename } = body
console.log(`🔍 後台管理 - 匯出 Excel: ${filename}`)
// 動態導入 xlsx
const XLSX = await import('xlsx')
// 準備 Excel 數據
const excelData = data.map((wish: any) => ({
'ID': wish.id,
'標題': wish.title,
'遇到的困擾': wish.current_pain,
'期望的解決方式': wish.expected_solution,
'預期效果': wish.expected_effect || '',
'是否公開': wish.is_public ? '是' : '否',
'電子郵件': wish.email || '',
'狀態': wish.status === 'active' ? '活躍' : '非活躍',
'類別': wish.category || '未分類',
'優先級': wish.priority,
'點讚數': wish.like_count,
'創建時間': new Date(wish.created_at).toLocaleString('zh-TW'),
'更新時間': new Date(wish.updated_at).toLocaleString('zh-TW'),
'用戶會話': wish.user_session
}))
// 創建工作簿
const workbook = XLSX.utils.book_new()
// 創建工作表
const worksheet = XLSX.utils.json_to_sheet(excelData)
// 設置列寬
const columnWidths = [
{ wch: 8 }, // ID
{ wch: 30 }, // 標題
{ wch: 40 }, // 遇到的困擾
{ wch: 40 }, // 期望的解決方式
{ wch: 30 }, // 預期效果
{ wch: 10 }, // 是否公開
{ wch: 25 }, // 電子郵件
{ wch: 10 }, // 狀態
{ wch: 15 }, // 類別
{ wch: 8 }, // 優先級
{ wch: 8 }, // 點讚數
{ wch: 20 }, // 創建時間
{ wch: 20 }, // 更新時間
{ wch: 25 } // 用戶會話
]
worksheet['!cols'] = columnWidths
// 添加工作表到工作簿
XLSX.utils.book_append_sheet(workbook, worksheet, '困擾案例數據')
// 生成 Excel 文件
const excelBuffer = XLSX.write(workbook, {
type: 'buffer',
bookType: 'xlsx'
})
console.log(`✅ 成功生成 Excel 文件: ${excelData.length} 筆數據`)
// 返回文件
return new NextResponse(excelBuffer, {
status: 200,
headers: {
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'Content-Disposition': `attachment; filename="${encodeURIComponent(filename)}"`,
'Content-Length': excelBuffer.length.toString()
}
})
} catch (error) {
console.error('Excel 匯出錯誤:', error)
return NextResponse.json(
{ success: false, error: 'Failed to export Excel' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,107 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export async function GET(request: NextRequest) {
try {
console.log('🔍 後台管理 - 獲取統計數據...')
// 獲取基本統計
const totalWishes = await prisma.wish.count({
where: { status: 'active' }
})
const publicWishes = await prisma.wish.count({
where: {
status: 'active',
isPublic: true
}
})
const privateWishes = totalWishes - publicWishes
// 獲取總點讚數
const totalLikes = await prisma.wishLike.count()
// 獲取本週新增最近7天
const oneWeekAgo = new Date()
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7)
const recentWishes = await prisma.wish.count({
where: {
status: 'active',
createdAt: {
gte: oneWeekAgo
}
}
})
// 獲取所有困擾案例進行自動分類
const allWishes = await prisma.wish.findMany({
where: {
status: 'active'
},
select: {
id: true,
title: true,
currentPain: true,
expectedSolution: true,
category: true
}
})
// 導入分類函數
const { categorizeWishMultiple } = await import('@/lib/categorization')
// 對每個困擾案例進行分類
const categories: { [key: string]: number } = {}
allWishes.forEach(wish => {
// 如果資料庫中已有分類,使用資料庫的分類
if (wish.category && wish.category !== 'NULL' && wish.category !== '') {
categories[wish.category] = (categories[wish.category] || 0) + 1
} else {
// 否則進行自動分類
const wishData = {
title: wish.title,
currentPain: wish.currentPain,
expectedSolution: wish.expectedSolution
}
const categories_result = categorizeWishMultiple(wishData)
if (categories_result.length > 0) {
// 使用第一個分類的名稱,但排除「其他問題」
const primaryCategory = categories_result[0].name
if (primaryCategory !== '其他問題') {
categories[primaryCategory] = (categories[primaryCategory] || 0) + 1
}
}
// 注意:不統計「其他問題」和「未分類」的案例
}
})
const stats = {
totalWishes,
publicWishes,
privateWishes,
totalLikes,
recentWishes,
categories
}
console.log(`✅ 成功獲取統計數據: 總計 ${totalWishes} 個困擾案例`)
return NextResponse.json({
success: true,
data: stats
})
} catch (error) {
console.error('後台管理統計 API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch admin stats' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,74 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export async function GET(request: NextRequest) {
try {
console.log('🔍 後台管理 - 獲取所有困擾案例數據...')
// 獲取所有困擾案例(包含私密的)
const wishes = await prisma.$queryRaw`
SELECT id, title, current_pain, expected_solution, expected_effect,
is_public, email, images, user_session, status, category, priority,
created_at, updated_at
FROM wishes
WHERE status = 'active'
ORDER BY id DESC
LIMIT 1000
`
// 獲取點讚數
const wishIds = (wishes as any[]).map(w => w.id)
const likeCountMap = {}
if (wishIds.length > 0) {
const likes = await prisma.wishLike.findMany({
where: {
wishId: { in: wishIds }
},
select: {
wishId: true
}
})
// 計算點讚數
likes.forEach(like => {
likeCountMap[Number(like.wishId)] = (likeCountMap[Number(like.wishId)] || 0) + 1
})
}
// 轉換數據格式
const formattedWishes = (wishes as any[]).map((wish) => ({
id: Number(wish.id),
title: wish.title,
current_pain: wish.current_pain,
expected_solution: wish.expected_solution,
expected_effect: wish.expected_effect,
is_public: Boolean(wish.is_public),
email: wish.email,
images: wish.images,
user_session: wish.user_session,
status: wish.status,
category: wish.category,
priority: Number(wish.priority),
like_count: likeCountMap[Number(wish.id)] || 0,
created_at: wish.created_at ? new Date(wish.created_at).toISOString() : new Date().toISOString(),
updated_at: wish.updated_at ? new Date(wish.updated_at).toISOString() : new Date().toISOString()
}))
console.log(`✅ 成功獲取 ${formattedWishes.length} 筆困擾案例數據`)
return NextResponse.json({
success: true,
data: formattedWishes
})
} catch (error) {
console.error('後台管理 API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch admin data' },
{ status: 500 }
)
}
}