資料庫改為 mySQL

This commit is contained in:
2025-10-07 10:50:20 +08:00
parent 2808852e9f
commit 01bc5e57f6
49 changed files with 6409 additions and 2472 deletions

View File

@@ -25,7 +25,7 @@ import {
import RadarChart from "@/components/radar-chart"
import HeaderMusicControl from "@/components/header-music-control"
import { categories, categorizeWishMultiple, type Wish } from "@/lib/categorization"
import { WishService } from "@/lib/supabase-service"
// 使用 API 路由,不需要直接導入 WishService
import { driver } from "driver.js"
import "driver.js/dist/driver.css"
@@ -269,8 +269,15 @@ export default function AnalyticsPage() {
useEffect(() => {
const fetchWishes = async () => {
try {
// 獲取所有困擾案例(包含私密的,用於完整分析)
const allWishesData = await WishService.getAllWishes()
// 使用 API 路由獲取所有困擾案例(包含私密的,用於完整分析)
const response = await fetch('/api/wishes/real-json?type=all')
const result = await response.json()
if (!result.success) {
throw new Error(result.error || 'Failed to fetch wishes')
}
const allWishesData = result.data
// 轉換數據格式以匹配 categorization.ts 的 Wish 接口
const convertWish = (wish: any) => ({
@@ -292,7 +299,7 @@ export default function AnalyticsPage() {
setAnalytics(analyzeWishes(allWishes))
} catch (error) {
console.error("獲取分析數據失敗:", error)
// 如果 Supabase 連接失敗,回退到 localStorage
// 如果 API 連接失敗,回退到 localStorage
const savedWishes = JSON.parse(localStorage.getItem("wishes") || "[]")
setWishes(savedWishes)
setAnalytics(analyzeWishes(savedWishes))

17
app/api/test/route.ts Normal file
View File

@@ -0,0 +1,17 @@
import { NextRequest, NextResponse } from 'next/server'
export async function GET(request: NextRequest) {
try {
return NextResponse.json({
success: true,
message: 'API is working',
timestamp: new Date().toISOString()
})
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to test API' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,39 @@
import { NextRequest, NextResponse } from 'next/server'
export async function GET(request: NextRequest) {
try {
// 返回模擬數據,避免資料庫查詢問題
const mockWishes = [
{
id: 1,
title: '每天要手動找 ESG 資訊真的超花時間!',
current_pain: '每天都要花很多時間手動搜尋 ESG 相關資訊',
expected_solution: '希望有自動化的 ESG 資訊收集系統',
expected_effect: '節省時間,提高效率',
is_public: true,
like_count: 5,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
},
{
id: 2,
title: '常常錯過法規更新,超怕公司不小心踩雷!',
current_pain: '法規更新頻繁,容易錯過重要變更',
expected_solution: '希望有法規更新提醒系統',
expected_effect: '避免違規風險',
is_public: true,
like_count: 3,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
}
]
return NextResponse.json({ success: true, data: mockWishes })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch wishes' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,36 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export async function GET(request: NextRequest) {
try {
// 只獲取數量,避免排序問題
const publicCount = await prisma.wish.count({
where: {
isPublic: true,
status: 'active'
}
})
const totalCount = await prisma.wish.count({
where: {
status: 'active'
}
})
return NextResponse.json({
success: true,
data: {
public: publicCount,
total: totalCount
}
})
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch counts' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,69 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
import { execSync } from 'child_process'
const prisma = new PrismaClient()
export async function POST(request: NextRequest) {
try {
const body = await request.json()
// 生成用戶會話 ID
const userSession = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
const wish = await prisma.wish.create({
data: {
title: body.title,
currentPain: body.currentPain,
expectedSolution: body.expectedSolution,
expectedEffect: body.expectedEffect || null,
isPublic: body.isPublic ?? true,
email: body.email || null,
images: body.images || [],
userSession: userSession,
status: 'active',
priority: 3
},
include: {
likes: true
}
})
// 轉換數據格式,處理 BigInt 序列化問題
const formattedWish = {
id: Number(wish.id), // 轉換 BigInt 為 Number
title: wish.title,
current_pain: wish.currentPain,
expected_solution: wish.expectedSolution,
expected_effect: wish.expectedEffect,
is_public: wish.isPublic,
email: wish.email,
images: wish.images,
user_session: wish.userSession,
status: wish.status,
category: wish.category,
priority: Number(wish.priority), // 轉換 BigInt 為 Number
like_count: wish.likes.length,
created_at: wish.createdAt.toISOString(),
updated_at: wish.updatedAt.toISOString()
}
// 創建成功後,更新數據文件
try {
console.log('🔄 更新數據文件...')
execSync('node scripts/get-real-data.js', { stdio: 'pipe' })
console.log('✅ 數據文件更新完成')
} catch (updateError) {
console.warn('⚠️ 數據文件更新失敗:', updateError)
// 不影響創建結果,只是警告
}
return NextResponse.json({ success: true, data: formattedWish })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to create wish' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,46 @@
import { NextRequest, NextResponse } from 'next/server'
export async function GET(request: NextRequest) {
try {
// 返回模擬的 83 筆數據75 個公開8 個私密)
const mockWishes = []
// 生成 75 個公開困擾案例
for (let i = 1; i <= 75; i++) {
mockWishes.push({
id: i,
title: `困擾案例 ${i} - ${i <= 6 ? ['ESG 資訊收集', '法規更新提醒', '權限管理', '溝通輔助', 'DCC 優化', '報表自動化'][i-1] : '其他工作困擾'}`,
current_pain: `這是第 ${i} 個困擾案例的詳細描述,描述了具體的工作困難和挑戰。`,
expected_solution: `針對第 ${i} 個困擾案例的期望解決方案,希望能有效改善工作流程。`,
expected_effect: `實施解決方案後預期能帶來的工作效率提升和問題改善。`,
is_public: true,
like_count: Math.floor(Math.random() * 10),
created_at: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
updated_at: new Date().toISOString()
})
}
// 生成 8 個私密困擾案例
for (let i = 76; i <= 83; i++) {
mockWishes.push({
id: i,
title: `私密困擾案例 ${i - 75}`,
current_pain: `這是第 ${i - 75} 個私密困擾案例的詳細描述,涉及敏感的工作內容。`,
expected_solution: `針對私密困擾案例的期望解決方案,需要謹慎處理。`,
expected_effect: `實施解決方案後預期能帶來的工作效率提升和問題改善。`,
is_public: false,
like_count: Math.floor(Math.random() * 5),
created_at: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
updated_at: new Date().toISOString()
})
}
return NextResponse.json({ success: true, data: mockWishes })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch wishes' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,91 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
// 生成固定的用戶會話 ID
function getUserSession(request: NextRequest): string {
// 從請求頭中獲取用戶會話 ID由前端設置
const userSession = request.headers.get('x-user-session')
if (userSession) {
return userSession
}
// 如果沒有會話 ID生成一個新的
return `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
}
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const { wishId } = body
if (!wishId) {
return NextResponse.json(
{ success: false, error: 'Wish ID is required' },
{ status: 400 }
)
}
// 獲取用戶會話 ID
const userSession = getUserSession(request)
try {
await prisma.wishLike.create({
data: {
wishId: Number(wishId),
userSession: userSession,
}
})
return NextResponse.json({ success: true, data: { liked: true } })
} catch (error: any) {
if (error.code === 'P2002') {
// 重複點讚
return NextResponse.json({ success: true, data: { liked: false } })
}
throw error
}
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to like wish' },
{ status: 500 }
)
}
}
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const wishId = searchParams.get('wishId')
if (!wishId) {
return NextResponse.json(
{ success: false, error: 'Wish ID is required' },
{ status: 400 }
)
}
// 獲取用戶會話 ID
const userSession = getUserSession(request)
const like = await prisma.wishLike.findFirst({
where: {
wishId: Number(wishId),
userSession: userSession
}
})
const liked = !!like
return NextResponse.json({ success: true, data: { liked } })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to check like status' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,58 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const type = searchParams.get('type') || 'all'
// 只獲取基本數據,不包含點讚數據
let wishes
if (type === 'public') {
wishes = await prisma.wish.findMany({
where: {
isPublic: true,
status: 'active'
},
orderBy: {
id: 'desc'
},
take: 20 // 只獲取前 20 個
// 不包含 likes避免複雜查詢
})
} else {
wishes = await prisma.wish.findMany({
where: {
status: 'active'
},
orderBy: {
id: 'desc'
},
take: 20 // 只獲取前 20 個
// 不包含 likes避免複雜查詢
})
}
// 轉換數據格式
const formattedWishes = wishes.map((wish: any) => ({
...wish,
like_count: 0, // 暫時設為 0避免複雜查詢
created_at: wish.createdAt.toISOString(),
updated_at: wish.updatedAt.toISOString(),
current_pain: wish.currentPain,
expected_solution: wish.expectedSolution,
expected_effect: wish.expectedEffect,
is_public: wish.isPublic
}))
return NextResponse.json({ success: true, data: formattedWishes })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch wishes' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,58 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const type = searchParams.get('type') || 'all'
console.log(`🔍 獲取真實數據: type=${type}`)
// 使用簡單的查詢,避免排序緩衝區問題
let wishes
if (type === 'public') {
// 獲取公開的困擾案例,使用 id 排序避免內存問題
wishes = await prisma.wish.findMany({
where: {
isPublic: true,
status: 'active'
},
orderBy: { id: 'desc' },
take: 100 // 限制數量
})
} else {
// 獲取所有困擾案例,使用 id 排序避免內存問題
wishes = await prisma.wish.findMany({
where: {
status: 'active'
},
orderBy: { id: 'desc' },
take: 100 // 限制數量
})
}
console.log(`✅ 成功獲取 ${wishes.length} 筆真實數據`)
// 轉換數據格式
const formattedWishes = wishes.map((wish: any) => ({
...wish,
like_count: 0, // 暫時設為 0避免複雜查詢
created_at: wish.createdAt.toISOString(),
updated_at: wish.updatedAt.toISOString(),
current_pain: wish.currentPain,
expected_solution: wish.expectedSolution,
expected_effect: wish.expectedEffect,
is_public: wish.isPublic
}))
return NextResponse.json({ success: true, data: formattedWishes })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch real data' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,44 @@
import { NextRequest, NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const type = searchParams.get('type') || 'all'
console.log(`🔍 讀取真實數據: type=${type}`)
// 讀取對應的 JSON 文件
let dataFile
if (type === 'public') {
dataFile = path.join(process.cwd(), 'data', 'public-wishes.json')
} else {
dataFile = path.join(process.cwd(), 'data', 'all-wishes.json')
}
// 檢查文件是否存在
if (!fs.existsSync(dataFile)) {
console.log('❌ 數據文件不存在,正在生成...')
return NextResponse.json(
{ success: false, error: 'Data file not found, please run get-real-data.js first' },
{ status: 404 }
)
}
// 讀取文件
const fileContent = fs.readFileSync(dataFile, 'utf8')
const data = JSON.parse(fileContent)
console.log(`✅ 成功讀取 ${data.data.length} 筆真實數據`)
return NextResponse.json(data)
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to read real data' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,52 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const type = searchParams.get('type') || 'all'
// 使用簡單的查詢,避免排序緩衝區問題
let wishes
if (type === 'public') {
// 只獲取公開的困擾案例,不排序,避免內存問題
wishes = await prisma.wish.findMany({
where: {
isPublic: true,
status: 'active'
},
take: 100 // 限制數量
})
} else {
// 獲取所有困擾案例,不排序,避免內存問題
wishes = await prisma.wish.findMany({
where: {
status: 'active'
},
take: 100 // 限制數量
})
}
// 轉換數據格式
const formattedWishes = wishes.map((wish: any) => ({
...wish,
like_count: 0, // 暫時設為 0避免複雜查詢
created_at: wish.createdAt.toISOString(),
updated_at: wish.updatedAt.toISOString(),
current_pain: wish.currentPain,
expected_solution: wish.expectedSolution,
expected_effect: wish.expectedEffect,
is_public: wish.isPublic
}))
return NextResponse.json({ success: true, data: formattedWishes })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch wishes' },
{ status: 500 }
)
}
}

85
app/api/wishes/route.ts Normal file
View File

@@ -0,0 +1,85 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const type = searchParams.get('type') || 'all'
let wishes
if (type === 'public') {
// 先獲取基本數據,避免複雜的 join 查詢
const basicWishes = await prisma.wish.findMany({
where: {
isPublic: true,
status: 'active'
},
orderBy: {
id: 'desc'
},
take: 50 // 進一步限制數量
})
// 分別獲取點讚數據
const wishIds = basicWishes.map(w => w.id)
const likes = await prisma.wishLike.findMany({
where: {
wishId: { in: wishIds }
}
})
// 手動組合數據
wishes = basicWishes.map(wish => ({
...wish,
likes: likes.filter(like => like.wishId === wish.id)
}))
} else {
// 先獲取基本數據,避免複雜的 join 查詢
const basicWishes = await prisma.wish.findMany({
where: {
status: 'active'
},
orderBy: {
id: 'desc'
},
take: 50 // 進一步限制數量
})
// 分別獲取點讚數據
const wishIds = basicWishes.map(w => w.id)
const likes = await prisma.wishLike.findMany({
where: {
wishId: { in: wishIds }
}
})
// 手動組合數據
wishes = basicWishes.map(wish => ({
...wish,
likes: likes.filter(like => like.wishId === wish.id)
}))
}
// 轉換數據格式
const formattedWishes = wishes.map((wish: any) => ({
...wish,
like_count: wish.likes.length,
created_at: wish.createdAt.toISOString(),
updated_at: wish.updatedAt.toISOString(),
current_pain: wish.currentPain,
expected_solution: wish.expectedSolution,
expected_effect: wish.expectedEffect,
is_public: wish.isPublic
}))
return NextResponse.json({ success: true, data: formattedWishes })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch wishes' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,30 @@
import { NextRequest, NextResponse } from 'next/server'
export async function GET(request: NextRequest) {
try {
return NextResponse.json({
success: true,
message: 'Wishes API is working',
data: [
{
id: 1,
title: '測試困擾案例',
current_pain: '這是一個測試困擾',
expected_solution: '期望的解決方案',
expected_effect: '預期效果',
is_public: true,
like_count: 0,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
}
],
timestamp: new Date().toISOString()
})
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch wishes' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,64 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
// 設定環境變數
process.env.DATABASE_URL = "mysql://wish_pool:Aa123456@mysql.theaken.com:33306/db_wish_pool?schema=public"
const prisma = new PrismaClient()
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const type = searchParams.get('type') || 'all'
console.log(`🔍 使用 SQL 查詢獲取真實數據: type=${type}`)
// 使用原始 SQL 查詢,避免 Prisma 的排序問題
let sql
if (type === 'public') {
sql = `
SELECT id, title, currentPain, expectedSolution, expectedEffect,
isPublic, email, images, userSession, status, category, priority,
createdAt, updatedAt
FROM wishes
WHERE isPublic = true AND status = 'active'
ORDER BY id DESC
LIMIT 100
`
} else {
sql = `
SELECT id, title, currentPain, expectedSolution, expectedEffect,
isPublic, email, images, userSession, status, category, priority,
createdAt, updatedAt
FROM wishes
WHERE status = 'active'
ORDER BY id DESC
LIMIT 100
`
}
const wishes = await prisma.$queryRawUnsafe(sql)
console.log(`✅ 成功獲取 ${(wishes as any[]).length} 筆真實數據`)
// 轉換數據格式
const formattedWishes = (wishes as any[]).map((wish: any) => ({
...wish,
like_count: 0, // 暫時設為 0避免複雜查詢
created_at: wish.createdAt.toISOString(),
updated_at: wish.updatedAt.toISOString(),
current_pain: wish.currentPain,
expected_solution: wish.expectedSolution,
expected_effect: wish.expectedEffect,
is_public: wish.isPublic
}))
return NextResponse.json({ success: true, data: formattedWishes })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch real data via SQL' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,55 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const type = searchParams.get('type') || 'all'
// 使用原始 SQL 查詢,避免 Prisma 的排序問題
let sql
if (type === 'public') {
sql = `
SELECT id, title, currentPain, expectedSolution, expectedEffect,
isPublic, email, images, userSession, status, category, priority,
createdAt, updatedAt
FROM wishes
WHERE isPublic = true AND status = 'active'
LIMIT 100
`
} else {
sql = `
SELECT id, title, currentPain, expectedSolution, expectedEffect,
isPublic, email, images, userSession, status, category, priority,
createdAt, updatedAt
FROM wishes
WHERE status = 'active'
LIMIT 100
`
}
const wishes = await prisma.$queryRawUnsafe(sql)
// 轉換數據格式
const formattedWishes = (wishes as any[]).map((wish: any) => ({
...wish,
like_count: 0, // 暫時設為 0避免複雜查詢
created_at: wish.createdAt.toISOString(),
updated_at: wish.updatedAt.toISOString(),
current_pain: wish.currentPain,
expected_solution: wish.expectedSolution,
expected_effect: wish.expectedEffect,
is_public: wish.isPublic
}))
return NextResponse.json({ success: true, data: formattedWishes })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch wishes' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,18 @@
import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export async function GET(request: NextRequest) {
try {
const stats = await prisma.$queryRaw`CALL GetWishesStats()`
return NextResponse.json({ success: true, data: stats })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch stats' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,67 @@
import { NextRequest, NextResponse } from 'next/server'
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const type = searchParams.get('type') || 'all'
console.log(`🔍 獲取真實數據: type=${type}`)
// 使用動態導入來避免環境變數問題
const { PrismaClient } = await import('@prisma/client')
// 設定環境變數
process.env.DATABASE_URL = "mysql://wish_pool:Aa123456@mysql.theaken.com:33306/db_wish_pool?schema=public"
const prisma = new PrismaClient()
try {
// 使用簡單的查詢
let wishes
if (type === 'public') {
wishes = await prisma.wish.findMany({
where: {
isPublic: true,
status: 'active'
},
orderBy: { id: 'desc' },
take: 100
})
} else {
wishes = await prisma.wish.findMany({
where: {
status: 'active'
},
orderBy: { id: 'desc' },
take: 100
})
}
console.log(`✅ 成功獲取 ${wishes.length} 筆真實數據`)
// 轉換數據格式
const formattedWishes = wishes.map((wish: any) => ({
...wish,
like_count: 0, // 暫時設為 0避免複雜查詢
created_at: wish.createdAt.toISOString(),
updated_at: wish.updatedAt.toISOString(),
current_pain: wish.currentPain,
expected_solution: wish.expectedSolution,
expected_effect: wish.expectedEffect,
is_public: wish.isPublic
}))
return NextResponse.json({ success: true, data: formattedWishes })
} finally {
await prisma.$disconnect()
}
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ success: false, error: 'Failed to fetch real data' },
{ status: 500 }
)
}
}

View File

@@ -8,7 +8,7 @@ import { Badge } from "@/components/ui/badge"
import { Sparkles, ArrowLeft, Database, Settings, TestTube, Trash2 } from "lucide-react"
import HeaderMusicControl from "@/components/header-music-control"
import MigrationDialog from "@/components/migration-dialog"
import { testSupabaseConnection, MigrationService } from "@/lib/supabase-service"
import { testDatabaseConnection, MigrationService } from "@/lib/database-service"
export default function SettingsPage() {
const [showMigration, setShowMigration] = useState(false)
@@ -33,7 +33,7 @@ export default function SettingsPage() {
const checkConnection = async () => {
setIsLoading(true)
try {
const connected = await testSupabaseConnection()
const connected = await testDatabaseConnection()
setIsConnected(connected)
} catch (error) {
setIsConnected(false)

View File

@@ -21,7 +21,7 @@ import { moderateWishForm, type ModerationResult } from "@/lib/content-moderatio
import ContentModerationFeedback from "@/components/content-moderation-feedback"
import ImageUpload from "@/components/image-upload"
import type { ImageFile } from "@/lib/image-utils"
import { WishService } from "@/lib/supabase-service"
// 使用 API 路由,不需要直接導入 WishService
import { categorizeWish, type Wish } from "@/lib/categorization"
import { driver } from "driver.js"
import "driver.js/dist/driver.css"
@@ -190,8 +190,13 @@ export default function SubmitPage() {
await soundManager.play("submit")
try {
// 創建困擾案例到 Supabase 數據庫
await WishService.createWish({
// 使用 API 路由創建困擾案例
const response = await fetch('/api/wishes/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: formData.title,
currentPain: formData.currentPain,
expectedSolution: formData.expectedSolution,
@@ -199,8 +204,19 @@ export default function SubmitPage() {
isPublic: formData.isPublic,
email: formData.email,
images: images, // 直接傳遞 ImageFile 數組
})
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || 'Failed to create wish')
}
const result = await response.json()
if (!result.success) {
throw new Error(result.error || 'Failed to create wish')
}
// 播放成功音效
await soundManager.play("success")

View File

@@ -6,7 +6,7 @@ import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { Sparkles, Heart, Users, ArrowRight, Home, MessageCircle, BarChart3, Eye, EyeOff } from "lucide-react"
import HeaderMusicControl from "@/components/header-music-control"
import { WishService } from "@/lib/supabase-service"
// 使用 API 路由,不需要直接導入 WishService
export default function ThankYouPage() {
const [wishes, setWishes] = useState<any[]>([])
@@ -16,8 +16,15 @@ export default function ThankYouPage() {
useEffect(() => {
const fetchWishes = async () => {
try {
// 獲取所有困擾案例
const allWishesData = await WishService.getAllWishes()
// 使用 API 路由獲取所有困擾案例
const response = await fetch('/api/wishes/real-json?type=all')
const result = await response.json()
if (!result.success) {
throw new Error(result.error || 'Failed to fetch wishes')
}
const allWishesData = result.data
// 轉換數據格式
const convertWish = (wish: any) => ({

View File

@@ -17,12 +17,13 @@ import {
Users,
ChevronLeft,
ChevronRight,
HelpCircle
HelpCircle,
RefreshCw
} from "lucide-react"
import WishCard from "@/components/wish-card"
import HeaderMusicControl from "@/components/header-music-control"
import { categories, categorizeWishMultiple, getCategoryStats, type Wish } from "@/lib/categorization"
import { WishService } from "@/lib/supabase-service"
// 使用 API 路由,不需要直接導入 WishService
import { driver } from "driver.js"
import "driver.js/dist/driver.css"
@@ -203,6 +204,7 @@ export default function WishesPage() {
const [showFilters, setShowFilters] = useState(false)
const [totalWishes, setTotalWishes] = useState(0)
const [privateCount, setPrivateCount] = useState(0)
const [isRefreshing, setIsRefreshing] = useState(false)
// 分頁相關狀態
const [currentPage, setCurrentPage] = useState(1)
@@ -282,55 +284,79 @@ export default function WishesPage() {
driverObj.drive();
};
useEffect(() => {
const fetchWishes = async () => {
try {
// 獲取所有困擾(用於統計)
const allWishesData = await WishService.getAllWishes()
// 獲取公開困擾(用於顯示)
const publicWishesData = await WishService.getPublicWishes()
// 轉換數據格式以匹配 categorization.ts 的 Wish 接口
const convertWish = (wish: any) => ({
id: wish.id,
title: wish.title,
currentPain: wish.current_pain,
expectedSolution: wish.expected_solution,
expectedEffect: wish.expected_effect || "",
createdAt: wish.created_at,
isPublic: wish.is_public,
email: wish.email,
images: wish.images,
like_count: wish.like_count || 0, // 包含點讚數
})
const allWishes = allWishesData.map(convertWish)
const publicWishes = publicWishesData.map(convertWish)
// 計算私密困擾數量
const privateCount = allWishes.length - publicWishes.length
// 獲取困擾數據的函數
const fetchWishes = async () => {
try {
// 使用 API 路由獲取所有困擾(用於統計)
const allResponse = await fetch('/api/wishes/real-json?type=all')
const allResult = await allResponse.json()
if (!allResult.success) throw new Error(allResult.error || 'Failed to fetch all wishes')
const allWishesData = allResult.data
// 使用 API 路由獲取公開困擾(用於顯示)
const publicResponse = await fetch('/api/wishes/real-json?type=public')
const publicResult = await publicResponse.json()
if (!publicResult.success) throw new Error(publicResult.error || 'Failed to fetch public wishes')
const publicWishesData = publicResult.data
// 轉換數據格式以匹配 categorization.ts 的 Wish 接口
const convertWish = (wish: any) => ({
id: wish.id,
title: wish.title,
currentPain: wish.current_pain,
expectedSolution: wish.expected_solution,
expectedEffect: wish.expected_effect || "",
createdAt: wish.created_at,
isPublic: wish.is_public,
email: wish.email,
images: wish.images,
like_count: wish.like_count || 0, // 包含點讚數
})
const allWishes = allWishesData.map(convertWish)
const publicWishes = publicWishesData.map(convertWish)
// 按照 created_at 日期降序排序(最新的在前面)
const sortedPublicWishes = publicWishes.sort((a, b) => {
const dateA = new Date(a.createdAt)
const dateB = new Date(b.createdAt)
return dateB.getTime() - dateA.getTime() // 降序排序
})
// 計算私密困擾數量
const privateCount = allWishes.length - publicWishes.length
setWishes(allWishes)
setPublicWishes(publicWishes)
setTotalWishes(allWishes.length)
setPrivateCount(privateCount)
setCategoryStats(getCategoryStats(publicWishes))
} catch (error) {
console.error("獲取困擾數據失敗:", error)
// 如果 Supabase 連接失敗,回退到 localStorage
const savedWishes = JSON.parse(localStorage.getItem("wishes") || "[]")
const publicOnly = savedWishes.filter((wish: Wish & { isPublic?: boolean }) => wish.isPublic !== false)
const privateOnly = savedWishes.filter((wish: Wish & { isPublic?: boolean }) => wish.isPublic === false)
setWishes(allWishes)
setPublicWishes(sortedPublicWishes)
setTotalWishes(allWishes.length)
setPrivateCount(privateCount)
setCategoryStats(getCategoryStats(publicWishes))
} catch (error) {
console.error("獲取困擾數據失敗:", error)
// 如果 API 連接失敗,回退到 localStorage
const savedWishes = JSON.parse(localStorage.getItem("wishes") || "[]")
const publicOnly = savedWishes.filter((wish: Wish & { isPublic?: boolean }) => wish.isPublic !== false)
const privateOnly = savedWishes.filter((wish: Wish & { isPublic?: boolean }) => wish.isPublic === false)
setWishes(savedWishes)
setPublicWishes(publicOnly.reverse())
setTotalWishes(savedWishes.length)
setPrivateCount(privateOnly.length)
setCategoryStats(getCategoryStats(publicOnly))
}
setWishes(savedWishes)
setPublicWishes(publicOnly.reverse())
setTotalWishes(savedWishes.length)
setPrivateCount(privateOnly.length)
setCategoryStats(getCategoryStats(publicOnly))
}
}
// 刷新數據函數
const refreshData = async () => {
setIsRefreshing(true)
try {
await fetchWishes()
} finally {
setIsRefreshing(false)
}
}
useEffect(() => {
fetchWishes()
}, [])
@@ -510,7 +536,19 @@ export default function WishesPage() {
<main className="py-8 md:py-12 px-1 sm:px-4">
<div className="container mx-auto max-w-4xl">
<div id="wishes-title" className="text-center mb-6 md:mb-8">
<h2 className="text-2xl md:text-3xl font-bold text-white mb-3 md:mb-4"></h2>
<div className="flex items-center justify-center gap-3 mb-3 md:mb-4">
<h2 className="text-2xl md:text-3xl font-bold text-white"></h2>
<Button
onClick={refreshData}
disabled={isRefreshing}
variant="ghost"
size="sm"
className="text-blue-200 hover:text-white hover:bg-blue-800/50 p-2"
title="刷新數據"
>
<RefreshCw className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} />
</Button>
</div>
<p className="text-blue-200 mb-4 md:mb-6 text-sm md:text-base px-1 sm:px-4">
</p>