新增資料庫架構
This commit is contained in:
2
.gitattributes
vendored
2
.gitattributes
vendored
@@ -1,2 +0,0 @@
|
|||||||
# Auto detect text files and perform LF normalization
|
|
||||||
* text=auto
|
|
103
DEPLOYMENT-READY.md
Normal file
103
DEPLOYMENT-READY.md
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
# 🚀 心願星河 - 佈署就緒確認
|
||||||
|
|
||||||
|
## ✅ 資料清理完成
|
||||||
|
|
||||||
|
### 已清理的項目
|
||||||
|
- [x] 所有測試困擾案例 (wishes)
|
||||||
|
- [x] 點讚數據 (wishLikes)
|
||||||
|
- [x] 用戶點讚記錄 (userLikedWishes)
|
||||||
|
- [x] 背景音樂狀態 (backgroundMusicState)
|
||||||
|
|
||||||
|
### 初始狀態設定
|
||||||
|
- [x] 困擾案例:空陣列 `[]`
|
||||||
|
- [x] 點讚記錄:空物件 `{}`
|
||||||
|
- [x] 用戶記錄:空陣列 `[]`
|
||||||
|
- [x] 音樂設定:預設關閉狀態
|
||||||
|
|
||||||
|
## 🔍 佈署前最終檢查
|
||||||
|
|
||||||
|
### 功能驗證
|
||||||
|
- [ ] 首頁載入正常,許願瓶動畫運作
|
||||||
|
- [ ] 分享困擾頁面表單功能正常
|
||||||
|
- [ ] 聆聽心聲頁面顯示空狀態提示
|
||||||
|
- [ ] 問題洞察頁面顯示無資料狀態
|
||||||
|
- [ ] 感謝頁面跳轉正常
|
||||||
|
- [ ] 音效系統可正常開關
|
||||||
|
- [ ] 背景音樂控制正常
|
||||||
|
- [ ] 手機版隱私說明收放功能正常
|
||||||
|
|
||||||
|
### 響應式設計
|
||||||
|
- [ ] 手機版 (320px-768px) 顯示正常
|
||||||
|
- [ ] 平板版 (768px-1024px) 顯示正常
|
||||||
|
- [ ] 桌面版 (1024px+) 顯示正常
|
||||||
|
- [ ] 導航選單在各裝置正確顯示
|
||||||
|
- [ ] 表單在各裝置易於操作
|
||||||
|
|
||||||
|
### 數據狀態
|
||||||
|
- [ ] 所有統計數字顯示為 0
|
||||||
|
- [ ] 分類統計圖表顯示無資料狀態
|
||||||
|
- [ ] 搜尋和篩選功能正常
|
||||||
|
- [ ] 隱私設定功能正常運作
|
||||||
|
|
||||||
|
## 🎯 佈署建議
|
||||||
|
|
||||||
|
### 推薦平台
|
||||||
|
1. **Vercel** (推薦)
|
||||||
|
- 自動 CI/CD
|
||||||
|
- 優秀的 Next.js 支援
|
||||||
|
- 免費 SSL 憑證
|
||||||
|
- 全球 CDN
|
||||||
|
|
||||||
|
2. **Netlify**
|
||||||
|
- 簡單易用
|
||||||
|
- 自動佈署
|
||||||
|
- 表單處理功能
|
||||||
|
|
||||||
|
3. **Vercel/Netlify 替代方案**
|
||||||
|
- GitHub Pages
|
||||||
|
- Firebase Hosting
|
||||||
|
|
||||||
|
### 佈署步驟 (Vercel)
|
||||||
|
1. 將代碼推送到 GitHub
|
||||||
|
2. 連接 Vercel 到 GitHub 倉庫
|
||||||
|
3. 設定建構命令:`npm run build`
|
||||||
|
4. 設定輸出目錄:`out` 或 `dist`
|
||||||
|
5. 執行佈署
|
||||||
|
|
||||||
|
### 環境變數 (如需要)
|
||||||
|
目前應用程式不需要特殊環境變數,但如果未來需要:
|
||||||
|
- `NEXT_PUBLIC_APP_URL`: 應用程式網址
|
||||||
|
- `NEXT_PUBLIC_ANALYTICS_ID`: 分析追蹤 ID
|
||||||
|
|
||||||
|
## 🌟 佈署後驗證
|
||||||
|
|
||||||
|
### 立即檢查
|
||||||
|
1. 訪問所有頁面確認載入正常
|
||||||
|
2. 提交一個測試困擾確認流程完整
|
||||||
|
3. 檢查響應式設計在不同裝置
|
||||||
|
4. 測試音效和背景音樂功能
|
||||||
|
5. 驗證隱私設定功能
|
||||||
|
|
||||||
|
### 效能檢查
|
||||||
|
- 頁面載入速度 < 3 秒
|
||||||
|
- 動畫效果流暢
|
||||||
|
- 音效載入不影響頁面效能
|
||||||
|
- 圖片和資源正確載入
|
||||||
|
|
||||||
|
## 📞 技術支援
|
||||||
|
|
||||||
|
如遇到問題,請檢查:
|
||||||
|
1. 瀏覽器控制台是否有錯誤
|
||||||
|
2. 網路連線是否正常
|
||||||
|
3. 瀏覽器是否支援現代 JavaScript
|
||||||
|
4. 是否啟用了廣告攔截器
|
||||||
|
|
||||||
|
## 🎉 準備完成
|
||||||
|
|
||||||
|
**狀態**: ✅ 已準備好佈署
|
||||||
|
**版本**: v1.0.0
|
||||||
|
**清理時間**: ${new Date().toLocaleString('zh-TW')}
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**心願星河已準備好為用戶提供優質的職場困擾收集和分析服務!** 🌟
|
55
QUICK-START.md
Normal file
55
QUICK-START.md
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
# 🚀 心願星河 - 快速開始指南
|
||||||
|
|
||||||
|
## 📥 下載和設置
|
||||||
|
|
||||||
|
### 1. 下載專案
|
||||||
|
- 點擊 v0 右上角的 **"Download Code"** 按鈕
|
||||||
|
- 選擇下載方式並解壓縮
|
||||||
|
|
||||||
|
### 2. 安裝依賴
|
||||||
|
\`\`\`bash
|
||||||
|
cd wish-pool
|
||||||
|
chmod +x setup-supabase.sh
|
||||||
|
./setup-supabase.sh
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### 3. 創建 Supabase 項目
|
||||||
|
1. 前往 [Supabase Dashboard](https://supabase.com/dashboard)
|
||||||
|
2. 點擊 "New Project"
|
||||||
|
3. 填寫項目資訊並等待創建完成
|
||||||
|
|
||||||
|
### 4. 配置環境變數
|
||||||
|
編輯 `.env.local` 檔案:
|
||||||
|
\`\`\`env
|
||||||
|
NEXT_PUBLIC_SUPABASE_URL=https://your-project-id.supabase.co
|
||||||
|
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key-here
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### 5. 執行 SQL 腳本
|
||||||
|
在 Supabase Dashboard 的 SQL Editor 中,按順序執行:
|
||||||
|
1. `scripts/01-create-tables.sql`
|
||||||
|
2. `scripts/02-create-indexes.sql`
|
||||||
|
3. `scripts/03-create-views-functions.sql`
|
||||||
|
4. `scripts/04-setup-storage.sql`
|
||||||
|
5. `scripts/05-setup-rls.sql`
|
||||||
|
|
||||||
|
### 6. 測試連接
|
||||||
|
\`\`\`bash
|
||||||
|
npm run test-supabase
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### 7. 啟動應用
|
||||||
|
\`\`\`bash
|
||||||
|
npm run dev
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
## 🎯 重要提醒
|
||||||
|
|
||||||
|
- ✅ 必須在本地環境執行,不能在 v0 中完成
|
||||||
|
- ✅ 需要有 Supabase 帳號
|
||||||
|
- ✅ 按順序執行 SQL 腳本很重要
|
||||||
|
- ✅ 測試連接成功後再進行數據遷移
|
||||||
|
|
||||||
|
## 📞 需要幫助?
|
||||||
|
|
||||||
|
參考完整文檔:`SUPABASE-COMPLETE-SETUP.md`
|
369
SUPABASE-COMPLETE-SETUP.md
Normal file
369
SUPABASE-COMPLETE-SETUP.md
Normal file
@@ -0,0 +1,369 @@
|
|||||||
|
# 🚀 心願星河 - Supabase 完整建置指南
|
||||||
|
|
||||||
|
## 📋 目錄
|
||||||
|
- [前置準備](#前置準備)
|
||||||
|
- [Supabase 項目設置](#supabase-項目設置)
|
||||||
|
- [本地環境配置](#本地環境配置)
|
||||||
|
- [數據庫建置](#數據庫建置)
|
||||||
|
- [存儲服務設置](#存儲服務設置)
|
||||||
|
- [安全政策配置](#安全政策配置)
|
||||||
|
- [測試驗證](#測試驗證)
|
||||||
|
- [數據遷移](#數據遷移)
|
||||||
|
- [部署準備](#部署準備)
|
||||||
|
- [故障排除](#故障排除)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎯 前置準備
|
||||||
|
|
||||||
|
### 系統需求
|
||||||
|
- Node.js 18+
|
||||||
|
- npm 或 yarn
|
||||||
|
- 現代瀏覽器
|
||||||
|
- Supabase 帳號
|
||||||
|
|
||||||
|
### 預估時間
|
||||||
|
- 初次設置:30-45 分鐘
|
||||||
|
- 數據遷移:5-10 分鐘
|
||||||
|
- 測試驗證:10-15 分鐘
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🏗️ Supabase 項目設置
|
||||||
|
|
||||||
|
### 1. 創建新項目
|
||||||
|
1. 前往 [Supabase Dashboard](https://supabase.com/dashboard)
|
||||||
|
2. 點擊 **"New Project"**
|
||||||
|
3. 填寫項目資訊:
|
||||||
|
\`\`\`
|
||||||
|
Name: wish-pool-production
|
||||||
|
Organization: [選擇你的組織]
|
||||||
|
Database Password: [設置強密碼,請記住!]
|
||||||
|
Region: [選擇最近的區域,建議 ap-southeast-1]
|
||||||
|
\`\`\`
|
||||||
|
4. 點擊 **"Create new project"**
|
||||||
|
5. 等待 2-3 分鐘完成初始化
|
||||||
|
|
||||||
|
### 2. 獲取項目配置
|
||||||
|
項目創建完成後:
|
||||||
|
1. 進入項目 Dashboard
|
||||||
|
2. 左側選單 → **Settings** → **API**
|
||||||
|
3. 複製以下資訊:
|
||||||
|
\`\`\`
|
||||||
|
Project URL: https://[your-project-id].supabase.co
|
||||||
|
anon public key: eyJ... (很長的字串)
|
||||||
|
service_role key: eyJ... (僅在需要管理員功能時使用)
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ⚙️ 本地環境配置
|
||||||
|
|
||||||
|
### 1. 安裝依賴
|
||||||
|
\`\`\`bash
|
||||||
|
# 安裝 Supabase 客戶端
|
||||||
|
npm install @supabase/supabase-js
|
||||||
|
|
||||||
|
# 如果需要圖片處理功能
|
||||||
|
npm install sharp
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### 2. 環境變數設置
|
||||||
|
1. 複製環境變數範本:
|
||||||
|
\`\`\`bash
|
||||||
|
cp .env.local.example .env.local
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
2. 編輯 `.env.local`:
|
||||||
|
\`\`\`env
|
||||||
|
# Supabase 配置
|
||||||
|
NEXT_PUBLIC_SUPABASE_URL=https://your-project-id.supabase.co
|
||||||
|
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key-here
|
||||||
|
|
||||||
|
# 可選:管理員功能(謹慎使用)
|
||||||
|
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
|
||||||
|
|
||||||
|
# 應用配置
|
||||||
|
NEXT_PUBLIC_APP_URL=http://localhost:3000
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### 3. 驗證連接
|
||||||
|
\`\`\`bash
|
||||||
|
# 啟動開發服務器
|
||||||
|
npm run dev
|
||||||
|
|
||||||
|
# 檢查控制台是否有 Supabase 連接錯誤
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🗄️ 數據庫建置
|
||||||
|
|
||||||
|
### 執行順序很重要!請按照以下順序執行 SQL 腳本:
|
||||||
|
|
||||||
|
### 步驟 1: 創建基礎表格
|
||||||
|
1. 進入 Supabase Dashboard
|
||||||
|
2. 左側選單 → **SQL Editor**
|
||||||
|
3. 點擊 **"New Query"**
|
||||||
|
4. 複製並執行 `scripts/01-create-tables.sql`
|
||||||
|
5. 確認執行成功(無錯誤訊息)
|
||||||
|
|
||||||
|
### 步驟 2: 創建索引和觸發器
|
||||||
|
1. 新建查詢
|
||||||
|
2. 複製並執行 `scripts/02-create-indexes.sql`
|
||||||
|
3. 確認所有索引創建成功
|
||||||
|
|
||||||
|
### 步驟 3: 創建視圖和函數
|
||||||
|
1. 新建查詢
|
||||||
|
2. 複製並執行 `scripts/03-create-views-functions.sql`
|
||||||
|
3. 確認視圖和函數創建成功
|
||||||
|
|
||||||
|
### 步驟 4: 設置存儲服務
|
||||||
|
1. 新建查詢
|
||||||
|
2. 複製並執行 `scripts/04-setup-storage.sql`
|
||||||
|
3. 檢查 Storage → Buckets 是否出現新的桶
|
||||||
|
|
||||||
|
### 步驟 5: 配置安全政策
|
||||||
|
1. 新建查詢
|
||||||
|
2. 複製並執行 `scripts/05-setup-rls.sql`
|
||||||
|
3. 確認 RLS 政策設置完成
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📁 存儲服務設置
|
||||||
|
|
||||||
|
### 存儲桶說明
|
||||||
|
- **wish-images**: 主要圖片存儲(5MB 限制)
|
||||||
|
- **wish-thumbnails**: 縮圖存儲(1MB 限制)
|
||||||
|
|
||||||
|
### 支援格式
|
||||||
|
- JPEG, JPG, PNG, WebP, GIF
|
||||||
|
- 自動壓縮和優化
|
||||||
|
- CDN 加速分發
|
||||||
|
|
||||||
|
### 存儲政策
|
||||||
|
- 公開讀取:所有人可查看圖片
|
||||||
|
- 限制上傳:防止濫用
|
||||||
|
- 自動清理:定期清理孤立圖片
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔒 安全政策配置
|
||||||
|
|
||||||
|
### Row Level Security (RLS)
|
||||||
|
所有表格都啟用了 RLS,確保數據安全:
|
||||||
|
|
||||||
|
#### wishes 表格
|
||||||
|
- ✅ 公開困擾案例:所有人可查看
|
||||||
|
- ✅ 私密困擾案例:僅統計使用
|
||||||
|
- ✅ 插入權限:所有人可提交
|
||||||
|
|
||||||
|
#### wish_likes 表格
|
||||||
|
- ✅ 查看權限:用於統計顯示
|
||||||
|
- ✅ 插入權限:所有人可點讚
|
||||||
|
- ✅ 防重複:同一用戶不可重複點讚
|
||||||
|
|
||||||
|
#### user_settings 表格
|
||||||
|
- ✅ 個人設定:用戶只能管理自己的設定
|
||||||
|
- ✅ 會話隔離:基於 session ID 區分用戶
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🧪 測試驗證
|
||||||
|
|
||||||
|
### 1. 數據庫連接測試
|
||||||
|
\`\`\`sql
|
||||||
|
-- 在 SQL Editor 中執行
|
||||||
|
SELECT 'Database connection successful!' as status;
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### 2. 表格結構驗證
|
||||||
|
\`\`\`sql
|
||||||
|
-- 檢查所有表格是否存在
|
||||||
|
SELECT table_name
|
||||||
|
FROM information_schema.tables
|
||||||
|
WHERE table_schema = 'public'
|
||||||
|
ORDER BY table_name;
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### 3. 存儲服務測試
|
||||||
|
1. 進入 Storage → wish-images
|
||||||
|
2. 嘗試上傳一張測試圖片
|
||||||
|
3. 確認可以正常預覽
|
||||||
|
|
||||||
|
### 4. 功能測試清單
|
||||||
|
- [ ] 提交新的困擾案例
|
||||||
|
- [ ] 上傳圖片附件
|
||||||
|
- [ ] 點讚功能
|
||||||
|
- [ ] 查看統計數據
|
||||||
|
- [ ] 背景音樂設定保存
|
||||||
|
- [ ] 響應式設計正常
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔄 數據遷移
|
||||||
|
|
||||||
|
### 自動遷移流程
|
||||||
|
1. 啟動應用程式
|
||||||
|
2. 如果檢測到本地數據,會自動顯示遷移對話框
|
||||||
|
3. 點擊 **"開始遷移"**
|
||||||
|
4. 等待遷移完成
|
||||||
|
5. 驗證數據完整性
|
||||||
|
|
||||||
|
### 手動遷移(如需要)
|
||||||
|
\`\`\`javascript
|
||||||
|
// 在瀏覽器控制台執行
|
||||||
|
console.log('Local wishes:', JSON.parse(localStorage.getItem('wishes') || '[]'));
|
||||||
|
console.log('Local likes:', JSON.parse(localStorage.getItem('wishLikes') || '{}'));
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### 遷移後清理
|
||||||
|
\`\`\`javascript
|
||||||
|
// 確認遷移成功後,清理本地數據
|
||||||
|
localStorage.removeItem('wishes');
|
||||||
|
localStorage.removeItem('wishLikes');
|
||||||
|
localStorage.removeItem('userLikedWishes');
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 部署準備
|
||||||
|
|
||||||
|
### 1. 環境變數設置
|
||||||
|
在部署平台(Vercel/Netlify)設置:
|
||||||
|
\`\`\`
|
||||||
|
NEXT_PUBLIC_SUPABASE_URL=your-production-url
|
||||||
|
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-production-key
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### 2. 生產環境優化
|
||||||
|
\`\`\`sql
|
||||||
|
-- 執行生產環境優化
|
||||||
|
SELECT optimize_database_performance();
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### 3. 備份設置
|
||||||
|
1. 進入 Supabase Dashboard
|
||||||
|
2. Settings → Database → Backups
|
||||||
|
3. 確認自動備份已啟用
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔧 故障排除
|
||||||
|
|
||||||
|
### 常見問題
|
||||||
|
|
||||||
|
#### 1. 連接失敗
|
||||||
|
**症狀**: `Failed to connect to Supabase`
|
||||||
|
**解決方案**:
|
||||||
|
- 檢查環境變數是否正確
|
||||||
|
- 確認 Supabase 項目狀態正常
|
||||||
|
- 檢查網路連接
|
||||||
|
|
||||||
|
#### 2. RLS 政策錯誤
|
||||||
|
**症狀**: `Row Level Security policy violation`
|
||||||
|
**解決方案**:
|
||||||
|
\`\`\`sql
|
||||||
|
-- 檢查 RLS 政策
|
||||||
|
SELECT * FROM pg_policies WHERE tablename = 'wishes';
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
#### 3. 存儲上傳失敗
|
||||||
|
**症狀**: 圖片上傳失敗
|
||||||
|
**解決方案**:
|
||||||
|
- 檢查檔案大小(<5MB)
|
||||||
|
- 確認檔案格式支援
|
||||||
|
- 檢查存儲桶政策
|
||||||
|
|
||||||
|
#### 4. 性能問題
|
||||||
|
**症狀**: 查詢速度慢
|
||||||
|
**解決方案**:
|
||||||
|
\`\`\`sql
|
||||||
|
-- 檢查索引使用情況
|
||||||
|
EXPLAIN ANALYZE SELECT * FROM wishes_with_likes LIMIT 10;
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### 日誌檢查
|
||||||
|
1. Supabase Dashboard → Logs
|
||||||
|
2. 查看 Database、API、Storage 日誌
|
||||||
|
3. 過濾錯誤和警告訊息
|
||||||
|
|
||||||
|
### 性能監控
|
||||||
|
\`\`\`sql
|
||||||
|
-- 檢查數據庫性能
|
||||||
|
SELECT * FROM get_performance_stats();
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📊 維護建議
|
||||||
|
|
||||||
|
### 定期維護任務
|
||||||
|
|
||||||
|
#### 每週
|
||||||
|
- [ ] 檢查錯誤日誌
|
||||||
|
- [ ] 監控存儲使用量
|
||||||
|
- [ ] 清理孤立圖片
|
||||||
|
|
||||||
|
#### 每月
|
||||||
|
- [ ] 分析查詢性能
|
||||||
|
- [ ] 檢查備份完整性
|
||||||
|
- [ ] 更新統計數據
|
||||||
|
|
||||||
|
#### 每季
|
||||||
|
- [ ] 檢查安全政策
|
||||||
|
- [ ] 優化數據庫索引
|
||||||
|
- [ ] 評估擴展需求
|
||||||
|
|
||||||
|
### 清理腳本
|
||||||
|
\`\`\`sql
|
||||||
|
-- 清理 30 天前的孤立圖片
|
||||||
|
SELECT cleanup_orphaned_images();
|
||||||
|
|
||||||
|
-- 更新統計數據
|
||||||
|
REFRESH MATERIALIZED VIEW wishes_stats_cache;
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎉 完成檢查清單
|
||||||
|
|
||||||
|
設置完成後,請確認以下項目:
|
||||||
|
|
||||||
|
### 基礎設置
|
||||||
|
- [ ] Supabase 項目創建成功
|
||||||
|
- [ ] 環境變數配置正確
|
||||||
|
- [ ] 所有 SQL 腳本執行成功
|
||||||
|
- [ ] 存儲桶創建完成
|
||||||
|
|
||||||
|
### 功能測試
|
||||||
|
- [ ] 可以提交新困擾案例
|
||||||
|
- [ ] 圖片上傳功能正常
|
||||||
|
- [ ] 點讚功能運作正常
|
||||||
|
- [ ] 統計數據顯示正確
|
||||||
|
- [ ] 用戶設定保存成功
|
||||||
|
|
||||||
|
### 安全檢查
|
||||||
|
- [ ] RLS 政策生效
|
||||||
|
- [ ] 無法訪問他人私密數據
|
||||||
|
- [ ] 存儲權限設置正確
|
||||||
|
|
||||||
|
### 性能驗證
|
||||||
|
- [ ] 頁面載入速度正常
|
||||||
|
- [ ] 圖片載入速度快
|
||||||
|
- [ ] 查詢響應時間合理
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📞 支援資源
|
||||||
|
|
||||||
|
- **Supabase 官方文檔**: https://supabase.com/docs
|
||||||
|
- **Next.js 整合指南**: https://supabase.com/docs/guides/getting-started/quickstarts/nextjs
|
||||||
|
- **故障排除指南**: https://supabase.com/docs/guides/platform/troubleshooting
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**🌟 恭喜!你的心願星河已經成功整合 Supabase!**
|
||||||
|
|
||||||
|
現在你可以享受雲端數據存儲、圖片管理、實時同步等強大功能。如果遇到任何問題,請參考故障排除章節或聯繫技術支援。
|
||||||
|
\`\`\`
|
@@ -24,6 +24,7 @@ import {
|
|||||||
import RadarChart from "@/components/radar-chart"
|
import RadarChart from "@/components/radar-chart"
|
||||||
import HeaderMusicControl from "@/components/header-music-control"
|
import HeaderMusicControl from "@/components/header-music-control"
|
||||||
import { categories, categorizeWishMultiple, type Wish } from "@/lib/categorization"
|
import { categories, categorizeWishMultiple, type Wish } from "@/lib/categorization"
|
||||||
|
import { WishService } from "@/lib/supabase-service"
|
||||||
|
|
||||||
interface CategoryData {
|
interface CategoryData {
|
||||||
name: string
|
name: string
|
||||||
@@ -63,6 +64,7 @@ export default function AnalyticsPage() {
|
|||||||
const [wishes, setWishes] = useState<Wish[]>([])
|
const [wishes, setWishes] = useState<Wish[]>([])
|
||||||
const [analytics, setAnalytics] = useState<AnalyticsData | null>(null)
|
const [analytics, setAnalytics] = useState<AnalyticsData | null>(null)
|
||||||
const [showCategoryGuide, setShowCategoryGuide] = useState(false)
|
const [showCategoryGuide, setShowCategoryGuide] = useState(false)
|
||||||
|
const [showPrivacyDetails, setShowPrivacyDetails] = useState(false) // 新增:隱私說明收放狀態
|
||||||
|
|
||||||
// 分析許願內容(包含所有數據,包括私密的)
|
// 分析許願內容(包含所有數據,包括私密的)
|
||||||
const analyzeWishes = (wishList: (Wish & { isPublic?: boolean })[]): AnalyticsData => {
|
const analyzeWishes = (wishList: (Wish & { isPublic?: boolean })[]): AnalyticsData => {
|
||||||
@@ -181,9 +183,39 @@ export default function AnalyticsPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const savedWishes = JSON.parse(localStorage.getItem("wishes") || "[]")
|
const fetchWishes = async () => {
|
||||||
setWishes(savedWishes)
|
try {
|
||||||
setAnalytics(analyzeWishes(savedWishes))
|
// 獲取所有困擾案例(包含私密的,用於完整分析)
|
||||||
|
const allWishesData = await WishService.getAllWishes()
|
||||||
|
|
||||||
|
// 轉換數據格式以匹配 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)
|
||||||
|
|
||||||
|
setWishes(allWishes)
|
||||||
|
setAnalytics(analyzeWishes(allWishes))
|
||||||
|
} catch (error) {
|
||||||
|
console.error("獲取分析數據失敗:", error)
|
||||||
|
// 如果 Supabase 連接失敗,回退到 localStorage
|
||||||
|
const savedWishes = JSON.parse(localStorage.getItem("wishes") || "[]")
|
||||||
|
setWishes(savedWishes)
|
||||||
|
setAnalytics(analyzeWishes(savedWishes))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchWishes()
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
if (!analytics) {
|
if (!analytics) {
|
||||||
@@ -320,71 +352,92 @@ export default function AnalyticsPage() {
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
{/* Main Content */}
|
{/* Main Content */}
|
||||||
<main className="py-8 md:py-12 px-4">
|
<main className="py-6 md:py-12 px-3 md:px-4">
|
||||||
<div className="container mx-auto max-w-7xl">
|
<div className="container mx-auto max-w-7xl">
|
||||||
{/* 頁面標題 */}
|
{/* 頁面標題 - 手機優化 */}
|
||||||
<div className="text-center mb-8 md:mb-12">
|
<div className="text-center mb-6 md:mb-12">
|
||||||
<div className="flex items-center justify-center gap-3 mb-4">
|
<div className="flex flex-col sm:flex-row items-center justify-center gap-2 sm:gap-3 mb-3 md:mb-4">
|
||||||
<div className="w-12 h-12 bg-gradient-to-br from-purple-400 to-indigo-500 rounded-full flex items-center justify-center shadow-lg shadow-purple-500/25">
|
<div className="w-10 h-10 md:w-12 md:h-12 bg-gradient-to-br from-purple-600 to-indigo-700 rounded-full flex items-center justify-center shadow-lg shadow-purple-500/25">
|
||||||
<BarChart3 className="w-6 h-6 md:w-8 md:h-8 text-white" />
|
<BarChart3 className="w-5 h-5 md:w-6 md:h-6 text-white" />
|
||||||
</div>
|
</div>
|
||||||
<h2 className="text-3xl md:text-4xl font-bold text-white">問題洞察分析</h2>
|
<h2 className="text-2xl md:text-4xl font-bold text-white text-center sm:text-left">問題洞察分析</h2>
|
||||||
<Badge className="bg-gradient-to-r from-pink-500/20 to-purple-500/20 text-pink-200 border border-pink-400/30 px-3 py-1">
|
<Badge className="bg-gradient-to-r from-pink-700/60 to-purple-700/60 text-white border border-pink-400/50 px-2 md:px-3 py-1 text-xs md:text-sm">
|
||||||
完整數據分析
|
完整數據分析
|
||||||
</Badge>
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-blue-200 text-lg">深入分析職場困擾的分布和趨勢</p>
|
<p className="text-blue-200 text-base md:text-lg px-2">深入分析職場困擾的分布和趨勢</p>
|
||||||
<p className="text-blue-300 text-sm mt-2">包含所有提交的案例數據,協助管理者了解真實狀況</p>
|
<p className="text-blue-300 text-xs md:text-sm mt-1 px-2">包含所有提交的案例數據,協助管理者了解真實狀況</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 隱私說明卡片 */}
|
{/* 隱私說明卡片 - 手機版可收放 */}
|
||||||
<Card className="bg-gradient-to-r from-indigo-800/30 to-purple-800/30 backdrop-blur-sm border border-indigo-600/50 mb-8 md:mb-12">
|
<Card className="bg-gradient-to-r from-blue-900/80 to-indigo-800/80 backdrop-blur-sm border border-blue-500/50 mb-6 md:mb-12">
|
||||||
<CardHeader>
|
<CardHeader className="pb-3 md:pb-4">
|
||||||
<CardTitle className="text-lg sm:text-xl md:text-2xl text-white flex items-center gap-3">
|
<div className="flex items-center justify-between">
|
||||||
<div className="w-8 h-8 bg-gradient-to-br from-indigo-400 to-purple-500 rounded-full flex items-center justify-center">
|
<div className="flex items-center gap-2 md:gap-3 min-w-0 flex-1">
|
||||||
<Shield className="w-4 h-4 text-white" />
|
<div className="w-6 h-6 md:w-8 md:h-8 bg-gradient-to-br from-indigo-600 to-purple-700 rounded-full flex items-center justify-center flex-shrink-0">
|
||||||
|
<Shield className="w-3 h-3 md:w-4 md:h-4 text-white" />
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<CardTitle className="text-base md:text-xl lg:text-2xl text-white truncate">數據隱私說明</CardTitle>
|
||||||
|
<CardDescription className="text-white/90 text-xs md:text-sm lg:text-base">
|
||||||
|
本分析包含所有提交的案例,包括選擇保持私密的困擾
|
||||||
|
</CardDescription>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
數據隱私說明
|
{/* 手機版收放按鈕 */}
|
||||||
</CardTitle>
|
<Button
|
||||||
<CardDescription className="text-indigo-200 text-sm sm:text-base">
|
variant="ghost"
|
||||||
本分析包含所有提交的案例,包括選擇保持私密的困擾
|
size="sm"
|
||||||
</CardDescription>
|
onClick={() => setShowPrivacyDetails(!showPrivacyDetails)}
|
||||||
|
className="text-indigo-200 hover:text-white hover:bg-indigo-700/50 px-2 md:px-3 flex-shrink-0 md:hidden"
|
||||||
|
>
|
||||||
|
{showPrivacyDetails ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
|
||||||
<div className="grid sm:grid-cols-2 gap-4 text-sm">
|
{/* 桌面版始終顯示,手機版可收放 */}
|
||||||
<div className="space-y-2">
|
<div className={`${showPrivacyDetails ? "block" : "hidden"} md:block`}>
|
||||||
<h4 className="font-semibold text-indigo-200 flex items-center gap-2">
|
<CardContent className="pt-0">
|
||||||
<Eye className="w-4 h-4" />
|
<div className="grid sm:grid-cols-2 gap-3 md:gap-4 text-sm">
|
||||||
公開案例 ({analytics.publicWishes} 個)
|
<div className="space-y-2">
|
||||||
</h4>
|
<h4 className="font-semibold text-indigo-200 flex items-center gap-2">
|
||||||
<p className="text-indigo-100">這些案例會顯示在「聆聽心聲」頁面,供其他人查看和產生共鳴</p>
|
<Eye className="w-3 h-3 md:w-4 md:h-4" />
|
||||||
|
公開案例 ({analytics.publicWishes} 個)
|
||||||
|
</h4>
|
||||||
|
<p className="text-indigo-100 text-xs md:text-sm leading-relaxed">
|
||||||
|
這些案例會顯示在「聆聽心聲」頁面,供其他人查看和產生共鳴
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h4 className="font-semibold text-indigo-200 flex items-center gap-2">
|
||||||
|
<EyeOff className="w-3 h-3 md:w-4 md:h-4" />
|
||||||
|
私密案例 ({analytics.privateWishes} 個)
|
||||||
|
</h4>
|
||||||
|
<p className="text-indigo-100 text-xs md:text-sm leading-relaxed">
|
||||||
|
這些案例保持匿名且私密,僅用於統計分析,幫助了解整體趨勢
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div className="mt-3 md:mt-4 p-2 md:p-3 bg-slate-800/50 rounded-lg border border-slate-600/30">
|
||||||
<h4 className="font-semibold text-indigo-200 flex items-center gap-2">
|
<p className="text-xs md:text-sm text-slate-300 leading-relaxed">
|
||||||
<EyeOff className="w-4 h-4" />
|
<strong className="text-blue-200">給管理者的說明:</strong>
|
||||||
私密案例 ({analytics.privateWishes} 個)
|
此分析包含完整的問題數據,能幫助您了解團隊面臨的真實挑戰。私密案例雖然不會公開顯示,
|
||||||
</h4>
|
但其數據對於制定改善策略同樣重要。所有個人身份資訊都已匿名化處理。
|
||||||
<p className="text-indigo-100">這些案例保持匿名且私密,僅用於統計分析,幫助了解整體趨勢</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</CardContent>
|
||||||
<div className="mt-4 p-3 bg-slate-800/50 rounded-lg border border-slate-600/30">
|
</div>
|
||||||
<p className="text-xs md:text-sm text-slate-300 leading-relaxed">
|
|
||||||
<strong className="text-blue-200">給管理者的說明:</strong>
|
|
||||||
此分析包含完整的問題數據,能幫助您了解團隊面臨的真實挑戰。私密案例雖然不會公開顯示,
|
|
||||||
但其數據對於制定改善策略同樣重要。所有個人身份資訊都已匿名化處理。
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
{/* 統計概覽 */}
|
{/* 統計概覽 - 手機優化 */}
|
||||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 md:gap-6 mb-8 md:mb-12">
|
<div className="grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-6 mb-6 md:mb-12">
|
||||||
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50">
|
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50">
|
||||||
<CardContent className="p-4 md:p-6 text-center">
|
<CardContent className="p-3 md:p-6 text-center">
|
||||||
<div className="w-10 h-10 md:w-12 md:h-12 bg-gradient-to-br from-cyan-400 to-blue-500 rounded-full flex items-center justify-center mx-auto mb-2 md:mb-3">
|
<div className="w-8 h-8 md:w-12 md:h-12 bg-gradient-to-br from-cyan-400 to-blue-500 rounded-full flex items-center justify-center mx-auto mb-2 md:mb-3">
|
||||||
<Users className="w-5 h-5 md:w-6 md:h-6 text-white" />
|
<Users className="w-4 h-4 md:w-6 md:h-6 text-white" />
|
||||||
</div>
|
</div>
|
||||||
<div className="text-2xl md:text-3xl font-bold text-white mb-1">{analytics.totalWishes}</div>
|
<div className="text-xl md:text-3xl font-bold text-white mb-1">{analytics.totalWishes}</div>
|
||||||
<div className="text-xs md:text-sm text-blue-200">總案例數</div>
|
<div className="text-xs md:text-sm text-blue-200">總案例數</div>
|
||||||
<div className="text-xs text-slate-400 mt-1">
|
<div className="text-xs text-slate-400 mt-1">
|
||||||
公開 {analytics.publicWishes} + 私密 {analytics.privateWishes}
|
公開 {analytics.publicWishes} + 私密 {analytics.privateWishes}
|
||||||
@@ -393,21 +446,21 @@ export default function AnalyticsPage() {
|
|||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50">
|
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50">
|
||||||
<CardContent className="p-4 md:p-6 text-center">
|
<CardContent className="p-3 md:p-6 text-center">
|
||||||
<div className="w-10 h-10 md:w-12 md:h-12 bg-gradient-to-br from-green-400 to-emerald-500 rounded-full flex items-center justify-center mx-auto mb-2 md:mb-3">
|
<div className="w-8 h-8 md:w-12 md:h-12 bg-gradient-to-br from-green-400 to-emerald-500 rounded-full flex items-center justify-center mx-auto mb-2 md:mb-3">
|
||||||
<TrendingUp className="w-5 h-5 md:w-6 md:h-6 text-white" />
|
<TrendingUp className="w-4 h-4 md:w-6 md:h-6 text-white" />
|
||||||
</div>
|
</div>
|
||||||
<div className="text-2xl md:text-3xl font-bold text-white mb-1">{analytics.recentTrends.thisWeek}</div>
|
<div className="text-xl md:text-3xl font-bold text-white mb-1">{analytics.recentTrends.thisWeek}</div>
|
||||||
<div className="text-xs md:text-sm text-blue-200">本週新增</div>
|
<div className="text-xs md:text-sm text-blue-200">本週新增</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50">
|
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50">
|
||||||
<CardContent className="p-4 md:p-6 text-center">
|
<CardContent className="p-3 md:p-6 text-center">
|
||||||
<div className="w-10 h-10 md:w-12 md:h-12 bg-gradient-to-br from-purple-400 to-indigo-500 rounded-full flex items-center justify-center mx-auto mb-2 md:mb-3">
|
<div className="w-8 h-8 md:w-12 md:h-12 bg-gradient-to-br from-purple-400 to-indigo-500 rounded-full flex items-center justify-center mx-auto mb-2 md:mb-3">
|
||||||
<Target className="w-5 h-5 md:w-6 md:h-6 text-white" />
|
<Target className="w-4 h-4 md:w-6 md:h-6 text-white" />
|
||||||
</div>
|
</div>
|
||||||
<div className="text-2xl md:text-3xl font-bold text-white mb-1">
|
<div className="text-xl md:text-3xl font-bold text-white mb-1">
|
||||||
{analytics.categories.filter((c) => c.count > 0).length}
|
{analytics.categories.filter((c) => c.count > 0).length}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-xs md:text-sm text-blue-200">問題領域</div>
|
<div className="text-xs md:text-sm text-blue-200">問題領域</div>
|
||||||
@@ -415,16 +468,16 @@ export default function AnalyticsPage() {
|
|||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50">
|
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50">
|
||||||
<CardContent className="p-4 md:p-6 text-center">
|
<CardContent className="p-3 md:p-6 text-center">
|
||||||
<div
|
<div
|
||||||
className="w-10 h-10 md:w-12 md:h-12 rounded-full flex items-center justify-center mx-auto mb-2 md:mb-3"
|
className="w-8 h-8 md:w-12 md:h-12 rounded-full flex items-center justify-center mx-auto mb-2 md:mb-3"
|
||||||
style={{
|
style={{
|
||||||
background: `linear-gradient(135deg, ${analytics.recentTrends.growthColor}80, ${analytics.recentTrends.growthColor}60)`,
|
background: `linear-gradient(135deg, ${analytics.recentTrends.growthColor}80, ${analytics.recentTrends.growthColor}60)`,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<GrowthIcon className="w-5 h-5 md:w-6 md:h-6 text-white" />
|
<GrowthIcon className="w-4 h-4 md:w-6 md:h-6 text-white" />
|
||||||
</div>
|
</div>
|
||||||
<div className="text-2xl md:text-3xl font-bold text-white mb-1">
|
<div className="text-xl md:text-3xl font-bold text-white mb-1">
|
||||||
{analytics.recentTrends.growth > 0 ? "+" : ""}
|
{analytics.recentTrends.growth > 0 ? "+" : ""}
|
||||||
{analytics.recentTrends.growth}%
|
{analytics.recentTrends.growth}%
|
||||||
</div>
|
</div>
|
||||||
@@ -437,17 +490,17 @@ export default function AnalyticsPage() {
|
|||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 分類指南 */}
|
{/* 分類指南 - 手機優化 */}
|
||||||
<Card className="bg-gradient-to-r from-indigo-800/30 to-purple-800/30 backdrop-blur-sm border border-indigo-600/50 mb-8 md:mb-12">
|
<Card className="bg-gradient-to-r from-blue-900/80 to-indigo-800/80 backdrop-blur-sm border border-blue-500/50 mb-6 md:mb-12">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
|
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-2 md:gap-3 min-w-0 flex-1">
|
||||||
<div className="w-8 h-8 bg-gradient-to-br from-indigo-400 to-purple-500 rounded-full flex items-center justify-center flex-shrink-0">
|
<div className="w-6 h-6 md:w-8 md:h-8 bg-gradient-to-br from-indigo-600 to-purple-700 rounded-full flex items-center justify-center flex-shrink-0">
|
||||||
<BookOpen className="w-4 h-4 text-white" />
|
<BookOpen className="w-3 h-3 md:w-4 md:h-4 text-white" />
|
||||||
</div>
|
</div>
|
||||||
<div className="min-w-0 flex-1">
|
<div className="min-w-0 flex-1">
|
||||||
<CardTitle className="text-lg sm:text-xl md:text-2xl text-white">問題分類說明</CardTitle>
|
<CardTitle className="text-base md:text-xl lg:text-2xl text-white">問題分類說明</CardTitle>
|
||||||
<CardDescription className="text-indigo-200 text-sm sm:text-base">
|
<CardDescription className="text-white/90 text-xs md:text-sm lg:text-base">
|
||||||
了解我們如何分類和分析各種職場困擾
|
了解我們如何分類和分析各種職場困擾
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</div>
|
</div>
|
||||||
@@ -475,32 +528,35 @@ export default function AnalyticsPage() {
|
|||||||
|
|
||||||
{showCategoryGuide && (
|
{showCategoryGuide && (
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="grid md:grid-cols-2 gap-4">
|
<div className="grid md:grid-cols-2 gap-3 md:gap-4">
|
||||||
{categories.map((category, index) => (
|
{categories.map((category, index) => (
|
||||||
<div
|
<div
|
||||||
key={category.name}
|
key={category.name}
|
||||||
className="p-4 rounded-lg bg-slate-700/30 border border-slate-600/30 hover:bg-slate-600/40 transition-all duration-200"
|
className="p-3 md:p-4 rounded-lg bg-slate-800/50 border border-slate-600/30 hover:bg-slate-700/60 transition-all duration-200"
|
||||||
>
|
>
|
||||||
<div className="flex items-start gap-3 mb-2">
|
<div className="flex items-start gap-2 md:gap-3 mb-2">
|
||||||
<div className="text-2xl">{category.icon}</div>
|
<div className="text-lg md:text-2xl">{category.icon}</div>
|
||||||
<div className="flex-1">
|
<div className="flex-1 min-w-0">
|
||||||
<div className="flex items-center gap-2 mb-1">
|
<div className="flex items-center gap-2 mb-1">
|
||||||
<h4 className="font-semibold text-white">{category.name}</h4>
|
<h4 className="font-semibold text-white text-sm md:text-base">{category.name}</h4>
|
||||||
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: category.color }}></div>
|
<div
|
||||||
|
className="w-2 h-2 md:w-3 md:h-3 rounded-full flex-shrink-0"
|
||||||
|
style={{ backgroundColor: category.color }}
|
||||||
|
></div>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-sm text-slate-300 leading-relaxed">{category.description}</p>
|
<p className="text-xs md:text-sm text-slate-300 leading-relaxed">{category.description}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 關鍵字示例 */}
|
{/* 關鍵字示例 */}
|
||||||
<div className="mt-3 pt-3 border-t border-slate-600/30">
|
<div className="mt-2 md:mt-3 pt-2 md:pt-3 border-t border-slate-600/30">
|
||||||
<div className="text-xs text-slate-400 mb-2">常見關鍵字:</div>
|
<div className="text-xs text-slate-400 mb-2">常見關鍵字:</div>
|
||||||
<div className="flex flex-wrap gap-1">
|
<div className="flex flex-wrap gap-1">
|
||||||
{category.keywords.slice(0, 6).map((keyword, idx) => (
|
{category.keywords.slice(0, 6).map((keyword, idx) => (
|
||||||
<Badge
|
<Badge
|
||||||
key={idx}
|
key={idx}
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
className="text-xs px-2 py-0.5 bg-slate-600/50 text-slate-300 border-slate-500/50"
|
className="text-xs px-1.5 md:px-2 py-0.5 bg-slate-600/50 text-slate-300 border-slate-500/50"
|
||||||
>
|
>
|
||||||
{keyword}
|
{keyword}
|
||||||
</Badge>
|
</Badge>
|
||||||
@@ -508,7 +564,7 @@ export default function AnalyticsPage() {
|
|||||||
{category.keywords.length > 6 && (
|
{category.keywords.length > 6 && (
|
||||||
<Badge
|
<Badge
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
className="text-xs px-2 py-0.5 bg-slate-600/30 text-slate-400 border-slate-500/30"
|
className="text-xs px-1.5 md:px-2 py-0.5 bg-slate-600/30 text-slate-400 border-slate-500/30"
|
||||||
>
|
>
|
||||||
+{category.keywords.length - 6}
|
+{category.keywords.length - 6}
|
||||||
</Badge>
|
</Badge>
|
||||||
@@ -523,21 +579,23 @@ export default function AnalyticsPage() {
|
|||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
{/* 手機版:垂直佈局,桌面版:並排佈局 */}
|
{/* 手機版:垂直佈局,桌面版:並排佈局 */}
|
||||||
<div className="space-y-8 lg:space-y-0 lg:grid lg:grid-cols-2 lg:gap-8 md:gap-12">
|
<div className="space-y-6 md:space-y-0 lg:grid lg:grid-cols-2 lg:gap-8 md:gap-12">
|
||||||
{/* 雷達圖 - 手機版給予更多高度 */}
|
{/* 雷達圖 - 手機版給予更多高度 */}
|
||||||
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50">
|
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="text-xl md:text-2xl text-white flex items-center gap-3">
|
<CardTitle className="text-lg md:text-xl lg:text-2xl text-white flex items-center gap-2 md:gap-3">
|
||||||
<div className="w-8 h-8 bg-gradient-to-br from-purple-400 to-indigo-500 rounded-full flex items-center justify-center">
|
<div className="w-6 h-6 md:w-8 md:h-8 bg-gradient-to-br from-purple-600 to-indigo-700 rounded-full flex items-center justify-center">
|
||||||
<BarChart3 className="w-4 h-4 text-white" />
|
<BarChart3 className="w-3 h-3 md:w-4 md:h-4 text-white" />
|
||||||
</div>
|
</div>
|
||||||
問題分布圖譜
|
問題分布圖譜
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
<CardDescription className="text-blue-200">各類職場困擾的完整案例分布(包含私密數據)</CardDescription>
|
<CardDescription className="text-white/90 text-xs md:text-sm">
|
||||||
|
各類職場困擾的完整案例分布(包含私密數據)
|
||||||
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
{/* 手機版使用更大的高度,桌面版保持原有高度 */}
|
{/* 手機版使用更大的高度,桌面版保持原有高度 */}
|
||||||
<div className="h-80 sm:h-96 lg:h-80 xl:h-96">
|
<div className="h-64 sm:h-80 md:h-64 lg:h-80 xl:h-96">
|
||||||
<RadarChart data={analytics.categories} />
|
<RadarChart data={analytics.categories} />
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
@@ -546,16 +604,16 @@ export default function AnalyticsPage() {
|
|||||||
{/* 分類詳細統計 */}
|
{/* 分類詳細統計 */}
|
||||||
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50">
|
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="text-xl md:text-2xl text-white flex items-center gap-3">
|
<CardTitle className="text-lg md:text-xl lg:text-2xl text-white flex items-center gap-2 md:gap-3">
|
||||||
<div className="w-8 h-8 bg-gradient-to-br from-cyan-400 to-blue-500 rounded-full flex items-center justify-center">
|
<div className="w-6 h-6 md:w-8 md:h-8 bg-gradient-to-br from-cyan-600 to-blue-700 rounded-full flex items-center justify-center">
|
||||||
<Target className="w-4 h-4 text-white" />
|
<Target className="w-3 h-3 md:w-4 md:h-4 text-white" />
|
||||||
</div>
|
</div>
|
||||||
完整案例統計
|
完整案例統計
|
||||||
<Badge className="bg-gradient-to-r from-pink-500/20 to-purple-500/20 text-pink-200 border border-pink-400/30 text-xs px-2 py-1">
|
<Badge className="bg-gradient-to-r from-pink-700/60 to-purple-700/60 text-white border border-pink-400/50 text-xs px-2 py-1">
|
||||||
含私密數據
|
含私密數據
|
||||||
</Badge>
|
</Badge>
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
<CardDescription className="text-blue-200">
|
<CardDescription className="text-white/90 text-xs md:text-sm">
|
||||||
每個領域的所有案例數量(包含公開和私密案例)
|
每個領域的所有案例數量(包含公開和私密案例)
|
||||||
{analytics.categories.filter((cat) => cat.count > 0).length > 0 && (
|
{analytics.categories.filter((cat) => cat.count > 0).length > 0 && (
|
||||||
<span className="block text-xs text-slate-400 mt-1">
|
<span className="block text-xs text-slate-400 mt-1">
|
||||||
@@ -565,39 +623,42 @@ export default function AnalyticsPage() {
|
|||||||
)}
|
)}
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-4">
|
<CardContent className="space-y-3 md:space-y-4">
|
||||||
{/* 設定固定高度並添加滾動 */}
|
{/* 設定固定高度並添加滾動 */}
|
||||||
<div className="max-h-80 overflow-y-auto pr-2 space-y-4 scrollbar-thin scrollbar-thumb-slate-600 scrollbar-track-slate-800">
|
<div className="max-h-64 md:max-h-80 overflow-y-auto pr-2 space-y-3 md:space-y-4 scrollbar-thin scrollbar-thumb-slate-600 scrollbar-track-slate-800">
|
||||||
{analytics.categories
|
{analytics.categories
|
||||||
.filter((cat) => cat.count > 0)
|
.filter((cat) => cat.count > 0)
|
||||||
.sort((a, b) => b.count - a.count)
|
.sort((a, b) => b.count - a.count)
|
||||||
.map((category, index) => (
|
.map((category, index) => (
|
||||||
<div
|
<div
|
||||||
key={category.name}
|
key={category.name}
|
||||||
className="flex items-center justify-between p-4 rounded-lg bg-slate-700/30 border border-slate-600/30 hover:bg-slate-600/40 transition-all duration-200"
|
className="flex items-center justify-between p-3 md:p-4 rounded-lg bg-slate-700/30 border border-slate-600/30 hover:bg-slate-600/40 transition-all duration-200"
|
||||||
>
|
>
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-2 md:gap-3 min-w-0 flex-1">
|
||||||
<div className="text-xl">
|
<div className="text-base md:text-xl">
|
||||||
{categories.find((cat) => cat.name === category.name)?.icon || "❓"}
|
{categories.find((cat) => cat.name === category.name)?.icon || "❓"}
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div className="min-w-0 flex-1">
|
||||||
<div className="font-semibold text-white flex items-center gap-2">
|
<div className="font-semibold text-white flex items-center gap-2 mb-1">
|
||||||
{category.name}
|
<span className="truncate">{category.name}</span>
|
||||||
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: category.color }}></div>
|
<div
|
||||||
|
className="w-2 h-2 md:w-3 md:h-3 rounded-full flex-shrink-0"
|
||||||
|
style={{ backgroundColor: category.color }}
|
||||||
|
></div>
|
||||||
{/* 添加排名標示 */}
|
{/* 添加排名標示 */}
|
||||||
{index < 3 && (
|
{index < 3 && (
|
||||||
<span className="text-xs bg-gradient-to-r from-cyan-500/20 to-blue-500/20 text-cyan-200 px-2 py-0.5 rounded-full border border-cyan-500/30">
|
<span className="text-xs bg-gradient-to-r from-cyan-500/20 to-blue-500/20 text-cyan-200 px-1.5 md:px-2 py-0.5 rounded-full border border-cyan-500/30 flex-shrink-0">
|
||||||
TOP {index + 1}
|
TOP {index + 1}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-sm text-slate-300">{category.count} 個案例</div>
|
<div className="text-xs md:text-sm text-slate-300">{category.count} 個案例</div>
|
||||||
{category.description && (
|
{category.description && (
|
||||||
<div className="text-xs text-slate-400 mt-1 max-w-xs">{category.description}</div>
|
<div className="text-xs text-slate-400 mt-1 line-clamp-2">{category.description}</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<Badge variant="secondary" className="bg-slate-600/50 text-slate-200">
|
<Badge variant="secondary" className="bg-slate-600/50 text-slate-200 flex-shrink-0 ml-2">
|
||||||
{category.percentage}%
|
{category.percentage}%
|
||||||
</Badge>
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
@@ -622,33 +683,41 @@ export default function AnalyticsPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 多維度分析說明 */}
|
{/* 多維度分析說明 */}
|
||||||
<Card className="bg-gradient-to-r from-purple-800/30 to-indigo-800/30 backdrop-blur-sm border border-purple-600/50 mt-8 md:mt-12">
|
<Card className="bg-gradient-to-r from-blue-900/80 to-indigo-800/80 backdrop-blur-sm border border-blue-500/50 mt-6 md:mt-12">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="text-xl md:text-2xl text-white flex items-center gap-3">
|
<CardTitle className="text-lg md:text-xl lg:text-2xl text-white flex items-center gap-2 md:gap-3">
|
||||||
<div className="w-8 h-8 bg-gradient-to-br from-purple-400 to-pink-500 rounded-full flex items-center justify-center">
|
<div className="w-6 h-6 md:w-8 md:h-8 bg-gradient-to-br from-purple-400 to-pink-500 rounded-full flex items-center justify-center">
|
||||||
<Sparkles className="w-4 h-4 text-white" />
|
<Sparkles className="w-3 h-3 md:w-4 md:h-4 text-white" />
|
||||||
</div>
|
</div>
|
||||||
完整數據分析優勢
|
完整數據分析優勢
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
<CardDescription className="text-purple-200">包含私密案例的全面分析,提供更準確的洞察</CardDescription>
|
<CardDescription className="text-white/90 text-xs md:text-sm">
|
||||||
|
包含私密案例的全面分析,提供更準確的洞察
|
||||||
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="grid sm:grid-cols-2 gap-4 text-sm">
|
<div className="grid sm:grid-cols-2 gap-3 md:gap-4 text-xs md:text-sm">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<h4 className="font-semibold text-purple-200">🔍 真實全貌</h4>
|
<h4 className="font-semibold text-purple-200">🔍 真實全貌</h4>
|
||||||
<p className="text-purple-100">包含所有案例數據,不受公開意願影響,呈現最真實的問題狀況</p>
|
<p className="text-purple-100 leading-relaxed">
|
||||||
|
包含所有案例數據,不受公開意願影響,呈現最真實的問題狀況
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<h4 className="font-semibold text-purple-200">📊 精準決策</h4>
|
<h4 className="font-semibold text-purple-200">📊 精準決策</h4>
|
||||||
<p className="text-purple-100">基於完整數據制定改善策略,避免因樣本偏差導致的決策失誤</p>
|
<p className="text-purple-100 leading-relaxed">
|
||||||
|
基於完整數據制定改善策略,避免因樣本偏差導致的決策失誤
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<h4 className="font-semibold text-purple-200">🎯 隱藏問題</h4>
|
<h4 className="font-semibold text-purple-200">🎯 隱藏問題</h4>
|
||||||
<p className="text-purple-100">發現那些員工不願公開但確實存在的問題,提前預防和解決</p>
|
<p className="text-purple-100 leading-relaxed">
|
||||||
|
發現那些員工不願公開但確實存在的問題,提前預防和解決
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<h4 className="font-semibold text-purple-200">🔒 隱私保護</h4>
|
<h4 className="font-semibold text-purple-200">🔒 隱私保護</h4>
|
||||||
<p className="text-purple-100">在保護個人隱私的前提下,最大化數據的分析價值</p>
|
<p className="text-purple-100 leading-relaxed">在保護個人隱私的前提下,最大化數據的分析價值</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
@@ -656,15 +725,15 @@ export default function AnalyticsPage() {
|
|||||||
|
|
||||||
{/* 熱門關鍵字 */}
|
{/* 熱門關鍵字 */}
|
||||||
{analytics.topKeywords.length > 0 && (
|
{analytics.topKeywords.length > 0 && (
|
||||||
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50 mt-8 md:mt-12">
|
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50 mt-6 md:mt-12">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="text-xl md:text-2xl text-white flex items-center gap-3">
|
<CardTitle className="text-lg md:text-xl lg:text-2xl text-white flex items-center gap-2 md:gap-3">
|
||||||
<div className="w-8 h-8 bg-gradient-to-br from-green-400 to-emerald-500 rounded-full flex items-center justify-center">
|
<div className="w-6 h-6 md:w-8 md:h-8 bg-gradient-to-br from-green-400 to-emerald-500 rounded-full flex items-center justify-center">
|
||||||
<TrendingUp className="w-4 h-4 text-white" />
|
<TrendingUp className="w-3 h-3 md:w-4 md:h-4 text-white" />
|
||||||
</div>
|
</div>
|
||||||
最常見的問題關鍵字
|
最常見的問題關鍵字
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
<CardDescription className="text-blue-200">
|
<CardDescription className="text-white/90 text-xs md:text-sm">
|
||||||
在所有案例中最常出現的詞彙,反映團隊面臨的核心挑戰
|
在所有案例中最常出現的詞彙,反映團隊面臨的核心挑戰
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
@@ -674,7 +743,7 @@ export default function AnalyticsPage() {
|
|||||||
<Badge
|
<Badge
|
||||||
key={keyword.word}
|
key={keyword.word}
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
className="bg-gradient-to-r from-cyan-500/20 to-blue-500/20 text-cyan-200 border border-cyan-500/30 px-3 py-1.5 text-sm"
|
className="bg-gradient-to-r from-cyan-500/20 to-blue-500/20 text-cyan-200 border border-cyan-500/30 px-2 md:px-3 py-1 md:py-1.5 text-xs md:text-sm"
|
||||||
>
|
>
|
||||||
{keyword.word} ({keyword.count})
|
{keyword.word} ({keyword.count})
|
||||||
</Badge>
|
</Badge>
|
||||||
|
64
app/page.tsx
64
app/page.tsx
@@ -1,40 +1,72 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react"
|
||||||
import Link from "next/link"
|
import Link from "next/link"
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
import { Sparkles, MessageCircle, Users, BarChart3 } from "lucide-react"
|
import { Sparkles, MessageCircle, Users, BarChart3 } from "lucide-react"
|
||||||
import HeaderMusicControl from "@/components/header-music-control"
|
import HeaderMusicControl from "@/components/header-music-control"
|
||||||
|
|
||||||
|
interface Star {
|
||||||
|
id: number;
|
||||||
|
style: {
|
||||||
|
left: string;
|
||||||
|
top: string;
|
||||||
|
animationDelay: string;
|
||||||
|
animationDuration: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export default function HomePage() {
|
export default function HomePage() {
|
||||||
|
const [stars, setStars] = useState<Star[]>([]);
|
||||||
|
const [bigStars, setBigStars] = useState<Star[]>([]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// 生成小星星
|
||||||
|
setStars(
|
||||||
|
Array.from({ length: 30 }, (_, i) => ({
|
||||||
|
id: i,
|
||||||
|
style: {
|
||||||
|
left: `${Math.random() * 100}%`,
|
||||||
|
top: `${Math.random() * 100}%`,
|
||||||
|
animationDelay: `${Math.random() * 3}s`,
|
||||||
|
animationDuration: `${2 + Math.random() * 2}s`,
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
);
|
||||||
|
|
||||||
|
// 生成大星星
|
||||||
|
setBigStars(
|
||||||
|
Array.from({ length: 15 }, (_, i) => ({
|
||||||
|
id: i,
|
||||||
|
style: {
|
||||||
|
left: `${Math.random() * 100}%`,
|
||||||
|
top: `${Math.random() * 100}%`,
|
||||||
|
animationDelay: `${Math.random() * 4}s`,
|
||||||
|
animationDuration: `${3 + Math.random() * 2}s`,
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
);
|
||||||
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gradient-to-b from-slate-900 via-blue-900 to-indigo-900 relative overflow-hidden flex flex-col">
|
<div className="min-h-screen bg-gradient-to-b from-slate-900 via-blue-900 to-indigo-900 relative overflow-hidden flex flex-col">
|
||||||
{/* 星空背景 */}
|
{/* 星空背景 */}
|
||||||
<div className="absolute inset-0 overflow-hidden pointer-events-none">
|
<div className="absolute inset-0 overflow-hidden pointer-events-none">
|
||||||
{/* 星星 */}
|
{/* 星星 */}
|
||||||
{[...Array(30)].map((_, i) => (
|
{stars.map((star) => (
|
||||||
<div
|
<div
|
||||||
key={i}
|
key={star.id}
|
||||||
className="absolute w-0.5 h-0.5 md:w-1 md:h-1 bg-white rounded-full animate-pulse"
|
className="absolute w-0.5 h-0.5 md:w-1 md:h-1 bg-white rounded-full animate-pulse"
|
||||||
style={{
|
style={star.style}
|
||||||
left: `${Math.random() * 100}%`,
|
|
||||||
top: `${Math.random() * 100}%`,
|
|
||||||
animationDelay: `${Math.random() * 3}s`,
|
|
||||||
animationDuration: `${2 + Math.random() * 2}s`,
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
{/* 較大的星星 */}
|
{/* 較大的星星 */}
|
||||||
{[...Array(15)].map((_, i) => (
|
{bigStars.map((star) => (
|
||||||
<div
|
<div
|
||||||
key={`big-${i}`}
|
key={`big-${star.id}`}
|
||||||
className="absolute w-1 h-1 md:w-2 md:h-2 bg-blue-200 rounded-full animate-pulse opacity-60"
|
className="absolute w-1 h-1 md:w-2 md:h-2 bg-blue-200 rounded-full animate-pulse opacity-60"
|
||||||
style={{
|
style={star.style}
|
||||||
left: `${Math.random() * 100}%`,
|
|
||||||
top: `${Math.random() * 100}%`,
|
|
||||||
animationDelay: `${Math.random() * 4}s`,
|
|
||||||
animationDuration: `${3 + Math.random() * 2}s`,
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
|
263
app/settings/page.tsx
Normal file
263
app/settings/page.tsx
Normal file
@@ -0,0 +1,263 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useState, useEffect } from "react"
|
||||||
|
import Link from "next/link"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||||
|
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"
|
||||||
|
|
||||||
|
export default function SettingsPage() {
|
||||||
|
const [showMigration, setShowMigration] = useState(false)
|
||||||
|
const [isConnected, setIsConnected] = useState(false)
|
||||||
|
const [localDataCount, setLocalDataCount] = useState(0)
|
||||||
|
const [isLoading, setIsLoading] = useState(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
checkLocalData()
|
||||||
|
checkConnection()
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const checkLocalData = () => {
|
||||||
|
try {
|
||||||
|
const wishes = JSON.parse(localStorage.getItem("wishes") || "[]")
|
||||||
|
setLocalDataCount(wishes.length)
|
||||||
|
} catch (error) {
|
||||||
|
setLocalDataCount(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkConnection = async () => {
|
||||||
|
setIsLoading(true)
|
||||||
|
try {
|
||||||
|
const connected = await testSupabaseConnection()
|
||||||
|
setIsConnected(connected)
|
||||||
|
} catch (error) {
|
||||||
|
setIsConnected(false)
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const clearAllData = () => {
|
||||||
|
if (confirm("確定要清除所有本地數據嗎?此操作無法復原。")) {
|
||||||
|
MigrationService.clearLocalStorageData()
|
||||||
|
// 也清除其他設定
|
||||||
|
localStorage.removeItem("backgroundMusicState")
|
||||||
|
localStorage.removeItem("user_session")
|
||||||
|
setLocalDataCount(0)
|
||||||
|
alert("本地數據已清除")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gradient-to-b from-slate-900 via-blue-900 to-indigo-900 relative overflow-hidden">
|
||||||
|
{/* 星空背景 */}
|
||||||
|
<div className="absolute inset-0 overflow-hidden pointer-events-none">
|
||||||
|
{[...Array(25)].map((_, i) => (
|
||||||
|
<div
|
||||||
|
key={i}
|
||||||
|
className="absolute w-0.5 h-0.5 md:w-1 md:h-1 bg-white rounded-full animate-pulse"
|
||||||
|
style={{
|
||||||
|
left: `${Math.random() * 100}%`,
|
||||||
|
top: `${Math.random() * 100}%`,
|
||||||
|
animationDelay: `${Math.random() * 3}s`,
|
||||||
|
animationDuration: `${2 + Math.random() * 2}s`,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
<div className="absolute top-1/4 left-1/3 w-64 h-64 md:w-96 md:h-96 bg-gradient-radial from-purple-400/20 via-blue-500/10 to-transparent rounded-full blur-3xl"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Header */}
|
||||||
|
<header className="border-b border-blue-800/50 bg-slate-900/80 backdrop-blur-sm sticky top-0 z-50">
|
||||||
|
<div className="container mx-auto px-3 sm:px-4 py-3 md:py-4">
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<Link href="/" className="flex items-center gap-2 md:gap-3 min-w-0 flex-shrink-0">
|
||||||
|
<div className="w-7 h-7 sm:w-8 sm:h-8 md:w-10 md:h-10 bg-gradient-to-br from-cyan-400 to-blue-500 rounded-full flex items-center justify-center shadow-lg shadow-cyan-500/25">
|
||||||
|
<Sparkles className="w-3.5 h-3.5 sm:w-4 sm:h-4 md:w-6 md:h-6 text-white" />
|
||||||
|
</div>
|
||||||
|
<h1 className="text-base sm:text-lg md:text-2xl font-bold text-white whitespace-nowrap">心願星河</h1>
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<nav className="flex items-center gap-1 sm:gap-2 md:gap-4 flex-shrink-0">
|
||||||
|
<div className="hidden sm:block">
|
||||||
|
<HeaderMusicControl />
|
||||||
|
</div>
|
||||||
|
<div className="sm:hidden">
|
||||||
|
<HeaderMusicControl mobileSimplified />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Link href="/">
|
||||||
|
<Button variant="ghost" size="sm" className="text-blue-200 hover:text-white hover:bg-blue-800/50">
|
||||||
|
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||||
|
返回首頁
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{/* Main Content */}
|
||||||
|
<main className="py-8 md:py-12 px-4">
|
||||||
|
<div className="container mx-auto max-w-4xl">
|
||||||
|
<div className="text-center mb-8 md:mb-12">
|
||||||
|
<h2 className="text-2xl md:text-3xl font-bold text-white mb-4 flex items-center justify-center gap-3">
|
||||||
|
<Settings className="w-8 h-8 text-cyan-400" />
|
||||||
|
系統設定
|
||||||
|
</h2>
|
||||||
|
<p className="text-blue-200 text-sm md:text-base">管理數據存儲和系統配置</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-6 md:space-y-8">
|
||||||
|
{/* Supabase 連接狀態 */}
|
||||||
|
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-white flex items-center gap-3">
|
||||||
|
<Database className="w-6 h-6 text-blue-400" />
|
||||||
|
Supabase 數據庫狀態
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription className="text-blue-200">雲端數據庫連接和配置狀態</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<div className="flex items-center justify-between p-4 bg-slate-700/50 rounded-lg">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className={`w-4 h-4 rounded-full ${isConnected ? "bg-green-400" : "bg-red-400"}`}></div>
|
||||||
|
<span className="text-white">連接狀態</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Badge className={isConnected ? "bg-green-500/20 text-green-200" : "bg-red-500/20 text-red-200"}>
|
||||||
|
{isLoading ? "檢查中..." : isConnected ? "已連接" : "未連接"}
|
||||||
|
</Badge>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={checkConnection}
|
||||||
|
disabled={isLoading}
|
||||||
|
className="text-blue-200 hover:text-white"
|
||||||
|
>
|
||||||
|
<TestTube className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!isConnected && (
|
||||||
|
<div className="p-4 bg-red-900/20 border border-red-600/30 rounded-lg">
|
||||||
|
<p className="text-red-200 text-sm">無法連接到 Supabase。請檢查:</p>
|
||||||
|
<ul className="text-red-200 text-xs mt-2 ml-4 space-y-1">
|
||||||
|
<li>• 環境變數 NEXT_PUBLIC_SUPABASE_URL 是否正確</li>
|
||||||
|
<li>• 環境變數 NEXT_PUBLIC_SUPABASE_ANON_KEY 是否正確</li>
|
||||||
|
<li>• Supabase 項目是否正常運行</li>
|
||||||
|
<li>• 網路連接是否正常</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* 數據遷移 */}
|
||||||
|
{localDataCount > 0 && (
|
||||||
|
<Card className="bg-slate-800/50 backdrop-blur-sm border border-blue-600/50">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-white flex items-center gap-3">
|
||||||
|
<Database className="w-6 h-6 text-blue-400" />
|
||||||
|
數據遷移
|
||||||
|
<Badge className="bg-orange-500/20 text-orange-200 border border-orange-400/30">需要處理</Badge>
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription className="text-blue-200">
|
||||||
|
發現 {localDataCount} 個本地困擾案例,建議遷移到雲端數據庫
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<Button
|
||||||
|
onClick={() => setShowMigration(true)}
|
||||||
|
className="w-full bg-gradient-to-r from-blue-500 to-cyan-600 hover:from-blue-600 hover:to-cyan-700 text-white"
|
||||||
|
>
|
||||||
|
開始數據遷移
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 數據管理 */}
|
||||||
|
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-white flex items-center gap-3">
|
||||||
|
<Trash2 className="w-6 h-6 text-red-400" />
|
||||||
|
數據管理
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription className="text-blue-200">清除本地存儲的數據</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<div className="p-4 bg-slate-700/50 rounded-lg">
|
||||||
|
<div className="flex items-center justify-between mb-2">
|
||||||
|
<span className="text-white">本地困擾案例</span>
|
||||||
|
<Badge variant="secondary">{localDataCount} 個</Badge>
|
||||||
|
</div>
|
||||||
|
<p className="text-slate-300 text-sm">存儲在瀏覽器本地的困擾案例數據</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button onClick={clearAllData} disabled={localDataCount === 0} variant="destructive" className="w-full">
|
||||||
|
<Trash2 className="w-4 h-4 mr-2" />
|
||||||
|
清除所有本地數據
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* 系統資訊 */}
|
||||||
|
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-white">系統資訊</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-3">
|
||||||
|
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||||
|
<div>
|
||||||
|
<span className="text-slate-400">版本</span>
|
||||||
|
<div className="text-white">v1.0.0</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-slate-400">數據庫</span>
|
||||||
|
<div className="text-white">{isConnected ? "Supabase" : "LocalStorage"}</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-slate-400">用戶會話</span>
|
||||||
|
<div className="text-white text-xs truncate">
|
||||||
|
{typeof window !== "undefined"
|
||||||
|
? localStorage.getItem("user_session")?.slice(-8) || "未設定"
|
||||||
|
: "載入中..."}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-slate-400">瀏覽器</span>
|
||||||
|
<div className="text-white">
|
||||||
|
{typeof window !== "undefined" ? navigator.userAgent.split(" ").pop() : "未知"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
{/* 遷移對話框 */}
|
||||||
|
{showMigration && (
|
||||||
|
<div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
|
||||||
|
<div className="w-full max-w-2xl">
|
||||||
|
<MigrationDialog
|
||||||
|
onComplete={() => {
|
||||||
|
setShowMigration(false)
|
||||||
|
checkLocalData()
|
||||||
|
}}
|
||||||
|
onSkip={() => setShowMigration(false)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
219
app/settings/storage-management.tsx
Normal file
219
app/settings/storage-management.tsx
Normal file
@@ -0,0 +1,219 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useState, useEffect } from "react"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||||
|
import { Badge } from "@/components/ui/badge"
|
||||||
|
import { Progress } from "@/components/ui/progress"
|
||||||
|
import { Alert, AlertDescription } from "@/components/ui/alert"
|
||||||
|
import { Cloud, Trash2, RefreshCw, CheckCircle, AlertTriangle, HardDrive } from "lucide-react"
|
||||||
|
import { StorageHealthService } from "@/lib/supabase-service-updated"
|
||||||
|
|
||||||
|
export default function StorageManagement() {
|
||||||
|
const [storageHealth, setStorageHealth] = useState<{
|
||||||
|
healthy: boolean
|
||||||
|
stats?: { totalFiles: number; totalSize: number }
|
||||||
|
error?: string
|
||||||
|
} | null>(null)
|
||||||
|
const [isLoading, setIsLoading] = useState(false)
|
||||||
|
const [cleanupResult, setCleanupResult] = useState<{ cleaned: number; error?: string } | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
checkStorageHealth()
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const checkStorageHealth = async () => {
|
||||||
|
setIsLoading(true)
|
||||||
|
try {
|
||||||
|
const health = await StorageHealthService.checkStorageHealth()
|
||||||
|
setStorageHealth(health)
|
||||||
|
} catch (error) {
|
||||||
|
setStorageHealth({ healthy: false, error: `檢查失敗: ${error}` })
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const cleanupOrphanedImages = async () => {
|
||||||
|
if (!confirm("確定要清理孤立的圖片嗎?這將刪除沒有被任何困擾案例引用的圖片。")) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsLoading(true)
|
||||||
|
try {
|
||||||
|
const result = await StorageHealthService.cleanupOrphanedImages()
|
||||||
|
setCleanupResult(result)
|
||||||
|
// 重新檢查存儲狀態
|
||||||
|
await checkStorageHealth()
|
||||||
|
} catch (error) {
|
||||||
|
setCleanupResult({ cleaned: 0, error: `清理失敗: ${error}` })
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatFileSize = (bytes: number): string => {
|
||||||
|
if (bytes === 0) return "0 Bytes"
|
||||||
|
const k = 1024
|
||||||
|
const sizes = ["Bytes", "KB", "MB", "GB"]
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||||
|
return Number.parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* 存儲狀態 */}
|
||||||
|
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-white flex items-center gap-3">
|
||||||
|
<Cloud className="w-6 h-6 text-blue-400" />
|
||||||
|
Supabase Storage 狀態
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription className="text-blue-200">雲端圖片存儲服務狀態和使用情況</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<div className="flex items-center justify-between p-4 bg-slate-700/50 rounded-lg">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div
|
||||||
|
className={`w-4 h-4 rounded-full ${
|
||||||
|
storageHealth?.healthy ? "bg-green-400" : "bg-red-400"
|
||||||
|
} ${isLoading ? "animate-pulse" : ""}`}
|
||||||
|
></div>
|
||||||
|
<span className="text-white">存儲服務狀態</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Badge
|
||||||
|
className={storageHealth?.healthy ? "bg-green-500/20 text-green-200" : "bg-red-500/20 text-red-200"}
|
||||||
|
>
|
||||||
|
{isLoading ? "檢查中..." : storageHealth?.healthy ? "正常運行" : "服務異常"}
|
||||||
|
</Badge>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={checkStorageHealth}
|
||||||
|
disabled={isLoading}
|
||||||
|
className="text-blue-200 hover:text-white"
|
||||||
|
>
|
||||||
|
<RefreshCw className={`w-4 h-4 ${isLoading ? "animate-spin" : ""}`} />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 存儲統計 */}
|
||||||
|
{storageHealth?.stats && (
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="p-4 bg-slate-700/50 rounded-lg text-center">
|
||||||
|
<div className="text-2xl font-bold text-white mb-1">{storageHealth.stats.totalFiles}</div>
|
||||||
|
<div className="text-sm text-slate-300">圖片檔案</div>
|
||||||
|
</div>
|
||||||
|
<div className="p-4 bg-slate-700/50 rounded-lg text-center">
|
||||||
|
<div className="text-2xl font-bold text-white mb-1">
|
||||||
|
{formatFileSize(storageHealth.stats.totalSize)}
|
||||||
|
</div>
|
||||||
|
<div className="text-sm text-slate-300">總使用空間</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 存儲使用進度條 */}
|
||||||
|
{storageHealth?.stats && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex justify-between text-sm">
|
||||||
|
<span className="text-slate-300">存儲使用量</span>
|
||||||
|
<span className="text-slate-400">{formatFileSize(storageHealth.stats.totalSize)} / 1GB (免費額度)</span>
|
||||||
|
</div>
|
||||||
|
<Progress
|
||||||
|
value={Math.min((storageHealth.stats.totalSize / (1024 * 1024 * 1024)) * 100, 100)}
|
||||||
|
className="w-full"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 錯誤訊息 */}
|
||||||
|
{storageHealth?.error && (
|
||||||
|
<Alert className="border-red-500/50 bg-red-900/20">
|
||||||
|
<AlertTriangle className="h-4 w-4 text-red-400" />
|
||||||
|
<AlertDescription className="text-red-100">
|
||||||
|
<div className="space-y-1">
|
||||||
|
<p>存儲服務檢查失敗:</p>
|
||||||
|
<p className="text-sm">{storageHealth.error}</p>
|
||||||
|
</div>
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* 存儲管理 */}
|
||||||
|
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-white flex items-center gap-3">
|
||||||
|
<HardDrive className="w-6 h-6 text-purple-400" />
|
||||||
|
存儲管理
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription className="text-blue-200">管理和優化雲端圖片存儲</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<div className="p-4 bg-slate-700/50 rounded-lg">
|
||||||
|
<h4 className="text-white font-semibold mb-2 flex items-center gap-2">
|
||||||
|
<Trash2 className="w-4 h-4 text-orange-400" />
|
||||||
|
清理孤立圖片
|
||||||
|
</h4>
|
||||||
|
<p className="text-slate-300 text-sm mb-3">清理沒有被任何困擾案例引用的圖片檔案,釋放存儲空間。</p>
|
||||||
|
<Button
|
||||||
|
onClick={cleanupOrphanedImages}
|
||||||
|
disabled={isLoading || !storageHealth?.healthy}
|
||||||
|
className="bg-gradient-to-r from-orange-500 to-red-600 hover:from-orange-600 hover:to-red-700 text-white"
|
||||||
|
>
|
||||||
|
<Trash2 className="w-4 h-4 mr-2" />
|
||||||
|
{isLoading ? "清理中..." : "開始清理"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 清理結果 */}
|
||||||
|
{cleanupResult && (
|
||||||
|
<Alert
|
||||||
|
className={`${
|
||||||
|
cleanupResult.error ? "border-red-500/50 bg-red-900/20" : "border-green-500/50 bg-green-900/20"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{cleanupResult.error ? (
|
||||||
|
<AlertTriangle className="h-4 w-4 text-red-400" />
|
||||||
|
) : (
|
||||||
|
<CheckCircle className="h-4 w-4 text-green-400" />
|
||||||
|
)}
|
||||||
|
<AlertDescription className={cleanupResult.error ? "text-red-100" : "text-green-100"}>
|
||||||
|
{cleanupResult.error ? (
|
||||||
|
<div>
|
||||||
|
<p>清理過程中發生錯誤:</p>
|
||||||
|
<p className="text-sm mt-1">{cleanupResult.error}</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div>
|
||||||
|
<p>清理完成!</p>
|
||||||
|
<p className="text-sm mt-1">
|
||||||
|
{cleanupResult.cleaned > 0
|
||||||
|
? `成功清理了 ${cleanupResult.cleaned} 個孤立的圖片檔案`
|
||||||
|
: "沒有發現需要清理的孤立圖片"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 存儲最佳實踐 */}
|
||||||
|
<div className="p-4 bg-blue-900/20 border border-blue-600/30 rounded-lg">
|
||||||
|
<h4 className="text-blue-200 font-semibold mb-2">💡 存儲最佳實踐</h4>
|
||||||
|
<ul className="text-blue-100 text-sm space-y-1">
|
||||||
|
<li>• 定期清理孤立圖片以節省存儲空間</li>
|
||||||
|
<li>• 上傳前壓縮大圖片以減少存儲使用量</li>
|
||||||
|
<li>• 避免上傳重複的圖片內容</li>
|
||||||
|
<li>• 使用適當的圖片格式(WebP 通常最優)</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
@@ -11,10 +11,15 @@ import { Input } from "@/components/ui/input"
|
|||||||
import { Label } from "@/components/ui/label"
|
import { Label } from "@/components/ui/label"
|
||||||
import { Textarea } from "@/components/ui/textarea"
|
import { Textarea } from "@/components/ui/textarea"
|
||||||
import { Checkbox } from "@/components/ui/checkbox"
|
import { Checkbox } from "@/components/ui/checkbox"
|
||||||
import { Sparkles, ArrowLeft, Send, BarChart3, Eye, EyeOff, Shield, Info } from "lucide-react"
|
import { Sparkles, ArrowLeft, Send, BarChart3, Eye, EyeOff, Shield, Info, Mail, ImageIcon } from "lucide-react"
|
||||||
import { useToast } from "@/hooks/use-toast"
|
import { useToast } from "@/hooks/use-toast"
|
||||||
import { soundManager } from "@/lib/sound-effects"
|
import { soundManager } from "@/lib/sound-effects"
|
||||||
import HeaderMusicControl from "@/components/header-music-control"
|
import HeaderMusicControl from "@/components/header-music-control"
|
||||||
|
import { moderateWishForm, type ModerationResult } from "@/lib/content-moderation"
|
||||||
|
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"
|
||||||
|
|
||||||
export default function SubmitPage() {
|
export default function SubmitPage() {
|
||||||
const [formData, setFormData] = useState({
|
const [formData, setFormData] = useState({
|
||||||
@@ -22,11 +27,15 @@ export default function SubmitPage() {
|
|||||||
currentPain: "",
|
currentPain: "",
|
||||||
expectedSolution: "",
|
expectedSolution: "",
|
||||||
expectedEffect: "",
|
expectedEffect: "",
|
||||||
isPublic: true, // 預設為公開
|
isPublic: true,
|
||||||
|
email: "",
|
||||||
})
|
})
|
||||||
|
const [images, setImages] = useState<ImageFile[]>([])
|
||||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||||
const { toast } = useToast()
|
const { toast } = useToast()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
const [moderationResult, setModerationResult] = useState<ModerationResult | null>(null)
|
||||||
|
const [showModerationFeedback, setShowModerationFeedback] = useState(false)
|
||||||
|
|
||||||
// 初始化音效系統
|
// 初始化音效系統
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -43,31 +52,64 @@ export default function SubmitPage() {
|
|||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
|
|
||||||
|
// 先進行內容審核
|
||||||
|
const moderation = moderateWishForm(formData)
|
||||||
|
setModerationResult(moderation)
|
||||||
|
|
||||||
|
if (!moderation.isAppropriate) {
|
||||||
|
setShowModerationFeedback(true)
|
||||||
|
await soundManager.play("click") // 播放提示音效
|
||||||
|
toast({
|
||||||
|
title: "內容需要修改",
|
||||||
|
description: "請根據建議修改內容後再次提交",
|
||||||
|
variant: "destructive",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
setIsSubmitting(true)
|
setIsSubmitting(true)
|
||||||
|
setShowModerationFeedback(false)
|
||||||
|
|
||||||
// 播放提交音效
|
// 播放提交音效
|
||||||
await soundManager.play("submit")
|
await soundManager.play("submit")
|
||||||
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 1500))
|
try {
|
||||||
|
// 創建困擾案例到 Supabase 數據庫
|
||||||
|
await WishService.createWish({
|
||||||
|
title: formData.title,
|
||||||
|
currentPain: formData.currentPain,
|
||||||
|
expectedSolution: formData.expectedSolution,
|
||||||
|
expectedEffect: formData.expectedEffect,
|
||||||
|
isPublic: formData.isPublic,
|
||||||
|
email: formData.email,
|
||||||
|
images: images, // 直接傳遞 ImageFile 數組
|
||||||
|
})
|
||||||
|
|
||||||
const wishes = JSON.parse(localStorage.getItem("wishes") || "[]")
|
// 播放成功音效
|
||||||
const newWish = {
|
await soundManager.play("success")
|
||||||
id: Date.now(),
|
|
||||||
...formData,
|
toast({
|
||||||
createdAt: new Date().toISOString(),
|
title: "你的困擾已成功提交",
|
||||||
|
description: formData.isPublic
|
||||||
|
? "正在為你準備專業的回饋,其他人也能看到你的分享..."
|
||||||
|
: "正在為你準備專業的回饋,你的分享將保持私密...",
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
console.error("提交困擾失敗:", error)
|
||||||
|
|
||||||
|
// 播放錯誤音效
|
||||||
|
await soundManager.play("click")
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: "提交失敗",
|
||||||
|
description: "請稍後再試或檢查網路連接",
|
||||||
|
variant: "destructive",
|
||||||
|
})
|
||||||
|
|
||||||
|
setIsSubmitting(false)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
wishes.push(newWish)
|
|
||||||
localStorage.setItem("wishes", JSON.stringify(wishes))
|
|
||||||
|
|
||||||
// 播放成功音效
|
|
||||||
await soundManager.play("success")
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: "你的困擾已成功提交",
|
|
||||||
description: formData.isPublic
|
|
||||||
? "正在為你準備專業的回饋,其他人也能看到你的分享..."
|
|
||||||
: "正在為你準備專業的回饋,你的分享將保持私密...",
|
|
||||||
})
|
|
||||||
|
|
||||||
setFormData({
|
setFormData({
|
||||||
title: "",
|
title: "",
|
||||||
@@ -75,8 +117,11 @@ export default function SubmitPage() {
|
|||||||
expectedSolution: "",
|
expectedSolution: "",
|
||||||
expectedEffect: "",
|
expectedEffect: "",
|
||||||
isPublic: true,
|
isPublic: true,
|
||||||
|
email: "",
|
||||||
})
|
})
|
||||||
|
setImages([])
|
||||||
setIsSubmitting(false)
|
setIsSubmitting(false)
|
||||||
|
setModerationResult(null)
|
||||||
|
|
||||||
// 跳轉到感謝頁面
|
// 跳轉到感謝頁面
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
@@ -354,6 +399,70 @@ export default function SubmitPage() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* 圖片上傳區域 */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-blue-100 font-semibold text-sm md:text-base flex items-center gap-2">
|
||||||
|
<ImageIcon className="w-4 h-4" />
|
||||||
|
相關圖片 (可選)
|
||||||
|
</Label>
|
||||||
|
<div className="text-xs md:text-sm text-slate-400 mb-3">
|
||||||
|
上傳與困擾相關的截圖、照片或文件圖片,幫助我們更好地理解問題
|
||||||
|
</div>
|
||||||
|
<ImageUpload images={images} onImagesChange={setImages} disabled={isSubmitting} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Email 聯絡資訊 - 可選 */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label
|
||||||
|
htmlFor="email"
|
||||||
|
className="text-blue-100 font-semibold text-sm md:text-base flex items-center gap-2"
|
||||||
|
>
|
||||||
|
<Mail className="w-4 h-4" />
|
||||||
|
聯絡信箱 (可選)
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
placeholder="your.email@example.com"
|
||||||
|
value={formData.email}
|
||||||
|
onChange={(e) => handleChange("email", e.target.value)}
|
||||||
|
className="bg-slate-700/50 border-blue-600/50 text-white placeholder:text-blue-300 focus:border-cyan-400 text-sm md:text-base"
|
||||||
|
/>
|
||||||
|
<div className="text-xs md:text-sm text-slate-400 leading-relaxed">
|
||||||
|
<div className="flex items-start gap-2 mb-2">
|
||||||
|
<Shield className="w-3 h-3 text-blue-400 mt-0.5 flex-shrink-0" />
|
||||||
|
<div>
|
||||||
|
<p className="font-medium text-blue-300 mb-1">完全匿名且可選</p>
|
||||||
|
<ul className="space-y-1 text-slate-400">
|
||||||
|
<li>• 你的身份將完全保持匿名,我們不會公開任何個人資訊</li>
|
||||||
|
<li>• 提供 Email 僅用於我們主動聯繫你,提供個人化的解決方案建議</li>
|
||||||
|
<li>• 如果不想被聯繫,完全可以留空,不影響困擾的提交和分析</li>
|
||||||
|
<li>• 我們承諾不會將你的 Email 用於任何行銷或其他用途</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 內容審核回饋 */}
|
||||||
|
{showModerationFeedback && moderationResult && (
|
||||||
|
<ContentModerationFeedback
|
||||||
|
result={moderationResult}
|
||||||
|
onRetry={() => {
|
||||||
|
const newModeration = moderateWishForm(formData)
|
||||||
|
setModerationResult(newModeration)
|
||||||
|
if (newModeration.isAppropriate) {
|
||||||
|
setShowModerationFeedback(false)
|
||||||
|
toast({
|
||||||
|
title: "內容檢查通過",
|
||||||
|
description: "現在可以提交你的困擾了!",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="animate-in slide-in-from-top-2 duration-300"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* 隱私設定區塊 */}
|
{/* 隱私設定區塊 */}
|
||||||
<div className="space-y-4 p-4 md:p-5 bg-gradient-to-r from-slate-700/30 to-slate-800/30 rounded-lg border border-slate-600/50">
|
<div className="space-y-4 p-4 md:p-5 bg-gradient-to-r from-slate-700/30 to-slate-800/30 rounded-lg border border-slate-600/50">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
@@ -391,12 +500,12 @@ export default function SubmitPage() {
|
|||||||
<div className="text-xs md:text-sm text-slate-300 leading-relaxed">
|
<div className="text-xs md:text-sm text-slate-300 leading-relaxed">
|
||||||
{formData.isPublic ? (
|
{formData.isPublic ? (
|
||||||
<span>
|
<span>
|
||||||
✅ 你的困擾將會出現在「聆聽心聲」頁面,讓其他人看到並產生共鳴
|
✅ 你的困擾和圖片將會出現在「聆聽心聲」頁面,讓其他人看到並產生共鳴
|
||||||
<br />✅ 同時納入「問題洞察」分析,幫助改善整體工作環境
|
<br />✅ 同時納入「問題洞察」分析,幫助改善整體工作環境
|
||||||
</span>
|
</span>
|
||||||
) : (
|
) : (
|
||||||
<span>
|
<span>
|
||||||
🔒 你的困擾將保持私密,不會出現在「聆聽心聲」頁面
|
🔒 你的困擾和圖片將保持私密,不會出現在「聆聽心聲」頁面
|
||||||
<br />✅ 仍會納入「問題洞察」分析,幫助開發者和管理者了解問題趨勢
|
<br />✅ 仍會納入「問題洞察」分析,幫助開發者和管理者了解問題趨勢
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
@@ -413,6 +522,7 @@ export default function SubmitPage() {
|
|||||||
<ul className="space-y-1 text-slate-400">
|
<ul className="space-y-1 text-slate-400">
|
||||||
<li>• 無論選擇公開或私密,你的個人身份都會保持匿名</li>
|
<li>• 無論選擇公開或私密,你的個人身份都會保持匿名</li>
|
||||||
<li>• 私密分享只用於統計分析,幫助了解整體問題狀況</li>
|
<li>• 私密分享只用於統計分析,幫助了解整體問題狀況</li>
|
||||||
|
<li>• 上傳的圖片會與文字內容一起受到相同的隱私保護</li>
|
||||||
<li>• 你可以隨時改變想法,但提交後無法修改此設定</li>
|
<li>• 你可以隨時改變想法,但提交後無法修改此設定</li>
|
||||||
<li>• 所有數據都會安全保存,僅用於改善工作環境</li>
|
<li>• 所有數據都會安全保存,僅用於改善工作環境</li>
|
||||||
</ul>
|
</ul>
|
||||||
@@ -437,6 +547,7 @@ export default function SubmitPage() {
|
|||||||
<>
|
<>
|
||||||
<Send className="w-4 h-4 mr-2" />
|
<Send className="w-4 h-4 mr-2" />
|
||||||
{formData.isPublic ? "公開提交困擾" : "私密提交困擾"}
|
{formData.isPublic ? "公開提交困擾" : "私密提交困擾"}
|
||||||
|
{images.length > 0 && <span className="ml-1 text-xs opacity-75">({images.length} 張圖片)</span>}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
|
@@ -6,6 +6,7 @@ import { Button } from "@/components/ui/button"
|
|||||||
import { Card, CardContent } from "@/components/ui/card"
|
import { Card, CardContent } from "@/components/ui/card"
|
||||||
import { Sparkles, Heart, Users, ArrowRight, Home, MessageCircle, BarChart3, Eye, EyeOff } from "lucide-react"
|
import { Sparkles, Heart, Users, ArrowRight, Home, MessageCircle, BarChart3, Eye, EyeOff } from "lucide-react"
|
||||||
import HeaderMusicControl from "@/components/header-music-control"
|
import HeaderMusicControl from "@/components/header-music-control"
|
||||||
|
import { WishService } from "@/lib/supabase-service"
|
||||||
|
|
||||||
export default function ThankYouPage() {
|
export default function ThankYouPage() {
|
||||||
const [wishes, setWishes] = useState<any[]>([])
|
const [wishes, setWishes] = useState<any[]>([])
|
||||||
@@ -13,15 +14,48 @@ export default function ThankYouPage() {
|
|||||||
const [lastWishIsPublic, setLastWishIsPublic] = useState(true)
|
const [lastWishIsPublic, setLastWishIsPublic] = useState(true)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const savedWishes = JSON.parse(localStorage.getItem("wishes") || "[]")
|
const fetchWishes = async () => {
|
||||||
setWishes(savedWishes)
|
try {
|
||||||
|
// 獲取所有困擾案例
|
||||||
|
const allWishesData = await WishService.getAllWishes()
|
||||||
|
|
||||||
|
// 轉換數據格式
|
||||||
|
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)
|
||||||
|
setWishes(allWishes)
|
||||||
|
|
||||||
// 檢查最後一個提交的願望是否為公開
|
// 檢查最後一個提交的願望是否為公開
|
||||||
if (savedWishes.length > 0) {
|
if (allWishes.length > 0) {
|
||||||
const lastWish = savedWishes[savedWishes.length - 1]
|
const lastWish = allWishes[allWishes.length - 1]
|
||||||
setLastWishIsPublic(lastWish.isPublic !== false)
|
setLastWishIsPublic(lastWish.isPublic !== false)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("獲取統計數據失敗:", error)
|
||||||
|
// 如果 Supabase 連接失敗,回退到 localStorage
|
||||||
|
const savedWishes = JSON.parse(localStorage.getItem("wishes") || "[]")
|
||||||
|
setWishes(savedWishes)
|
||||||
|
|
||||||
|
if (savedWishes.length > 0) {
|
||||||
|
const lastWish = savedWishes[savedWishes.length - 1]
|
||||||
|
setLastWishIsPublic(lastWish.isPublic !== false)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fetchWishes()
|
||||||
|
|
||||||
// 延遲顯示內容,創造進入效果
|
// 延遲顯示內容,創造進入效果
|
||||||
setTimeout(() => setShowContent(true), 300)
|
setTimeout(() => setShowContent(true), 300)
|
||||||
}, [])
|
}, [])
|
||||||
@@ -250,7 +284,7 @@ export default function ThankYouPage() {
|
|||||||
|
|
||||||
{/* 統計卡片 */}
|
{/* 統計卡片 */}
|
||||||
<div className="grid sm:grid-cols-2 md:grid-cols-3 gap-4 sm:gap-6 md:gap-8 mb-8 sm:mb-12 md:mb-16">
|
<div className="grid sm:grid-cols-2 md:grid-cols-3 gap-4 sm:gap-6 md:gap-8 mb-8 sm:mb-12 md:mb-16">
|
||||||
<Card className="bg-gradient-to-br from-pink-800/30 to-purple-800/30 backdrop-blur-sm border border-pink-600/50 shadow-2xl shadow-pink-500/20 transform hover:scale-105 transition-all duration-300">
|
<Card className="bg-gradient-to-br from-pink-900/60 to-purple-900/60 backdrop-blur-sm border border-pink-700/40 shadow-2xl shadow-pink-500/20 transform hover:scale-105 transition-all duration-300">
|
||||||
<CardContent className="p-4 sm:p-6 md:p-8 text-center">
|
<CardContent className="p-4 sm:p-6 md:p-8 text-center">
|
||||||
<div className="w-12 h-12 md:w-16 md:h-16 bg-gradient-to-br from-pink-400 to-purple-500 rounded-full flex items-center justify-center mx-auto mb-4 shadow-lg shadow-pink-500/30">
|
<div className="w-12 h-12 md:w-16 md:h-16 bg-gradient-to-br from-pink-400 to-purple-500 rounded-full flex items-center justify-center mx-auto mb-4 shadow-lg shadow-pink-500/30">
|
||||||
<Users className="w-6 h-6 md:w-8 md:h-8 text-white" />
|
<Users className="w-6 h-6 md:w-8 md:h-8 text-white" />
|
||||||
@@ -261,7 +295,7 @@ export default function ThankYouPage() {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Card className="bg-gradient-to-br from-cyan-800/30 to-blue-800/30 backdrop-blur-sm border border-cyan-600/50 shadow-2xl shadow-cyan-500/20 transform hover:scale-105 transition-all duration-300">
|
<Card className="bg-gradient-to-br from-cyan-900/60 to-blue-900/60 backdrop-blur-sm border border-cyan-700/40 shadow-2xl shadow-cyan-500/20 transform hover:scale-105 transition-all duration-300">
|
||||||
<CardContent className="p-4 sm:p-6 md:p-8 text-center">
|
<CardContent className="p-4 sm:p-6 md:p-8 text-center">
|
||||||
<div className="w-12 h-12 md:w-16 md:h-16 bg-gradient-to-br from-cyan-400 to-blue-500 rounded-full flex items-center justify-center mx-auto mb-4 shadow-lg shadow-cyan-500/30">
|
<div className="w-12 h-12 md:w-16 md:h-16 bg-gradient-to-br from-cyan-400 to-blue-500 rounded-full flex items-center justify-center mx-auto mb-4 shadow-lg shadow-cyan-500/30">
|
||||||
<Sparkles className="w-6 h-6 md:w-8 md:h-8 text-white" />
|
<Sparkles className="w-6 h-6 md:w-8 md:h-8 text-white" />
|
||||||
@@ -272,7 +306,7 @@ export default function ThankYouPage() {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Card className="bg-gradient-to-br from-purple-800/30 to-indigo-800/30 backdrop-blur-sm border border-purple-600/50 shadow-2xl shadow-purple-500/20 transform hover:scale-105 transition-all duration-300">
|
<Card className="bg-gradient-to-br from-purple-900/60 to-indigo-900/60 backdrop-blur-sm border border-purple-700/40 shadow-2xl shadow-purple-500/20 transform hover:scale-105 transition-all duration-300">
|
||||||
<CardContent className="p-4 sm:p-6 md:p-8 text-center">
|
<CardContent className="p-4 sm:p-6 md:p-8 text-center">
|
||||||
<div className="w-12 h-12 md:w-16 md:h-16 bg-gradient-to-br from-purple-400 to-indigo-500 rounded-full flex items-center justify-center mx-auto mb-4 shadow-lg shadow-purple-500/30">
|
<div className="w-12 h-12 md:w-16 md:h-16 bg-gradient-to-br from-purple-400 to-indigo-500 rounded-full flex items-center justify-center mx-auto mb-4 shadow-lg shadow-purple-500/30">
|
||||||
<Heart className="w-6 h-6 md:w-8 md:h-8 text-white" fill="currentColor" />
|
<Heart className="w-6 h-6 md:w-8 md:h-8 text-white" fill="currentColor" />
|
||||||
|
@@ -9,6 +9,7 @@ import { Sparkles, ArrowLeft, Search, Plus, Filter, X, BarChart3, Eye, Users } f
|
|||||||
import WishCard from "@/components/wish-card"
|
import WishCard from "@/components/wish-card"
|
||||||
import HeaderMusicControl from "@/components/header-music-control"
|
import HeaderMusicControl from "@/components/header-music-control"
|
||||||
import { categories, categorizeWishMultiple, getCategoryStats, type Wish } from "@/lib/categorization"
|
import { categories, categorizeWishMultiple, getCategoryStats, type Wish } from "@/lib/categorization"
|
||||||
|
import { WishService } from "@/lib/supabase-service"
|
||||||
|
|
||||||
export default function WishesPage() {
|
export default function WishesPage() {
|
||||||
const [wishes, setWishes] = useState<Wish[]>([])
|
const [wishes, setWishes] = useState<Wish[]>([])
|
||||||
@@ -22,15 +23,55 @@ export default function WishesPage() {
|
|||||||
const [privateCount, setPrivateCount] = useState(0)
|
const [privateCount, setPrivateCount] = useState(0)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const savedWishes = JSON.parse(localStorage.getItem("wishes") || "[]")
|
const fetchWishes = async () => {
|
||||||
const publicOnly = savedWishes.filter((wish: Wish & { isPublic?: boolean }) => wish.isPublic !== false)
|
try {
|
||||||
const privateOnly = savedWishes.filter((wish: Wish & { isPublic?: boolean }) => wish.isPublic === false)
|
// 獲取所有困擾(用於統計)
|
||||||
|
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
|
||||||
|
|
||||||
setWishes(savedWishes)
|
setWishes(allWishes)
|
||||||
setPublicWishes(publicOnly.reverse())
|
setPublicWishes(publicWishes)
|
||||||
setTotalWishes(savedWishes.length)
|
setTotalWishes(allWishes.length)
|
||||||
setPrivateCount(privateOnly.length)
|
setPrivateCount(privateCount)
|
||||||
setCategoryStats(getCategoryStats(publicOnly)) // 只統計公開的困擾
|
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(savedWishes)
|
||||||
|
setPublicWishes(publicOnly.reverse())
|
||||||
|
setTotalWishes(savedWishes.length)
|
||||||
|
setPrivateCount(privateOnly.length)
|
||||||
|
setCategoryStats(getCategoryStats(publicOnly))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchWishes()
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
161
components/content-moderation-feedback.tsx
Normal file
161
components/content-moderation-feedback.tsx
Normal file
@@ -0,0 +1,161 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { Alert, AlertDescription } from "@/components/ui/alert"
|
||||||
|
import { Badge } from "@/components/ui/badge"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { Card, CardContent } from "@/components/ui/card"
|
||||||
|
import { AlertTriangle, Lightbulb, CheckCircle, XCircle, RefreshCw } from "lucide-react"
|
||||||
|
import type { ModerationResult } from "@/lib/content-moderation"
|
||||||
|
|
||||||
|
interface ContentModerationFeedbackProps {
|
||||||
|
result: ModerationResult
|
||||||
|
onRetry: () => void
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ContentModerationFeedback({ result, onRetry, className = "" }: ContentModerationFeedbackProps) {
|
||||||
|
if (result.issues.length === 0 && result.suggestions.length === 0) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const getSeverityColor = (severity: string) => {
|
||||||
|
switch (severity) {
|
||||||
|
case "high":
|
||||||
|
return "border-red-500/50 bg-red-900/20"
|
||||||
|
case "medium":
|
||||||
|
return "border-yellow-500/50 bg-yellow-900/20"
|
||||||
|
case "low":
|
||||||
|
return "border-blue-500/50 bg-blue-900/20"
|
||||||
|
default:
|
||||||
|
return "border-slate-500/50 bg-slate-900/20"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const getSeverityIcon = (severity: string) => {
|
||||||
|
switch (severity) {
|
||||||
|
case "high":
|
||||||
|
return <XCircle className="w-5 h-5 text-red-400" />
|
||||||
|
case "medium":
|
||||||
|
return <AlertTriangle className="w-5 h-5 text-yellow-400" />
|
||||||
|
case "low":
|
||||||
|
return <Lightbulb className="w-5 h-5 text-blue-400" />
|
||||||
|
default:
|
||||||
|
return <CheckCircle className="w-5 h-5 text-green-400" />
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const getSeverityTitle = (severity: string) => {
|
||||||
|
switch (severity) {
|
||||||
|
case "high":
|
||||||
|
return "內容審核未通過"
|
||||||
|
case "medium":
|
||||||
|
return "內容建議優化"
|
||||||
|
case "low":
|
||||||
|
return "內容建議"
|
||||||
|
default:
|
||||||
|
return "內容檢查"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className={`${getSeverityColor(result.severity)} backdrop-blur-sm border ${className}`}>
|
||||||
|
<CardContent className="p-4 space-y-4">
|
||||||
|
{/* 標題區域 */}
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
{getSeverityIcon(result.severity)}
|
||||||
|
<div className="flex-1">
|
||||||
|
<h4 className="font-semibold text-white text-sm md:text-base">{getSeverityTitle(result.severity)}</h4>
|
||||||
|
<div className="flex items-center gap-2 mt-1">
|
||||||
|
<Badge
|
||||||
|
className={`text-xs px-2 py-0.5 ${
|
||||||
|
result.severity === "high"
|
||||||
|
? "bg-red-500/20 text-red-200 border-red-400/30"
|
||||||
|
: result.severity === "medium"
|
||||||
|
? "bg-yellow-500/20 text-yellow-200 border-yellow-400/30"
|
||||||
|
: "bg-blue-500/20 text-blue-200 border-blue-400/30"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{result.severity === "high" ? "需要修改" : result.severity === "medium" ? "建議優化" : "輕微建議"}
|
||||||
|
</Badge>
|
||||||
|
{!result.isAppropriate && (
|
||||||
|
<Badge className="bg-red-500/20 text-red-200 border-red-400/30 text-xs px-2 py-0.5">無法提交</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{!result.isAppropriate && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={onRetry}
|
||||||
|
className="text-blue-200 hover:text-white hover:bg-blue-800/50 px-3"
|
||||||
|
>
|
||||||
|
<RefreshCw className="w-4 h-4 mr-1" />
|
||||||
|
重新檢查
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 問題列表 */}
|
||||||
|
{result.issues.length > 0 && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h5 className="text-sm font-medium text-red-200 flex items-center gap-2">
|
||||||
|
<AlertTriangle className="w-4 h-4" />
|
||||||
|
發現的問題:
|
||||||
|
</h5>
|
||||||
|
<ul className="space-y-1">
|
||||||
|
{result.issues.map((issue, index) => (
|
||||||
|
<li key={index} className="text-sm text-red-100 flex items-start gap-2">
|
||||||
|
<div className="w-1.5 h-1.5 bg-red-400 rounded-full mt-2 flex-shrink-0"></div>
|
||||||
|
{issue}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 建議列表 */}
|
||||||
|
{result.suggestions.length > 0 && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h5 className="text-sm font-medium text-blue-200 flex items-center gap-2">
|
||||||
|
<Lightbulb className="w-4 h-4" />
|
||||||
|
改善建議:
|
||||||
|
</h5>
|
||||||
|
<ul className="space-y-1">
|
||||||
|
{result.suggestions.map((suggestion, index) => (
|
||||||
|
<li key={index} className="text-sm text-blue-100 flex items-start gap-2">
|
||||||
|
<div className="w-1.5 h-1.5 bg-blue-400 rounded-full mt-2 flex-shrink-0"></div>
|
||||||
|
{suggestion}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 被阻擋的詞彙 */}
|
||||||
|
{result.blockedWords.length > 0 && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h5 className="text-sm font-medium text-red-200">需要修改的詞彙:</h5>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{result.blockedWords.map((word, index) => (
|
||||||
|
<Badge key={index} className="bg-red-500/20 text-red-200 border-red-400/30 text-xs px-2 py-1">
|
||||||
|
{word}
|
||||||
|
</Badge>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 鼓勵訊息 */}
|
||||||
|
{!result.isAppropriate && (
|
||||||
|
<Alert className="border-cyan-500/30 bg-cyan-900/20">
|
||||||
|
<Lightbulb className="h-4 w-4 text-cyan-400" />
|
||||||
|
<AlertDescription className="text-cyan-100 text-sm">
|
||||||
|
我們理解工作中的挫折和困難。請使用更建設性的語言來描述遇到的問題,
|
||||||
|
這樣我們能更好地幫助你找到解決方案。你的每一個真實困擾都很重要!
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
214
components/image-gallery.tsx
Normal file
214
components/image-gallery.tsx
Normal file
@@ -0,0 +1,214 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useState } from "react"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { Card, CardContent } from "@/components/ui/card"
|
||||||
|
import { Badge } from "@/components/ui/badge"
|
||||||
|
import { X, ChevronLeft, ChevronRight, Download, ZoomIn, ZoomOut, RotateCw, Maximize2 } from "lucide-react"
|
||||||
|
import { formatFileSize, type ImageFile } from "@/lib/image-utils"
|
||||||
|
|
||||||
|
interface ImageGalleryProps {
|
||||||
|
images: ImageFile[]
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ImageModalProps {
|
||||||
|
images: ImageFile[]
|
||||||
|
currentIndex: number
|
||||||
|
onClose: () => void
|
||||||
|
onNavigate: (index: number) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
function ImageModal({ images, currentIndex, onClose, onNavigate }: ImageModalProps) {
|
||||||
|
const [zoom, setZoom] = useState(1)
|
||||||
|
const [rotation, setRotation] = useState(0)
|
||||||
|
|
||||||
|
const currentImage = images[currentIndex]
|
||||||
|
|
||||||
|
const handlePrevious = () => {
|
||||||
|
const newIndex = currentIndex > 0 ? currentIndex - 1 : images.length - 1
|
||||||
|
onNavigate(newIndex)
|
||||||
|
setZoom(1)
|
||||||
|
setRotation(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleNext = () => {
|
||||||
|
const newIndex = currentIndex < images.length - 1 ? currentIndex + 1 : 0
|
||||||
|
onNavigate(newIndex)
|
||||||
|
setZoom(1)
|
||||||
|
setRotation(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleZoomIn = () => setZoom((prev) => Math.min(prev + 0.25, 3))
|
||||||
|
const handleZoomOut = () => setZoom((prev) => Math.max(prev - 0.25, 0.25))
|
||||||
|
const handleRotate = () => setRotation((prev) => (prev + 90) % 360)
|
||||||
|
|
||||||
|
const handleDownload = () => {
|
||||||
|
// 創建下載連結
|
||||||
|
const link = document.createElement("a")
|
||||||
|
link.href = currentImage.url
|
||||||
|
link.download = currentImage.name
|
||||||
|
document.body.appendChild(link)
|
||||||
|
link.click()
|
||||||
|
document.body.removeChild(link)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-50 bg-black/90 backdrop-blur-sm flex items-center justify-center">
|
||||||
|
{/* 關閉按鈕 */}
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={onClose}
|
||||||
|
className="absolute top-4 right-4 z-10 text-white hover:bg-white/20"
|
||||||
|
>
|
||||||
|
<X className="w-6 h-6" />
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{/* 工具列 */}
|
||||||
|
<div className="absolute top-4 left-4 z-10 flex items-center gap-2">
|
||||||
|
<Badge className="bg-black/50 text-white border-white/20">
|
||||||
|
{currentIndex + 1} / {images.length}
|
||||||
|
</Badge>
|
||||||
|
<div className="flex items-center gap-1 bg-black/50 rounded-lg p-1">
|
||||||
|
<Button variant="ghost" size="sm" onClick={handleZoomOut} className="text-white hover:bg-white/20 p-2">
|
||||||
|
<ZoomOut className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
<span className="text-white text-sm px-2">{Math.round(zoom * 100)}%</span>
|
||||||
|
<Button variant="ghost" size="sm" onClick={handleZoomIn} className="text-white hover:bg-white/20 p-2">
|
||||||
|
<ZoomIn className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="sm" onClick={handleRotate} className="text-white hover:bg-white/20 p-2">
|
||||||
|
<RotateCw className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="sm" onClick={handleDownload} className="text-white hover:bg-white/20 p-2">
|
||||||
|
<Download className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 導航按鈕 */}
|
||||||
|
{images.length > 1 && (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={handlePrevious}
|
||||||
|
className="absolute left-4 top-1/2 -translate-y-1/2 text-white hover:bg-white/20 p-3"
|
||||||
|
>
|
||||||
|
<ChevronLeft className="w-6 h-6" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={handleNext}
|
||||||
|
className="absolute right-4 top-1/2 -translate-y-1/2 text-white hover:bg-white/20 p-3"
|
||||||
|
>
|
||||||
|
<ChevronRight className="w-6 h-6" />
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 圖片容器 */}
|
||||||
|
<div className="flex items-center justify-center w-full h-full p-16">
|
||||||
|
<img
|
||||||
|
src={currentImage.url || "/placeholder.svg"}
|
||||||
|
alt={currentImage.name}
|
||||||
|
className="max-w-full max-h-full object-contain transition-transform duration-200"
|
||||||
|
style={{
|
||||||
|
transform: `scale(${zoom}) rotate(${rotation}deg)`,
|
||||||
|
}}
|
||||||
|
onError={(e) => {
|
||||||
|
// 如果圖片載入失敗,顯示錯誤訊息
|
||||||
|
const target = e.target as HTMLImageElement
|
||||||
|
target.src = "/placeholder.svg?height=400&width=400&text=圖片載入失敗"
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 圖片資訊 */}
|
||||||
|
<div className="absolute bottom-4 left-4 right-4 z-10">
|
||||||
|
<Card className="bg-black/50 backdrop-blur-sm border-white/20">
|
||||||
|
<CardContent className="p-3">
|
||||||
|
<div className="text-white text-sm">
|
||||||
|
<div className="font-medium truncate">{currentImage.name}</div>
|
||||||
|
<div className="text-white/70 text-xs mt-1">
|
||||||
|
{formatFileSize(currentImage.size)} • {currentImage.type}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ImageGallery({ images, className = "" }: ImageGalleryProps) {
|
||||||
|
const [modalOpen, setModalOpen] = useState(false)
|
||||||
|
const [currentImageIndex, setCurrentImageIndex] = useState(0)
|
||||||
|
|
||||||
|
if (images.length === 0) return null
|
||||||
|
|
||||||
|
const openModal = (index: number) => {
|
||||||
|
setCurrentImageIndex(index)
|
||||||
|
setModalOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const closeModal = () => {
|
||||||
|
setModalOpen(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className={`space-y-3 ${className}`}>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Badge className="bg-blue-500/20 text-blue-200 border border-blue-400/30">
|
||||||
|
📷 相關圖片 ({images.length})
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
|
||||||
|
{images.map((image, index) => (
|
||||||
|
<div key={image.id} className="relative group cursor-pointer" onClick={() => openModal(index)}>
|
||||||
|
<div className="aspect-square rounded-lg overflow-hidden bg-slate-700/50 border border-slate-600/50 hover:border-cyan-400/50 transition-all duration-200">
|
||||||
|
<img
|
||||||
|
src={image.url || "/placeholder.svg"}
|
||||||
|
alt={image.name}
|
||||||
|
className="w-full h-full object-cover transition-transform duration-200 group-hover:scale-105"
|
||||||
|
onError={(e) => {
|
||||||
|
// 如果圖片載入失敗,顯示預設圖片
|
||||||
|
const target = e.target as HTMLImageElement
|
||||||
|
target.src = "/placeholder.svg?height=200&width=200&text=圖片載入失敗"
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* 懸停覆蓋層 */}
|
||||||
|
<div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex items-center justify-center">
|
||||||
|
<div className="text-white text-center">
|
||||||
|
<Maximize2 className="w-6 h-6 mx-auto mb-1" />
|
||||||
|
<div className="text-xs">點擊放大</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 檔案名稱 */}
|
||||||
|
<div className="mt-1 text-xs text-slate-400 truncate" title={image.name}>
|
||||||
|
{image.name}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 圖片模態框 */}
|
||||||
|
{modalOpen && (
|
||||||
|
<ImageModal
|
||||||
|
images={images}
|
||||||
|
currentIndex={currentImageIndex}
|
||||||
|
onClose={closeModal}
|
||||||
|
onNavigate={setCurrentImageIndex}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
334
components/image-upload.tsx
Normal file
334
components/image-upload.tsx
Normal file
@@ -0,0 +1,334 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import type React from "react"
|
||||||
|
|
||||||
|
import { useState, useRef, useCallback } from "react"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { Card, CardContent } from "@/components/ui/card"
|
||||||
|
import { Badge } from "@/components/ui/badge"
|
||||||
|
import { Alert, AlertDescription } from "@/components/ui/alert"
|
||||||
|
import { Upload, X, AlertCircle, Eye, RotateCcw, FileImage } from "lucide-react"
|
||||||
|
import {
|
||||||
|
validateImageFile,
|
||||||
|
createImageFile,
|
||||||
|
revokeImageUrl,
|
||||||
|
formatFileSize,
|
||||||
|
compressImage,
|
||||||
|
MAX_FILES_PER_UPLOAD,
|
||||||
|
MAX_TOTAL_FILES,
|
||||||
|
MAX_FILE_SIZE,
|
||||||
|
type ImageFile,
|
||||||
|
} from "@/lib/image-utils"
|
||||||
|
import { soundManager } from "@/lib/sound-effects"
|
||||||
|
|
||||||
|
interface ImageUploadProps {
|
||||||
|
images: ImageFile[]
|
||||||
|
onImagesChange: (images: ImageFile[]) => void
|
||||||
|
disabled?: boolean
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ImageUpload({ images, onImagesChange, disabled = false, className = "" }: ImageUploadProps) {
|
||||||
|
const [dragActive, setDragActive] = useState(false)
|
||||||
|
const [uploading, setUploading] = useState(false)
|
||||||
|
const [errors, setErrors] = useState<string[]>([])
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||||
|
|
||||||
|
const handleFiles = useCallback(
|
||||||
|
async (files: FileList) => {
|
||||||
|
if (disabled) return
|
||||||
|
|
||||||
|
setUploading(true)
|
||||||
|
setErrors([])
|
||||||
|
|
||||||
|
const newErrors: string[] = []
|
||||||
|
const validFiles: File[] = []
|
||||||
|
|
||||||
|
// 檢查總數量限制
|
||||||
|
if (images.length + files.length > MAX_TOTAL_FILES) {
|
||||||
|
newErrors.push(`最多只能上傳 ${MAX_TOTAL_FILES} 張圖片`)
|
||||||
|
setErrors(newErrors)
|
||||||
|
setUploading(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 檢查單次上傳數量
|
||||||
|
if (files.length > MAX_FILES_PER_UPLOAD) {
|
||||||
|
newErrors.push(`單次最多只能上傳 ${MAX_FILES_PER_UPLOAD} 張圖片`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 驗證每個檔案
|
||||||
|
const filesToProcess = Array.from(files).slice(0, MAX_FILES_PER_UPLOAD)
|
||||||
|
|
||||||
|
for (const file of filesToProcess) {
|
||||||
|
const validation = validateImageFile(file)
|
||||||
|
if (validation.isValid) {
|
||||||
|
validFiles.push(file)
|
||||||
|
} else {
|
||||||
|
newErrors.push(`${file.name}: ${validation.error}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (newErrors.length > 0) {
|
||||||
|
setErrors(newErrors)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (validFiles.length > 0) {
|
||||||
|
try {
|
||||||
|
// 壓縮並創建圖片物件
|
||||||
|
const newImageFiles: ImageFile[] = []
|
||||||
|
|
||||||
|
for (const file of validFiles) {
|
||||||
|
let processedFile = file
|
||||||
|
|
||||||
|
// 如果檔案過大,嘗試壓縮
|
||||||
|
if (file.size > MAX_FILE_SIZE * 0.8) {
|
||||||
|
try {
|
||||||
|
processedFile = await compressImage(file, 1920, 0.8)
|
||||||
|
} catch (error) {
|
||||||
|
console.warn("圖片壓縮失敗,使用原檔案:", error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 轉換為 base64 格式
|
||||||
|
const imageFile = await createImageFile(processedFile)
|
||||||
|
newImageFiles.push(imageFile)
|
||||||
|
}
|
||||||
|
|
||||||
|
onImagesChange([...images, ...newImageFiles])
|
||||||
|
await soundManager.play("success")
|
||||||
|
} catch (error) {
|
||||||
|
newErrors.push("圖片處理失敗,請重試")
|
||||||
|
setErrors(newErrors)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setUploading(false)
|
||||||
|
},
|
||||||
|
[images, onImagesChange, disabled],
|
||||||
|
)
|
||||||
|
|
||||||
|
const handleDrag = useCallback((e: React.DragEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const handleDragIn = useCallback((e: React.DragEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
if (e.dataTransfer.items && e.dataTransfer.items.length > 0) {
|
||||||
|
setDragActive(true)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const handleDragOut = useCallback((e: React.DragEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
setDragActive(false)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const handleDrop = useCallback(
|
||||||
|
(e: React.DragEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
setDragActive(false)
|
||||||
|
|
||||||
|
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
|
||||||
|
handleFiles(e.dataTransfer.files)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[handleFiles],
|
||||||
|
)
|
||||||
|
|
||||||
|
const handleFileInput = useCallback(
|
||||||
|
(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
if (e.target.files && e.target.files.length > 0) {
|
||||||
|
handleFiles(e.target.files)
|
||||||
|
}
|
||||||
|
// 清空 input 值,允許重複選擇相同檔案
|
||||||
|
e.target.value = ""
|
||||||
|
},
|
||||||
|
[handleFiles],
|
||||||
|
)
|
||||||
|
|
||||||
|
const removeImage = useCallback(
|
||||||
|
async (imageId: string) => {
|
||||||
|
const imageToRemove = images.find((img) => img.id === imageId)
|
||||||
|
if (imageToRemove) {
|
||||||
|
revokeImageUrl(imageToRemove)
|
||||||
|
onImagesChange(images.filter((img) => img.id !== imageId))
|
||||||
|
await soundManager.play("click")
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[images, onImagesChange],
|
||||||
|
)
|
||||||
|
|
||||||
|
const clearAllImages = useCallback(async () => {
|
||||||
|
images.forEach(revokeImageUrl)
|
||||||
|
onImagesChange([])
|
||||||
|
setErrors([])
|
||||||
|
await soundManager.play("click")
|
||||||
|
}, [images, onImagesChange])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`space-y-4 ${className}`}>
|
||||||
|
{/* 上傳區域 */}
|
||||||
|
<Card
|
||||||
|
className={`
|
||||||
|
relative overflow-hidden transition-all duration-200 cursor-pointer
|
||||||
|
${
|
||||||
|
dragActive
|
||||||
|
? "border-cyan-400 bg-cyan-500/10 scale-[1.02]"
|
||||||
|
: "border-slate-600/50 bg-slate-700/30 hover:bg-slate-600/40"
|
||||||
|
}
|
||||||
|
${disabled ? "opacity-50 cursor-not-allowed" : ""}
|
||||||
|
`}
|
||||||
|
onDragEnter={handleDragIn}
|
||||||
|
onDragLeave={handleDragOut}
|
||||||
|
onDragOver={handleDrag}
|
||||||
|
onDrop={handleDrop}
|
||||||
|
onClick={() => !disabled && fileInputRef.current?.click()}
|
||||||
|
>
|
||||||
|
<CardContent className="p-6 md:p-8 text-center">
|
||||||
|
<div className="flex flex-col items-center gap-4">
|
||||||
|
<div
|
||||||
|
className={`
|
||||||
|
w-16 h-16 rounded-full flex items-center justify-center transition-all duration-200
|
||||||
|
${dragActive ? "bg-cyan-500/20 text-cyan-300 scale-110" : "bg-slate-600/50 text-slate-300"}
|
||||||
|
`}
|
||||||
|
>
|
||||||
|
{uploading ? (
|
||||||
|
<div className="w-6 h-6 border-2 border-current border-t-transparent rounded-full animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Upload className="w-8 h-8" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h3 className="text-lg font-semibold text-white">{dragActive ? "放開以上傳圖片" : "上傳相關圖片"}</h3>
|
||||||
|
<p className="text-sm text-slate-300">{uploading ? "正在處理圖片..." : "拖拽圖片到此處或點擊選擇檔案"}</p>
|
||||||
|
<div className="flex flex-wrap justify-center gap-2 text-xs text-slate-400">
|
||||||
|
<Badge variant="secondary" className="bg-slate-600/50 text-slate-300">
|
||||||
|
支援 JPG、PNG、WebP、GIF
|
||||||
|
</Badge>
|
||||||
|
<Badge variant="secondary" className="bg-slate-600/50 text-slate-300">
|
||||||
|
單檔最大 5MB
|
||||||
|
</Badge>
|
||||||
|
<Badge variant="secondary" className="bg-slate-600/50 text-slate-300">
|
||||||
|
最多 {MAX_TOTAL_FILES} 張
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
multiple
|
||||||
|
accept="image/*"
|
||||||
|
onChange={handleFileInput}
|
||||||
|
className="hidden"
|
||||||
|
disabled={disabled}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* 錯誤訊息 */}
|
||||||
|
{errors.length > 0 && (
|
||||||
|
<Alert className="border-red-500/50 bg-red-900/20">
|
||||||
|
<AlertCircle className="h-4 w-4 text-red-400" />
|
||||||
|
<AlertDescription className="text-red-100">
|
||||||
|
<div className="space-y-1">
|
||||||
|
{errors.map((error, index) => (
|
||||||
|
<div key={index} className="text-sm">
|
||||||
|
• {error}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 已上傳的圖片 */}
|
||||||
|
{images.length > 0 && (
|
||||||
|
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50">
|
||||||
|
<CardContent className="p-4">
|
||||||
|
<div className="flex items-center justify-between mb-4">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<FileImage className="w-5 h-5 text-blue-400" />
|
||||||
|
<h4 className="font-semibold text-white">
|
||||||
|
已上傳圖片 ({images.length}/{MAX_TOTAL_FILES})
|
||||||
|
</h4>
|
||||||
|
</div>
|
||||||
|
{images.length > 1 && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={clearAllImages}
|
||||||
|
className="text-red-300 hover:text-red-200 hover:bg-red-900/20"
|
||||||
|
>
|
||||||
|
<RotateCcw className="w-4 h-4 mr-1" />
|
||||||
|
清空全部
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
|
||||||
|
{images.map((image) => (
|
||||||
|
<div key={image.id} className="relative group">
|
||||||
|
<div className="aspect-square rounded-lg overflow-hidden bg-slate-700/50 border border-slate-600/50">
|
||||||
|
<img
|
||||||
|
src={image.url || "/placeholder.svg"}
|
||||||
|
alt={image.name}
|
||||||
|
className="w-full h-full object-cover transition-transform duration-200 group-hover:scale-105"
|
||||||
|
onError={(e) => {
|
||||||
|
// 如果圖片載入失敗,顯示預設圖片
|
||||||
|
const target = e.target as HTMLImageElement
|
||||||
|
target.src = "/placeholder.svg?height=200&width=200&text=圖片載入失敗"
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* 懸停覆蓋層 */}
|
||||||
|
<div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex items-center justify-center gap-2">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="text-white hover:bg-white/20 p-2"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
// 在新視窗中開啟圖片
|
||||||
|
window.open(image.url, "_blank")
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Eye className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="text-red-300 hover:text-red-200 hover:bg-red-900/20 p-2"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
removeImage(image.id)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<X className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 檔案資訊 */}
|
||||||
|
<div className="mt-2 text-xs text-slate-400 truncate">
|
||||||
|
<div className="font-medium text-slate-300 truncate" title={image.name}>
|
||||||
|
{image.name}
|
||||||
|
</div>
|
||||||
|
<div>{formatFileSize(image.size)}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
314
components/migration-dialog.tsx
Normal file
314
components/migration-dialog.tsx
Normal file
@@ -0,0 +1,314 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useState, useEffect } from "react"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||||
|
import { Badge } from "@/components/ui/badge"
|
||||||
|
import { Alert, AlertDescription } from "@/components/ui/alert"
|
||||||
|
import { Progress } from "@/components/ui/progress"
|
||||||
|
import { Database, Upload, CheckCircle, XCircle, AlertTriangle, Loader2, Trash2, RefreshCw } from "lucide-react"
|
||||||
|
import { MigrationService, testSupabaseConnection } from "@/lib/supabase-service"
|
||||||
|
|
||||||
|
interface MigrationDialogProps {
|
||||||
|
onComplete?: () => void
|
||||||
|
onSkip?: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function MigrationDialog({ onComplete, onSkip }: MigrationDialogProps) {
|
||||||
|
const [step, setStep] = useState<"check" | "migrate" | "complete" | "error">("check")
|
||||||
|
const [localDataCount, setLocalDataCount] = useState(0)
|
||||||
|
const [migrationResult, setMigrationResult] = useState<{
|
||||||
|
success: number
|
||||||
|
failed: number
|
||||||
|
errors: string[]
|
||||||
|
} | null>(null)
|
||||||
|
const [isConnected, setIsConnected] = useState(false)
|
||||||
|
const [isLoading, setIsLoading] = useState(false)
|
||||||
|
const [progress, setProgress] = useState(0)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
checkLocalData()
|
||||||
|
checkConnection()
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const checkLocalData = () => {
|
||||||
|
try {
|
||||||
|
const wishes = JSON.parse(localStorage.getItem("wishes") || "[]")
|
||||||
|
setLocalDataCount(wishes.length)
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error checking local data:", error)
|
||||||
|
setLocalDataCount(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkConnection = async () => {
|
||||||
|
setIsLoading(true)
|
||||||
|
try {
|
||||||
|
const connected = await testSupabaseConnection()
|
||||||
|
setIsConnected(connected)
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Connection check failed:", error)
|
||||||
|
setIsConnected(false)
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const startMigration = async () => {
|
||||||
|
if (!isConnected) {
|
||||||
|
alert("請先確保 Supabase 連接正常")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setStep("migrate")
|
||||||
|
setIsLoading(true)
|
||||||
|
setProgress(0)
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 模擬進度更新
|
||||||
|
const progressInterval = setInterval(() => {
|
||||||
|
setProgress((prev) => Math.min(prev + 10, 90))
|
||||||
|
}, 200)
|
||||||
|
|
||||||
|
const result = await MigrationService.migrateWishesFromLocalStorage()
|
||||||
|
|
||||||
|
clearInterval(progressInterval)
|
||||||
|
setProgress(100)
|
||||||
|
|
||||||
|
setMigrationResult(result)
|
||||||
|
|
||||||
|
if (result.success > 0) {
|
||||||
|
setStep("complete")
|
||||||
|
} else {
|
||||||
|
setStep("error")
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Migration failed:", error)
|
||||||
|
setMigrationResult({
|
||||||
|
success: 0,
|
||||||
|
failed: localDataCount,
|
||||||
|
errors: [`遷移過程失敗: ${error}`],
|
||||||
|
})
|
||||||
|
setStep("error")
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const clearLocalData = () => {
|
||||||
|
if (confirm("確定要清除本地數據嗎?此操作無法復原。")) {
|
||||||
|
MigrationService.clearLocalStorageData()
|
||||||
|
setLocalDataCount(0)
|
||||||
|
onComplete?.()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const skipMigration = () => {
|
||||||
|
if (confirm("跳過遷移將繼續使用本地存儲。確定要跳過嗎?")) {
|
||||||
|
onSkip?.()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (localDataCount === 0) {
|
||||||
|
return (
|
||||||
|
<Card className="bg-slate-800/50 backdrop-blur-sm border border-green-600/50">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-white flex items-center gap-3">
|
||||||
|
<CheckCircle className="w-6 h-6 text-green-400" />
|
||||||
|
準備就緒
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription className="text-green-200">沒有發現本地數據,可以直接開始使用 Supabase</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<Button
|
||||||
|
onClick={onComplete}
|
||||||
|
className="w-full bg-gradient-to-r from-green-500 to-emerald-600 hover:from-green-600 hover:to-emerald-700 text-white"
|
||||||
|
>
|
||||||
|
開始使用
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="bg-slate-800/50 backdrop-blur-sm border border-blue-600/50">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-white flex items-center gap-3">
|
||||||
|
<Database className="w-6 h-6 text-blue-400" />
|
||||||
|
數據遷移到 Supabase
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription className="text-blue-200">
|
||||||
|
發現 {localDataCount} 個本地困擾案例,建議遷移到雲端數據庫
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
{/* 連接狀態 */}
|
||||||
|
<div className="flex items-center justify-between p-3 bg-slate-700/50 rounded-lg">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<div className={`w-3 h-3 rounded-full ${isConnected ? "bg-green-400" : "bg-red-400"}`}></div>
|
||||||
|
<span className="text-white text-sm">Supabase 連接狀態</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Badge className={isConnected ? "bg-green-500/20 text-green-200" : "bg-red-500/20 text-red-200"}>
|
||||||
|
{isConnected ? "已連接" : "未連接"}
|
||||||
|
</Badge>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={checkConnection}
|
||||||
|
disabled={isLoading}
|
||||||
|
className="text-blue-200 hover:text-white"
|
||||||
|
>
|
||||||
|
<RefreshCw className={`w-4 h-4 ${isLoading ? "animate-spin" : ""}`} />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{step === "check" && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<Alert className="border-blue-500/50 bg-blue-900/20">
|
||||||
|
<AlertTriangle className="h-4 w-4 text-blue-400" />
|
||||||
|
<AlertDescription className="text-blue-100">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<p>
|
||||||
|
<strong>遷移優勢:</strong>
|
||||||
|
</p>
|
||||||
|
<ul className="text-sm space-y-1 ml-4">
|
||||||
|
<li>• 數據永久保存,不會因清除瀏覽器而丟失</li>
|
||||||
|
<li>• 支援多設備同步訪問</li>
|
||||||
|
<li>• 更好的性能和穩定性</li>
|
||||||
|
<li>• 支援更多用戶同時使用</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<Button
|
||||||
|
onClick={startMigration}
|
||||||
|
disabled={!isConnected || isLoading}
|
||||||
|
className="flex-1 bg-gradient-to-r from-blue-500 to-cyan-600 hover:from-blue-600 hover:to-cyan-700 text-white"
|
||||||
|
>
|
||||||
|
<Upload className="w-4 h-4 mr-2" />
|
||||||
|
開始遷移
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={skipMigration}
|
||||||
|
className="border-slate-600 text-slate-300 hover:bg-slate-700 bg-transparent"
|
||||||
|
>
|
||||||
|
暫時跳過
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{step === "migrate" && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="text-center">
|
||||||
|
<Loader2 className="w-8 h-8 animate-spin text-blue-400 mx-auto mb-2" />
|
||||||
|
<p className="text-white">正在遷移數據...</p>
|
||||||
|
</div>
|
||||||
|
<Progress value={progress} className="w-full" />
|
||||||
|
<p className="text-sm text-slate-300 text-center">請稍候,正在將 {localDataCount} 個案例遷移到雲端</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{step === "complete" && migrationResult && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="text-center">
|
||||||
|
<CheckCircle className="w-12 h-12 text-green-400 mx-auto mb-3" />
|
||||||
|
<h3 className="text-xl font-semibold text-white mb-2">遷移完成!</h3>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="text-center p-3 bg-green-900/20 rounded-lg border border-green-600/30">
|
||||||
|
<div className="text-2xl font-bold text-green-400">{migrationResult.success}</div>
|
||||||
|
<div className="text-sm text-green-200">成功遷移</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-center p-3 bg-red-900/20 rounded-lg border border-red-600/30">
|
||||||
|
<div className="text-2xl font-bold text-red-400">{migrationResult.failed}</div>
|
||||||
|
<div className="text-sm text-red-200">遷移失敗</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{migrationResult.errors.length > 0 && (
|
||||||
|
<Alert className="border-yellow-500/50 bg-yellow-900/20">
|
||||||
|
<AlertTriangle className="h-4 w-4 text-yellow-400" />
|
||||||
|
<AlertDescription className="text-yellow-100">
|
||||||
|
<details>
|
||||||
|
<summary className="cursor-pointer">查看錯誤詳情</summary>
|
||||||
|
<div className="mt-2 text-xs space-y-1">
|
||||||
|
{migrationResult.errors.map((error, index) => (
|
||||||
|
<div key={index}>• {error}</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<Button
|
||||||
|
onClick={clearLocalData}
|
||||||
|
className="flex-1 bg-gradient-to-r from-green-500 to-emerald-600 hover:from-green-600 hover:to-emerald-700 text-white"
|
||||||
|
>
|
||||||
|
<Trash2 className="w-4 h-4 mr-2" />
|
||||||
|
清除本地數據並完成
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={onComplete}
|
||||||
|
className="border-slate-600 text-slate-300 hover:bg-slate-700 bg-transparent"
|
||||||
|
>
|
||||||
|
保留本地數據
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{step === "error" && migrationResult && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="text-center">
|
||||||
|
<XCircle className="w-12 h-12 text-red-400 mx-auto mb-3" />
|
||||||
|
<h3 className="text-xl font-semibold text-white mb-2">遷移失敗</h3>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Alert className="border-red-500/50 bg-red-900/20">
|
||||||
|
<XCircle className="h-4 w-4 text-red-400" />
|
||||||
|
<AlertDescription className="text-red-100">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<p>遷移過程中遇到問題:</p>
|
||||||
|
<div className="text-xs space-y-1 ml-4">
|
||||||
|
{migrationResult.errors.map((error, index) => (
|
||||||
|
<div key={index}>• {error}</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<Button
|
||||||
|
onClick={startMigration}
|
||||||
|
disabled={!isConnected}
|
||||||
|
className="flex-1 bg-gradient-to-r from-blue-500 to-cyan-600 hover:from-blue-600 hover:to-cyan-700 text-white"
|
||||||
|
>
|
||||||
|
<RefreshCw className="w-4 h-4 mr-2" />
|
||||||
|
重試遷移
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={skipMigration}
|
||||||
|
className="border-slate-600 text-slate-300 hover:bg-slate-700 bg-transparent"
|
||||||
|
>
|
||||||
|
跳過遷移
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
394
components/supabase-image-upload.tsx
Normal file
394
components/supabase-image-upload.tsx
Normal file
@@ -0,0 +1,394 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import type React from "react"
|
||||||
|
|
||||||
|
import { useState, useRef, useCallback } from "react"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { Card, CardContent } from "@/components/ui/card"
|
||||||
|
import { Badge } from "@/components/ui/badge"
|
||||||
|
import { Alert, AlertDescription } from "@/components/ui/alert"
|
||||||
|
import { Progress } from "@/components/ui/progress"
|
||||||
|
import { Upload, X, AlertCircle, Eye, RotateCcw, FileImage, Cloud, Loader2 } from "lucide-react"
|
||||||
|
import {
|
||||||
|
SupabaseImageService,
|
||||||
|
ImageCompressionService,
|
||||||
|
type SupabaseImageFile,
|
||||||
|
type BatchUploadResult,
|
||||||
|
} from "@/lib/supabase-image-utils"
|
||||||
|
import { soundManager } from "@/lib/sound-effects"
|
||||||
|
|
||||||
|
interface SupabaseImageUploadProps {
|
||||||
|
images: SupabaseImageFile[]
|
||||||
|
onImagesChange: (images: SupabaseImageFile[]) => void
|
||||||
|
disabled?: boolean
|
||||||
|
className?: string
|
||||||
|
maxFiles?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function SupabaseImageUpload({
|
||||||
|
images,
|
||||||
|
onImagesChange,
|
||||||
|
disabled = false,
|
||||||
|
className = "",
|
||||||
|
maxFiles = 10,
|
||||||
|
}: SupabaseImageUploadProps) {
|
||||||
|
const [dragActive, setDragActive] = useState(false)
|
||||||
|
const [uploading, setUploading] = useState(false)
|
||||||
|
const [uploadProgress, setUploadProgress] = useState(0)
|
||||||
|
const [errors, setErrors] = useState<string[]>([])
|
||||||
|
const [uploadStats, setUploadStats] = useState<{ total: 0; completed: 0; failed: 0 }>({
|
||||||
|
total: 0,
|
||||||
|
completed: 0,
|
||||||
|
failed: 0,
|
||||||
|
})
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||||
|
|
||||||
|
const handleFiles = useCallback(
|
||||||
|
async (files: FileList) => {
|
||||||
|
if (disabled) return
|
||||||
|
|
||||||
|
setUploading(true)
|
||||||
|
setErrors([])
|
||||||
|
setUploadProgress(0)
|
||||||
|
|
||||||
|
const fileArray = Array.from(files)
|
||||||
|
const remainingSlots = maxFiles - images.length
|
||||||
|
|
||||||
|
if (fileArray.length > remainingSlots) {
|
||||||
|
setErrors([`最多只能再上傳 ${remainingSlots} 張圖片`])
|
||||||
|
setUploading(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 初始化統計
|
||||||
|
setUploadStats({ total: fileArray.length, completed: 0, failed: 0 })
|
||||||
|
|
||||||
|
// 先壓縮圖片
|
||||||
|
setUploadProgress(10)
|
||||||
|
const compressedFiles = await ImageCompressionService.compressImages(fileArray)
|
||||||
|
setUploadProgress(20)
|
||||||
|
|
||||||
|
// 批量上傳到 Supabase Storage
|
||||||
|
const uploadResult: BatchUploadResult = await SupabaseImageService.uploadImages(compressedFiles)
|
||||||
|
|
||||||
|
// 更新統計
|
||||||
|
setUploadStats({
|
||||||
|
total: uploadResult.total,
|
||||||
|
completed: uploadResult.successful.length,
|
||||||
|
failed: uploadResult.failed.length,
|
||||||
|
})
|
||||||
|
|
||||||
|
// 處理上傳結果
|
||||||
|
if (uploadResult.successful.length > 0) {
|
||||||
|
onImagesChange([...images, ...uploadResult.successful])
|
||||||
|
await soundManager.play("success")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 處理錯誤
|
||||||
|
if (uploadResult.failed.length > 0) {
|
||||||
|
const errorMessages = uploadResult.failed.map((failure) => `${failure.file.name}: ${failure.error}`)
|
||||||
|
setErrors(errorMessages)
|
||||||
|
}
|
||||||
|
|
||||||
|
setUploadProgress(100)
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Upload process error:", error)
|
||||||
|
setErrors([`上傳過程中發生錯誤: ${error}`])
|
||||||
|
} finally {
|
||||||
|
setTimeout(() => {
|
||||||
|
setUploading(false)
|
||||||
|
setUploadProgress(0)
|
||||||
|
setUploadStats({ total: 0, completed: 0, failed: 0 })
|
||||||
|
}, 2000)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[images, onImagesChange, disabled, maxFiles],
|
||||||
|
)
|
||||||
|
|
||||||
|
const handleDrag = useCallback((e: React.DragEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const handleDragIn = useCallback((e: React.DragEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
if (e.dataTransfer.items && e.dataTransfer.items.length > 0) {
|
||||||
|
setDragActive(true)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const handleDragOut = useCallback((e: React.DragEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
setDragActive(false)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const handleDrop = useCallback(
|
||||||
|
(e: React.DragEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
setDragActive(false)
|
||||||
|
|
||||||
|
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
|
||||||
|
handleFiles(e.dataTransfer.files)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[handleFiles],
|
||||||
|
)
|
||||||
|
|
||||||
|
const handleFileInput = useCallback(
|
||||||
|
(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
if (e.target.files && e.target.files.length > 0) {
|
||||||
|
handleFiles(e.target.files)
|
||||||
|
}
|
||||||
|
e.target.value = ""
|
||||||
|
},
|
||||||
|
[handleFiles],
|
||||||
|
)
|
||||||
|
|
||||||
|
const removeImage = useCallback(
|
||||||
|
async (imageId: string) => {
|
||||||
|
const imageToRemove = images.find((img) => img.id === imageId)
|
||||||
|
if (imageToRemove) {
|
||||||
|
// 從 Supabase Storage 刪除圖片
|
||||||
|
const deleteResult = await SupabaseImageService.deleteImage(imageToRemove.storage_path)
|
||||||
|
if (!deleteResult.success) {
|
||||||
|
console.warn("Failed to delete image from storage:", deleteResult.error)
|
||||||
|
// 即使刪除失敗,也從列表中移除(避免阻塞用戶操作)
|
||||||
|
}
|
||||||
|
|
||||||
|
onImagesChange(images.filter((img) => img.id !== imageId))
|
||||||
|
await soundManager.play("click")
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[images, onImagesChange],
|
||||||
|
)
|
||||||
|
|
||||||
|
const clearAllImages = useCallback(async () => {
|
||||||
|
if (images.length === 0) return
|
||||||
|
|
||||||
|
const storagePaths = images.map((img) => img.storage_path)
|
||||||
|
const deleteResult = await SupabaseImageService.deleteImages(storagePaths)
|
||||||
|
|
||||||
|
if (!deleteResult.success) {
|
||||||
|
console.warn("Failed to delete some images from storage:", deleteResult.error)
|
||||||
|
}
|
||||||
|
|
||||||
|
onImagesChange([])
|
||||||
|
setErrors([])
|
||||||
|
await soundManager.play("click")
|
||||||
|
}, [images, onImagesChange])
|
||||||
|
|
||||||
|
const formatFileSize = (bytes: number): string => {
|
||||||
|
if (bytes === 0) return "0 Bytes"
|
||||||
|
const k = 1024
|
||||||
|
const sizes = ["Bytes", "KB", "MB", "GB"]
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||||
|
return Number.parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`space-y-4 ${className}`}>
|
||||||
|
{/* 上傳區域 */}
|
||||||
|
<Card
|
||||||
|
className={`
|
||||||
|
relative overflow-hidden transition-all duration-200 cursor-pointer
|
||||||
|
${
|
||||||
|
dragActive
|
||||||
|
? "border-cyan-400 bg-cyan-500/10 scale-[1.02]"
|
||||||
|
: "border-slate-600/50 bg-slate-700/30 hover:bg-slate-600/40"
|
||||||
|
}
|
||||||
|
${disabled ? "opacity-50 cursor-not-allowed" : ""}
|
||||||
|
`}
|
||||||
|
onDragEnter={handleDragIn}
|
||||||
|
onDragLeave={handleDragOut}
|
||||||
|
onDragOver={handleDrag}
|
||||||
|
onDrop={handleDrop}
|
||||||
|
onClick={() => !disabled && !uploading && fileInputRef.current?.click()}
|
||||||
|
>
|
||||||
|
<CardContent className="p-6 md:p-8 text-center">
|
||||||
|
<div className="flex flex-col items-center gap-4">
|
||||||
|
<div
|
||||||
|
className={`
|
||||||
|
w-16 h-16 rounded-full flex items-center justify-center transition-all duration-200
|
||||||
|
${dragActive ? "bg-cyan-500/20 text-cyan-300 scale-110" : "bg-slate-600/50 text-slate-300"}
|
||||||
|
`}
|
||||||
|
>
|
||||||
|
{uploading ? (
|
||||||
|
<Loader2 className="w-8 h-8 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<div className="relative">
|
||||||
|
<Upload className="w-8 h-8" />
|
||||||
|
<Cloud className="w-4 h-4 absolute -bottom-1 -right-1 text-blue-400" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h3 className="text-lg font-semibold text-white">
|
||||||
|
{uploading ? "正在上傳到雲端..." : dragActive ? "放開以上傳圖片" : "上傳相關圖片到雲端"}
|
||||||
|
</h3>
|
||||||
|
<p className="text-sm text-slate-300">
|
||||||
|
{uploading ? "圖片將安全存儲在 Supabase 雲端" : "拖拽圖片到此處或點擊選擇檔案"}
|
||||||
|
</p>
|
||||||
|
<div className="flex flex-wrap justify-center gap-2 text-xs text-slate-400">
|
||||||
|
<Badge variant="secondary" className="bg-slate-600/50 text-slate-300">
|
||||||
|
<Cloud className="w-3 h-3 mr-1" />
|
||||||
|
雲端存儲
|
||||||
|
</Badge>
|
||||||
|
<Badge variant="secondary" className="bg-slate-600/50 text-slate-300">
|
||||||
|
支援 JPG、PNG、WebP、GIF
|
||||||
|
</Badge>
|
||||||
|
<Badge variant="secondary" className="bg-slate-600/50 text-slate-300">
|
||||||
|
單檔最大 5MB
|
||||||
|
</Badge>
|
||||||
|
<Badge variant="secondary" className="bg-slate-600/50 text-slate-300">
|
||||||
|
最多 {maxFiles} 張
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 上傳進度 */}
|
||||||
|
{uploading && (
|
||||||
|
<div className="mt-6 space-y-3">
|
||||||
|
<Progress value={uploadProgress} className="w-full" />
|
||||||
|
<div className="flex justify-between text-xs text-slate-400">
|
||||||
|
<span>
|
||||||
|
{uploadStats.completed}/{uploadStats.total} 完成
|
||||||
|
</span>
|
||||||
|
<span>{uploadProgress}%</span>
|
||||||
|
</div>
|
||||||
|
{uploadStats.failed > 0 && (
|
||||||
|
<div className="text-xs text-red-400">{uploadStats.failed} 個檔案上傳失敗</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
multiple
|
||||||
|
accept="image/*"
|
||||||
|
onChange={handleFileInput}
|
||||||
|
className="hidden"
|
||||||
|
disabled={disabled || uploading}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* 錯誤訊息 */}
|
||||||
|
{errors.length > 0 && (
|
||||||
|
<Alert className="border-red-500/50 bg-red-900/20">
|
||||||
|
<AlertCircle className="h-4 w-4 text-red-400" />
|
||||||
|
<AlertDescription className="text-red-100">
|
||||||
|
<div className="space-y-1">
|
||||||
|
{errors.map((error, index) => (
|
||||||
|
<div key={index} className="text-sm">
|
||||||
|
• {error}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 已上傳的圖片 */}
|
||||||
|
{images.length > 0 && (
|
||||||
|
<Card className="bg-slate-800/50 backdrop-blur-sm border border-slate-600/50">
|
||||||
|
<CardContent className="p-4">
|
||||||
|
<div className="flex items-center justify-between mb-4">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<FileImage className="w-5 h-5 text-blue-400" />
|
||||||
|
<h4 className="font-semibold text-white">
|
||||||
|
雲端圖片 ({images.length}/{maxFiles})
|
||||||
|
</h4>
|
||||||
|
<Badge className="bg-blue-500/20 text-blue-200 border border-blue-400/30 text-xs px-2 py-1">
|
||||||
|
<Cloud className="w-3 h-3 mr-1" />
|
||||||
|
Supabase
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
{images.length > 1 && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={clearAllImages}
|
||||||
|
disabled={uploading}
|
||||||
|
className="text-red-300 hover:text-red-200 hover:bg-red-900/20"
|
||||||
|
>
|
||||||
|
<RotateCcw className="w-4 h-4 mr-1" />
|
||||||
|
清空全部
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
|
||||||
|
{images.map((image) => (
|
||||||
|
<div key={image.id} className="relative group">
|
||||||
|
<div className="aspect-square rounded-lg overflow-hidden bg-slate-700/50 border border-slate-600/50">
|
||||||
|
<img
|
||||||
|
src={image.public_url || "/placeholder.svg"}
|
||||||
|
alt={image.name}
|
||||||
|
className="w-full h-full object-cover transition-transform duration-200 group-hover:scale-105"
|
||||||
|
onError={(e) => {
|
||||||
|
const target = e.target as HTMLImageElement
|
||||||
|
target.src = "/placeholder.svg?height=200&width=200&text=圖片載入失敗"
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* 懸停覆蓋層 */}
|
||||||
|
<div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex items-center justify-center gap-2">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="text-white hover:bg-white/20 p-2"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
window.open(image.public_url, "_blank")
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Eye className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="text-red-300 hover:text-red-200 hover:bg-red-900/20 p-2"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
removeImage(image.id)
|
||||||
|
}}
|
||||||
|
disabled={uploading}
|
||||||
|
>
|
||||||
|
<X className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 雲端標識 */}
|
||||||
|
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
|
||||||
|
<Badge className="bg-blue-500/80 text-white text-xs px-1.5 py-0.5">
|
||||||
|
<Cloud className="w-3 h-3" />
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 檔案資訊 */}
|
||||||
|
<div className="mt-2 text-xs text-slate-400 truncate">
|
||||||
|
<div className="font-medium text-slate-300 truncate" title={image.name}>
|
||||||
|
{image.name}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span>{formatFileSize(image.size)}</span>
|
||||||
|
<span className="text-blue-400">雲端</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
@@ -17,10 +17,10 @@ const Slider = React.forwardRef<
|
|||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-secondary">
|
<SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-slate-700">
|
||||||
<SliderPrimitive.Range className="absolute h-full bg-primary" />
|
<SliderPrimitive.Range className="absolute h-full bg-white" />
|
||||||
</SliderPrimitive.Track>
|
</SliderPrimitive.Track>
|
||||||
<SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
|
<SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-slate-700 bg-white ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
|
||||||
</SliderPrimitive.Root>
|
</SliderPrimitive.Root>
|
||||||
))
|
))
|
||||||
Slider.displayName = SliderPrimitive.Root.displayName
|
Slider.displayName = SliderPrimitive.Root.displayName
|
||||||
|
@@ -20,9 +20,12 @@ import { categorizeWishMultiple, type Wish } from "@/lib/categorization"
|
|||||||
import { generateSolutionRecommendations, type SolutionCategory } from "@/lib/solution-recommendations"
|
import { generateSolutionRecommendations, type SolutionCategory } from "@/lib/solution-recommendations"
|
||||||
import { useState, useEffect } from "react"
|
import { useState, useEffect } from "react"
|
||||||
import { soundManager } from "@/lib/sound-effects"
|
import { soundManager } from "@/lib/sound-effects"
|
||||||
|
import ImageGallery from "@/components/image-gallery"
|
||||||
|
import { restoreImageFile, type ImageFile } from "@/lib/image-utils"
|
||||||
|
import { LikeService } from "@/lib/supabase-service"
|
||||||
|
|
||||||
interface WishCardProps {
|
interface WishCardProps {
|
||||||
wish: Wish
|
wish: Wish & { images?: any[]; like_count?: number } // 添加圖片支援和點讚數
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function WishCard({ wish }: WishCardProps) {
|
export default function WishCard({ wish }: WishCardProps) {
|
||||||
@@ -34,12 +37,29 @@ export default function WishCard({ wish }: WishCardProps) {
|
|||||||
|
|
||||||
// 載入點讚數據
|
// 載入點讚數據
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const likes = JSON.parse(localStorage.getItem("wishLikes") || "{}")
|
const loadLikeData = async () => {
|
||||||
const likedWishes = JSON.parse(localStorage.getItem("userLikedWishes") || "[]")
|
try {
|
||||||
|
// 從 Supabase 獲取用戶已點讚的困擾列表
|
||||||
|
const userLikedWishes = await LikeService.getUserLikedWishes()
|
||||||
|
|
||||||
|
// 設置點讚狀態
|
||||||
|
setHasLiked(userLikedWishes.includes(wish.id))
|
||||||
|
|
||||||
|
// 點讚數從 wish 的 like_count 字段獲取,如果沒有則默認為 0
|
||||||
|
setLikeCount(wish.like_count || 0)
|
||||||
|
} catch (error) {
|
||||||
|
console.error("載入點讚數據失敗:", error)
|
||||||
|
// 如果 Supabase 連接失敗,回退到 localStorage
|
||||||
|
const likes = JSON.parse(localStorage.getItem("wishLikes") || "{}")
|
||||||
|
const likedWishes = JSON.parse(localStorage.getItem("userLikedWishes") || "[]")
|
||||||
|
|
||||||
setLikeCount(likes[wish.id] || 0)
|
setLikeCount(likes[wish.id] || 0)
|
||||||
setHasLiked(likedWishes.includes(wish.id))
|
setHasLiked(likedWishes.includes(wish.id))
|
||||||
}, [wish.id])
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
loadLikeData()
|
||||||
|
}, [wish.id, wish.like_count])
|
||||||
|
|
||||||
const handleLike = async () => {
|
const handleLike = async () => {
|
||||||
if (hasLiked || isLiking) return
|
if (hasLiked || isLiking) return
|
||||||
@@ -49,24 +69,46 @@ export default function WishCard({ wish }: WishCardProps) {
|
|||||||
// 播放點讚音效
|
// 播放點讚音效
|
||||||
await soundManager.play("click")
|
await soundManager.play("click")
|
||||||
|
|
||||||
// 更新點讚數據
|
try {
|
||||||
const likes = JSON.parse(localStorage.getItem("wishLikes") || "{}")
|
// 使用 Supabase 點讚服務
|
||||||
const likedWishes = JSON.parse(localStorage.getItem("userLikedWishes") || "[]")
|
const success = await LikeService.likeWish(wish.id)
|
||||||
|
|
||||||
|
if (success) {
|
||||||
|
// 更新本地狀態
|
||||||
|
setLikeCount(prev => prev + 1)
|
||||||
|
setHasLiked(true)
|
||||||
|
|
||||||
|
// 播放成功音效
|
||||||
|
setTimeout(async () => {
|
||||||
|
await soundManager.play("success")
|
||||||
|
}, 300)
|
||||||
|
} else {
|
||||||
|
// 已經點讚過
|
||||||
|
console.log("已經點讚過此困擾")
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("點讚失敗:", error)
|
||||||
|
|
||||||
|
// 如果 Supabase 失敗,回退到 localStorage
|
||||||
|
const likes = JSON.parse(localStorage.getItem("wishLikes") || "{}")
|
||||||
|
const likedWishes = JSON.parse(localStorage.getItem("userLikedWishes") || "[]")
|
||||||
|
|
||||||
likes[wish.id] = (likes[wish.id] || 0) + 1
|
likes[wish.id] = (likes[wish.id] || 0) + 1
|
||||||
likedWishes.push(wish.id)
|
likedWishes.push(wish.id)
|
||||||
|
|
||||||
localStorage.setItem("wishLikes", JSON.stringify(likes))
|
localStorage.setItem("wishLikes", JSON.stringify(likes))
|
||||||
localStorage.setItem("userLikedWishes", JSON.stringify(likedWishes))
|
localStorage.setItem("userLikedWishes", JSON.stringify(likedWishes))
|
||||||
|
|
||||||
setLikeCount(likes[wish.id])
|
setLikeCount(likes[wish.id])
|
||||||
setHasLiked(true)
|
setHasLiked(true)
|
||||||
|
|
||||||
// 播放成功音效
|
// 播放成功音效
|
||||||
setTimeout(async () => {
|
setTimeout(async () => {
|
||||||
await soundManager.play("success")
|
await soundManager.play("success")
|
||||||
|
}, 300)
|
||||||
|
} finally {
|
||||||
setIsLiking(false)
|
setIsLiking(false)
|
||||||
}, 300)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const formatDate = (dateString: string) => {
|
const formatDate = (dateString: string) => {
|
||||||
@@ -84,6 +126,9 @@ export default function WishCard({ wish }: WishCardProps) {
|
|||||||
// 生成解決方案建議
|
// 生成解決方案建議
|
||||||
const solutionRecommendation = generateSolutionRecommendations(wish)
|
const solutionRecommendation = generateSolutionRecommendations(wish)
|
||||||
|
|
||||||
|
// 轉換圖片數據格式 - 使用 restoreImageFile 恢復圖片
|
||||||
|
const images: ImageFile[] = (wish.images || []).map((img) => restoreImageFile(img))
|
||||||
|
|
||||||
const getDifficultyColor = (difficulty: string) => {
|
const getDifficultyColor = (difficulty: string) => {
|
||||||
switch (difficulty) {
|
switch (difficulty) {
|
||||||
case "easy":
|
case "easy":
|
||||||
@@ -220,6 +265,16 @@ export default function WishCard({ wish }: WishCardProps) {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* 圖片展示區域 */}
|
||||||
|
{images.length > 0 && (
|
||||||
|
<div className="relative overflow-hidden rounded-lg md:rounded-xl bg-gradient-to-r from-slate-700/60 to-slate-800/60 border border-slate-600/40 hover:border-green-400/30 p-4 md:p-5 backdrop-blur-sm transition-all duration-300">
|
||||||
|
<div className="absolute inset-0 bg-gradient-to-r from-green-500/8 to-emerald-500/8"></div>
|
||||||
|
<div className="relative">
|
||||||
|
<ImageGallery images={images} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* 共鳴支持區塊 - 新增 */}
|
{/* 共鳴支持區塊 - 新增 */}
|
||||||
<div className="relative overflow-hidden rounded-lg md:rounded-xl bg-gradient-to-r from-pink-800/30 to-rose-800/30 border border-pink-600/40 p-3 md:p-4 backdrop-blur-sm transition-all duration-300">
|
<div className="relative overflow-hidden rounded-lg md:rounded-xl bg-gradient-to-r from-pink-800/30 to-rose-800/30 border border-pink-600/40 p-3 md:p-4 backdrop-blur-sm transition-all duration-300">
|
||||||
<div className="absolute inset-0 bg-gradient-to-r from-pink-500/10 to-rose-500/10"></div>
|
<div className="absolute inset-0 bg-gradient-to-r from-pink-500/10 to-rose-500/10"></div>
|
||||||
|
249
lib/background-music-supabase.ts
Normal file
249
lib/background-music-supabase.ts
Normal file
@@ -0,0 +1,249 @@
|
|||||||
|
import { UserSettingsService } from "./supabase-service"
|
||||||
|
|
||||||
|
// 背景音樂管理系統 - Supabase 版本
|
||||||
|
class BackgroundMusicManagerSupabase {
|
||||||
|
private audio: HTMLAudioElement | null = null
|
||||||
|
private isPlaying = false
|
||||||
|
private enabled = false
|
||||||
|
private volume = 0.3
|
||||||
|
private fadeInterval: NodeJS.Timeout | null = null
|
||||||
|
private initialized = false
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.initAudio()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化並載入用戶設定
|
||||||
|
async init() {
|
||||||
|
if (this.initialized) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
const settings = await UserSettingsService.getUserSettings()
|
||||||
|
if (settings) {
|
||||||
|
this.volume = settings.background_music_volume
|
||||||
|
this.enabled = settings.background_music_enabled
|
||||||
|
this.isPlaying = false // 不自動播放
|
||||||
|
}
|
||||||
|
this.initialized = true
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to load user settings:", error)
|
||||||
|
// 使用默認設定
|
||||||
|
this.volume = 0.3
|
||||||
|
this.enabled = false
|
||||||
|
this.isPlaying = false
|
||||||
|
this.initialized = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private initAudio() {
|
||||||
|
try {
|
||||||
|
this.audio = new Audio("https://hebbkx1anhila5yf.public.blob.vercel-storage.com/just-relax-11157-iAgp15dV2YGybAezUJFtKmKZPbteXd.mp3")
|
||||||
|
this.audio.loop = true
|
||||||
|
this.audio.volume = this.volume
|
||||||
|
this.audio.preload = "metadata"
|
||||||
|
this.audio.autoplay = false
|
||||||
|
this.audio.muted = false
|
||||||
|
|
||||||
|
this.audio.addEventListener("canplaythrough", () => {
|
||||||
|
// 音樂載入完成
|
||||||
|
})
|
||||||
|
|
||||||
|
this.audio.addEventListener("error", (e) => {
|
||||||
|
this.reinitAudio()
|
||||||
|
})
|
||||||
|
|
||||||
|
this.audio.addEventListener("ended", () => {
|
||||||
|
if (this.enabled && this.isPlaying) {
|
||||||
|
this.audio?.play().catch(() => {
|
||||||
|
this.reinitAudio()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Audio initialization failed:", error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private reinitAudio() {
|
||||||
|
try {
|
||||||
|
if (this.audio) {
|
||||||
|
this.audio.pause()
|
||||||
|
this.audio.src = ""
|
||||||
|
this.audio = null
|
||||||
|
}
|
||||||
|
setTimeout(() => {
|
||||||
|
this.initAudio()
|
||||||
|
}, 100)
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Audio reinitialization failed:", error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fadeIn(duration = 2000) {
|
||||||
|
if (!this.audio) return
|
||||||
|
|
||||||
|
this.audio.volume = 0
|
||||||
|
const targetVolume = this.volume
|
||||||
|
const steps = 50
|
||||||
|
const stepTime = duration / steps
|
||||||
|
const volumeStep = targetVolume / steps
|
||||||
|
|
||||||
|
let currentStep = 0
|
||||||
|
this.fadeInterval = setInterval(() => {
|
||||||
|
if (currentStep >= steps || !this.audio) {
|
||||||
|
if (this.fadeInterval) {
|
||||||
|
clearInterval(this.fadeInterval)
|
||||||
|
this.fadeInterval = null
|
||||||
|
}
|
||||||
|
if (this.audio) {
|
||||||
|
this.audio.volume = targetVolume
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
this.audio.volume = Math.min(volumeStep * currentStep, targetVolume)
|
||||||
|
currentStep++
|
||||||
|
}, stepTime)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fadeOut(duration = 1000) {
|
||||||
|
if (!this.audio) return
|
||||||
|
|
||||||
|
const startVolume = this.audio.volume
|
||||||
|
const steps = 50
|
||||||
|
const stepTime = duration / steps
|
||||||
|
const volumeStep = startVolume / steps
|
||||||
|
|
||||||
|
let currentStep = 0
|
||||||
|
this.fadeInterval = setInterval(() => {
|
||||||
|
if (currentStep >= steps || !this.audio) {
|
||||||
|
if (this.fadeInterval) {
|
||||||
|
clearInterval(this.fadeInterval)
|
||||||
|
this.fadeInterval = null
|
||||||
|
}
|
||||||
|
if (this.audio) {
|
||||||
|
this.audio.pause()
|
||||||
|
this.audio.currentTime = 0
|
||||||
|
this.audio.volume = this.volume
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
this.audio.volume = Math.max(startVolume - volumeStep * currentStep, 0)
|
||||||
|
currentStep++
|
||||||
|
}, stepTime)
|
||||||
|
}
|
||||||
|
|
||||||
|
async start() {
|
||||||
|
if (!this.initialized) await this.init()
|
||||||
|
|
||||||
|
if (this.fadeInterval) {
|
||||||
|
clearInterval(this.fadeInterval)
|
||||||
|
this.fadeInterval = null
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.audio) {
|
||||||
|
this.initAudio()
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.audio) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
this.enabled = true
|
||||||
|
this.isPlaying = true
|
||||||
|
|
||||||
|
// 保存設定到 Supabase
|
||||||
|
await this.saveSettings()
|
||||||
|
|
||||||
|
this.audio.currentTime = 0
|
||||||
|
this.audio.volume = 0
|
||||||
|
|
||||||
|
await this.audio.play()
|
||||||
|
this.fadeIn(2000)
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to start music:", error)
|
||||||
|
this.reinitAudio()
|
||||||
|
this.isPlaying = false
|
||||||
|
this.enabled = false
|
||||||
|
await this.saveSettings()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async stop() {
|
||||||
|
if (!this.initialized) await this.init()
|
||||||
|
|
||||||
|
if (!this.audio) return
|
||||||
|
|
||||||
|
this.enabled = false
|
||||||
|
this.isPlaying = false
|
||||||
|
|
||||||
|
// 保存設定到 Supabase
|
||||||
|
await this.saveSettings()
|
||||||
|
|
||||||
|
if (this.fadeInterval) {
|
||||||
|
clearInterval(this.fadeInterval)
|
||||||
|
this.fadeInterval = null
|
||||||
|
}
|
||||||
|
|
||||||
|
this.fadeOut(1000)
|
||||||
|
}
|
||||||
|
|
||||||
|
async setVolume(volume: number) {
|
||||||
|
if (!this.initialized) await this.init()
|
||||||
|
|
||||||
|
this.volume = Math.max(0, Math.min(1, volume))
|
||||||
|
if (this.audio && this.isPlaying) {
|
||||||
|
this.audio.volume = this.volume
|
||||||
|
}
|
||||||
|
|
||||||
|
// 保存設定到 Supabase
|
||||||
|
await this.saveSettings()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 保存設定到 Supabase
|
||||||
|
private async saveSettings() {
|
||||||
|
try {
|
||||||
|
await UserSettingsService.updateUserSettings({
|
||||||
|
backgroundMusicEnabled: this.enabled,
|
||||||
|
backgroundMusicVolume: this.volume,
|
||||||
|
backgroundMusicPlaying: this.isPlaying,
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to save music settings:", error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getVolume() {
|
||||||
|
return this.volume
|
||||||
|
}
|
||||||
|
|
||||||
|
isEnabled() {
|
||||||
|
return this.enabled
|
||||||
|
}
|
||||||
|
|
||||||
|
getIsPlaying() {
|
||||||
|
return this.isPlaying && this.audio && !this.audio.paused
|
||||||
|
}
|
||||||
|
|
||||||
|
getState() {
|
||||||
|
return {
|
||||||
|
isPlaying: this.getIsPlaying(),
|
||||||
|
enabled: this.enabled,
|
||||||
|
volume: this.volume,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getMusicInfo() {
|
||||||
|
if (!this.audio) return null
|
||||||
|
|
||||||
|
return {
|
||||||
|
duration: this.audio.duration || 0,
|
||||||
|
currentTime: this.audio.currentTime || 0,
|
||||||
|
loaded: this.audio.readyState >= 3,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 全局背景音樂管理器 - Supabase 版本
|
||||||
|
export const backgroundMusicManagerSupabase = new BackgroundMusicManagerSupabase()
|
@@ -49,9 +49,9 @@ export const categories = [
|
|||||||
"報告",
|
"報告",
|
||||||
"圖表",
|
"圖表",
|
||||||
],
|
],
|
||||||
color: "#EC4899",
|
color: "#DB2777",
|
||||||
bgColor: "from-pink-500/20 to-rose-600/20",
|
bgColor: "from-pink-600/20 to-rose-700/20",
|
||||||
borderColor: "border-pink-400/30",
|
borderColor: "border-pink-500/30",
|
||||||
textColor: "text-pink-200",
|
textColor: "text-pink-200",
|
||||||
icon: "📊",
|
icon: "📊",
|
||||||
},
|
},
|
||||||
@@ -322,10 +322,10 @@ export function categorizeWishMultiple(wish: Wish): Category[] {
|
|||||||
name: "其他問題",
|
name: "其他問題",
|
||||||
description: "未能歸類的特殊工作困擾",
|
description: "未能歸類的特殊工作困擾",
|
||||||
keywords: [],
|
keywords: [],
|
||||||
color: "#6B7280",
|
color: "#94A3B8",
|
||||||
bgColor: "from-gray-500/20 to-slate-600/20",
|
bgColor: "from-slate-400/20 to-slate-500/20",
|
||||||
borderColor: "border-gray-400/30",
|
borderColor: "border-slate-400/40",
|
||||||
textColor: "text-gray-200",
|
textColor: "text-slate-200",
|
||||||
icon: "❓",
|
icon: "❓",
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
249
lib/content-moderation.ts
Normal file
249
lib/content-moderation.ts
Normal file
@@ -0,0 +1,249 @@
|
|||||||
|
// 內容審核 AI 系統
|
||||||
|
export interface ModerationResult {
|
||||||
|
isAppropriate: boolean
|
||||||
|
issues: string[]
|
||||||
|
suggestions: string[]
|
||||||
|
severity: "low" | "medium" | "high"
|
||||||
|
blockedWords: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
// 不雅詞彙和辱罵詞彙庫
|
||||||
|
const inappropriateWords = [
|
||||||
|
// 髒話和不雅詞彙
|
||||||
|
"幹",
|
||||||
|
"靠",
|
||||||
|
"操",
|
||||||
|
"媽的",
|
||||||
|
"他媽的",
|
||||||
|
"去死",
|
||||||
|
"死",
|
||||||
|
"滾",
|
||||||
|
"白痴",
|
||||||
|
"智障",
|
||||||
|
"腦殘",
|
||||||
|
"垃圾",
|
||||||
|
"廢物",
|
||||||
|
"混蛋",
|
||||||
|
"王八蛋",
|
||||||
|
"狗屎",
|
||||||
|
"屎",
|
||||||
|
"婊子",
|
||||||
|
"賤",
|
||||||
|
"爛",
|
||||||
|
"鳥",
|
||||||
|
"屌",
|
||||||
|
"雞掰",
|
||||||
|
"機掰",
|
||||||
|
"北七",
|
||||||
|
|
||||||
|
// 公司辱罵相關
|
||||||
|
"爛公司",
|
||||||
|
"垃圾公司",
|
||||||
|
"黑心公司",
|
||||||
|
"慣老闆",
|
||||||
|
"奴隸主",
|
||||||
|
"血汗工廠",
|
||||||
|
"剝削",
|
||||||
|
"壓榨",
|
||||||
|
"去你的",
|
||||||
|
"見鬼",
|
||||||
|
"該死",
|
||||||
|
"要死",
|
||||||
|
"找死",
|
||||||
|
"活該",
|
||||||
|
"報應",
|
||||||
|
"天殺的",
|
||||||
|
|
||||||
|
// 威脅性詞彙
|
||||||
|
"殺",
|
||||||
|
"打死",
|
||||||
|
"弄死",
|
||||||
|
"搞死",
|
||||||
|
"整死",
|
||||||
|
"報復",
|
||||||
|
"復仇",
|
||||||
|
"毀掉",
|
||||||
|
"搞垮",
|
||||||
|
|
||||||
|
// 歧視性詞彙
|
||||||
|
"歧視",
|
||||||
|
"種族",
|
||||||
|
"性別歧視",
|
||||||
|
"老不死",
|
||||||
|
"死老頭",
|
||||||
|
"死老太婆",
|
||||||
|
"殘廢",
|
||||||
|
"瘸子",
|
||||||
|
|
||||||
|
// 英文不雅詞彙
|
||||||
|
"fuck",
|
||||||
|
"shit",
|
||||||
|
"damn",
|
||||||
|
"bitch",
|
||||||
|
"asshole",
|
||||||
|
"bastard",
|
||||||
|
"crap",
|
||||||
|
"hell",
|
||||||
|
"wtf",
|
||||||
|
"stfu",
|
||||||
|
"bullshit",
|
||||||
|
"motherfucker",
|
||||||
|
"dickhead",
|
||||||
|
"piss",
|
||||||
|
]
|
||||||
|
|
||||||
|
// 負面但可接受的詞彙(會給予建議但不阻擋)
|
||||||
|
const negativeButAcceptableWords = [
|
||||||
|
"討厭",
|
||||||
|
"煩",
|
||||||
|
"累",
|
||||||
|
"辛苦",
|
||||||
|
"困難",
|
||||||
|
"挫折",
|
||||||
|
"失望",
|
||||||
|
"無奈",
|
||||||
|
"痛苦",
|
||||||
|
"壓力",
|
||||||
|
"不滿",
|
||||||
|
"抱怨",
|
||||||
|
"不爽",
|
||||||
|
"生氣",
|
||||||
|
"憤怒",
|
||||||
|
"沮喪",
|
||||||
|
"絕望",
|
||||||
|
"疲憊",
|
||||||
|
"厭倦",
|
||||||
|
]
|
||||||
|
|
||||||
|
// 建設性詞彙建議
|
||||||
|
const constructiveSuggestions = [
|
||||||
|
"建議使用更具體的描述來說明遇到的困難",
|
||||||
|
"可以嘗試描述期望的改善方向",
|
||||||
|
"分享具體的情況會更有助於找到解決方案",
|
||||||
|
"描述問題的影響程度會幫助我們更好地理解",
|
||||||
|
"可以說明這個問題對工作效率的具體影響",
|
||||||
|
]
|
||||||
|
|
||||||
|
export function moderateContent(content: string): ModerationResult {
|
||||||
|
const fullText = content.toLowerCase()
|
||||||
|
const issues: string[] = []
|
||||||
|
const suggestions: string[] = []
|
||||||
|
const blockedWords: string[] = []
|
||||||
|
let severity: "low" | "medium" | "high" = "low"
|
||||||
|
|
||||||
|
// 檢查不雅詞彙
|
||||||
|
inappropriateWords.forEach((word) => {
|
||||||
|
if (fullText.includes(word.toLowerCase())) {
|
||||||
|
blockedWords.push(word)
|
||||||
|
issues.push(`包含不適當詞彙: "${word}"`)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// 檢查負面但可接受的詞彙
|
||||||
|
const negativeWordCount = negativeButAcceptableWords.filter((word) => fullText.includes(word.toLowerCase())).length
|
||||||
|
|
||||||
|
// 判斷嚴重程度
|
||||||
|
if (blockedWords.length > 0) {
|
||||||
|
severity = "high"
|
||||||
|
issues.push("內容包含不雅或辱罵詞彙,無法提交")
|
||||||
|
suggestions.push("請使用更專業和建設性的語言描述遇到的困難")
|
||||||
|
suggestions.push("我們理解工作中的挫折,但希望能以正面的方式表達")
|
||||||
|
} else if (negativeWordCount > 3) {
|
||||||
|
severity = "medium"
|
||||||
|
issues.push("內容情緒較為負面")
|
||||||
|
suggestions.push("建議加入一些具體的改善建議或期望")
|
||||||
|
suggestions.push("描述具體情況會比情緒性詞彙更有幫助")
|
||||||
|
} else if (negativeWordCount > 1) {
|
||||||
|
severity = "low"
|
||||||
|
suggestions.push("可以嘗試更具體地描述遇到的挑戰")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 內容長度檢查
|
||||||
|
if (content.trim().length < 10) {
|
||||||
|
issues.push("內容過於簡短,請提供更詳細的描述")
|
||||||
|
severity = severity === "low" ? "medium" : severity
|
||||||
|
}
|
||||||
|
|
||||||
|
// 重複字符檢查(可能是情緒性表達)
|
||||||
|
const repeatedChars = content.match(/(.)\1{4,}/g)
|
||||||
|
if (repeatedChars) {
|
||||||
|
issues.push("請避免使用過多重複字符")
|
||||||
|
suggestions.push("建議使用清楚的文字描述來表達感受")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 全大寫檢查(可能是憤怒表達)
|
||||||
|
const upperCaseRatio = (content.match(/[A-Z]/g) || []).length / content.length
|
||||||
|
if (upperCaseRatio > 0.5 && content.length > 20) {
|
||||||
|
issues.push("請避免使用過多大寫字母")
|
||||||
|
suggestions.push("正常的大小寫會讓內容更容易閱讀")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果沒有具體建議,添加通用建議
|
||||||
|
if (suggestions.length === 0 && severity !== "high") {
|
||||||
|
suggestions.push(...constructiveSuggestions.slice(0, 2))
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
isAppropriate: blockedWords.length === 0,
|
||||||
|
issues,
|
||||||
|
suggestions,
|
||||||
|
severity,
|
||||||
|
blockedWords,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 檢查整個表單內容
|
||||||
|
export function moderateWishForm(formData: {
|
||||||
|
title: string
|
||||||
|
currentPain: string
|
||||||
|
expectedSolution: string
|
||||||
|
expectedEffect: string
|
||||||
|
}): ModerationResult {
|
||||||
|
const allContent = `${formData.title} ${formData.currentPain} ${formData.expectedSolution} ${formData.expectedEffect}`
|
||||||
|
|
||||||
|
const result = moderateContent(allContent)
|
||||||
|
|
||||||
|
// 針對不同欄位給出具體建議
|
||||||
|
const fieldSpecificSuggestions: string[] = []
|
||||||
|
|
||||||
|
if (formData.title.length < 5) {
|
||||||
|
fieldSpecificSuggestions.push('標題建議更具體一些,例如:"資料整理效率低下" 而非 "很煩"')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (formData.currentPain.length < 20) {
|
||||||
|
fieldSpecificSuggestions.push("困擾描述可以更詳細,包括具體情況和影響")
|
||||||
|
}
|
||||||
|
|
||||||
|
if (formData.expectedSolution.length < 15) {
|
||||||
|
fieldSpecificSuggestions.push("期望解決方式可以更具體,這有助於我們提供更好的建議")
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...result,
|
||||||
|
suggestions: [...result.suggestions, ...fieldSpecificSuggestions],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提供正面的表達建議
|
||||||
|
export function getSuggestedPhrases(originalText: string): string[] {
|
||||||
|
const suggestions: string[] = []
|
||||||
|
|
||||||
|
// 根據內容提供建議
|
||||||
|
if (originalText.includes("很煩") || originalText.includes("討厭")) {
|
||||||
|
suggestions.push('可以說:"這個流程讓我感到困擾,希望能夠簡化"')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (originalText.includes("爛") || originalText.includes("垃圾")) {
|
||||||
|
suggestions.push('可以說:"這個系統存在一些問題,影響了工作效率"')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (originalText.includes("老闆") && (originalText.includes("討厌") || originalText.includes("爛"))) {
|
||||||
|
suggestions.push('可以說:"希望能與主管有更好的溝通和協作"')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (originalText.includes("同事")) {
|
||||||
|
suggestions.push('可以說:"團隊協作方面遇到一些挑戰"')
|
||||||
|
}
|
||||||
|
|
||||||
|
return suggestions
|
||||||
|
}
|
60
lib/email-validation.ts
Normal file
60
lib/email-validation.ts
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
// Email 驗證工具
|
||||||
|
export function isValidEmail(email: string): boolean {
|
||||||
|
if (!email) return true // 空值是允許的(可選欄位)
|
||||||
|
|
||||||
|
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||||
|
return emailRegex.test(email)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sanitizeEmail(email: string): string {
|
||||||
|
return email.trim().toLowerCase()
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getEmailDomain(email: string): string {
|
||||||
|
const parts = email.split("@")
|
||||||
|
return parts.length > 1 ? parts[1] : ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// 檢查是否為常見的臨時郵箱服務
|
||||||
|
const temporaryEmailDomains = [
|
||||||
|
"10minutemail.com",
|
||||||
|
"guerrillamail.com",
|
||||||
|
"mailinator.com",
|
||||||
|
"tempmail.org",
|
||||||
|
"throwaway.email",
|
||||||
|
]
|
||||||
|
|
||||||
|
export function isTemporaryEmail(email: string): boolean {
|
||||||
|
if (!email) return false
|
||||||
|
|
||||||
|
const domain = getEmailDomain(email)
|
||||||
|
return temporaryEmailDomains.includes(domain)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateEmailForSubmission(email: string): {
|
||||||
|
isValid: boolean
|
||||||
|
message?: string
|
||||||
|
suggestion?: string
|
||||||
|
} {
|
||||||
|
if (!email) {
|
||||||
|
return { isValid: true } // 空值允許
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isValidEmail(email)) {
|
||||||
|
return {
|
||||||
|
isValid: false,
|
||||||
|
message: "請輸入有效的 Email 格式",
|
||||||
|
suggestion: "例如:your.name@company.com",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isTemporaryEmail(email)) {
|
||||||
|
return {
|
||||||
|
isValid: false,
|
||||||
|
message: "請避免使用臨時郵箱服務",
|
||||||
|
suggestion: "建議使用常用的 Email 地址,以便我們能夠聯繫到你",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { isValid: true }
|
||||||
|
}
|
190
lib/image-utils.ts
Normal file
190
lib/image-utils.ts
Normal file
@@ -0,0 +1,190 @@
|
|||||||
|
// 圖片處理工具
|
||||||
|
export interface ImageFile {
|
||||||
|
id: string
|
||||||
|
file?: File // 可選,因為從 localStorage 恢復時不會有原始 File
|
||||||
|
url: string // 改為 base64 URL
|
||||||
|
name: string
|
||||||
|
size: number
|
||||||
|
type: string
|
||||||
|
base64?: string // 新增 base64 字段
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImageValidationResult {
|
||||||
|
isValid: boolean
|
||||||
|
error?: string
|
||||||
|
suggestion?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// 允許的圖片格式
|
||||||
|
export const ALLOWED_IMAGE_TYPES = ["image/jpeg", "image/jpg", "image/png", "image/webp", "image/gif"]
|
||||||
|
|
||||||
|
// 允許的檔案副檔名
|
||||||
|
export const ALLOWED_EXTENSIONS = [".jpg", ".jpeg", ".png", ".webp", ".gif"]
|
||||||
|
|
||||||
|
// 檔案大小限制 (5MB)
|
||||||
|
export const MAX_FILE_SIZE = 5 * 1024 * 1024
|
||||||
|
|
||||||
|
// 單次上傳數量限制
|
||||||
|
export const MAX_FILES_PER_UPLOAD = 10
|
||||||
|
|
||||||
|
// 總檔案數量限制
|
||||||
|
export const MAX_TOTAL_FILES = 20
|
||||||
|
|
||||||
|
export function validateImageFile(file: File): ImageValidationResult {
|
||||||
|
// 檢查檔案類型
|
||||||
|
if (!ALLOWED_IMAGE_TYPES.includes(file.type)) {
|
||||||
|
return {
|
||||||
|
isValid: false,
|
||||||
|
error: `不支援的檔案格式: ${file.type}`,
|
||||||
|
suggestion: `請使用 JPG、PNG、WebP 或 GIF 格式`,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 檢查檔案大小
|
||||||
|
if (file.size > MAX_FILE_SIZE) {
|
||||||
|
const sizeMB = (file.size / (1024 * 1024)).toFixed(1)
|
||||||
|
return {
|
||||||
|
isValid: false,
|
||||||
|
error: `檔案過大: ${sizeMB}MB`,
|
||||||
|
suggestion: `請壓縮圖片至 5MB 以下`,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 檢查檔案名稱
|
||||||
|
if (file.name.length > 100) {
|
||||||
|
return {
|
||||||
|
isValid: false,
|
||||||
|
error: "檔案名稱過長",
|
||||||
|
suggestion: "請使用較短的檔案名稱",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { isValid: true }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatFileSize(bytes: number): string {
|
||||||
|
if (bytes === 0) return "0 Bytes"
|
||||||
|
|
||||||
|
const k = 1024
|
||||||
|
const sizes = ["Bytes", "KB", "MB", "GB"]
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||||
|
|
||||||
|
return Number.parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
// 將 File 轉換為 base64
|
||||||
|
export function fileToBase64(file: File): Promise<string> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const reader = new FileReader()
|
||||||
|
reader.onload = () => {
|
||||||
|
if (typeof reader.result === "string") {
|
||||||
|
resolve(reader.result)
|
||||||
|
} else {
|
||||||
|
reject(new Error("Failed to convert file to base64"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
reader.onerror = () => reject(reader.error)
|
||||||
|
reader.readAsDataURL(file)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 創建圖片文件對象(使用 base64)
|
||||||
|
export async function createImageFile(file: File): Promise<ImageFile> {
|
||||||
|
const base64 = await fileToBase64(file)
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: `img_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
|
||||||
|
file,
|
||||||
|
url: base64, // 直接使用 base64 作為 URL
|
||||||
|
name: file.name,
|
||||||
|
size: file.size,
|
||||||
|
type: file.type,
|
||||||
|
base64,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 從儲存的數據恢復圖片對象
|
||||||
|
export function restoreImageFile(data: any): ImageFile {
|
||||||
|
return {
|
||||||
|
id: data.id,
|
||||||
|
url: data.base64 || data.url, // 優先使用 base64,向後兼容
|
||||||
|
name: data.name,
|
||||||
|
size: data.size,
|
||||||
|
type: data.type,
|
||||||
|
base64: data.base64,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 不再需要 revokeImageUrl,因為使用 base64
|
||||||
|
export function revokeImageUrl(imageFile: ImageFile): void {
|
||||||
|
// base64 不需要手動釋放
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 壓縮圖片並轉為 base64
|
||||||
|
export function compressImage(file: File, maxWidth = 1920, quality = 0.8): Promise<File> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const canvas = document.createElement("canvas")
|
||||||
|
const ctx = canvas.getContext("2d")
|
||||||
|
const img = new Image()
|
||||||
|
|
||||||
|
img.onload = () => {
|
||||||
|
// 計算新尺寸
|
||||||
|
let { width, height } = img
|
||||||
|
|
||||||
|
if (width > maxWidth) {
|
||||||
|
height = (height * maxWidth) / width
|
||||||
|
width = maxWidth
|
||||||
|
}
|
||||||
|
|
||||||
|
canvas.width = width
|
||||||
|
canvas.height = height
|
||||||
|
|
||||||
|
// 繪製壓縮後的圖片
|
||||||
|
ctx?.drawImage(img, 0, 0, width, height)
|
||||||
|
|
||||||
|
canvas.toBlob(
|
||||||
|
(blob) => {
|
||||||
|
if (blob) {
|
||||||
|
const compressedFile = new File([blob], file.name, {
|
||||||
|
type: file.type,
|
||||||
|
lastModified: Date.now(),
|
||||||
|
})
|
||||||
|
resolve(compressedFile)
|
||||||
|
} else {
|
||||||
|
resolve(file) // 如果壓縮失敗,返回原檔案
|
||||||
|
}
|
||||||
|
},
|
||||||
|
file.type,
|
||||||
|
quality,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
img.src = URL.createObjectURL(file)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成縮圖
|
||||||
|
export function generateThumbnail(file: File, size = 200): Promise<string> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const canvas = document.createElement("canvas")
|
||||||
|
const ctx = canvas.getContext("2d")
|
||||||
|
const img = new Image()
|
||||||
|
|
||||||
|
img.onload = () => {
|
||||||
|
canvas.width = size
|
||||||
|
canvas.height = size
|
||||||
|
|
||||||
|
// 計算裁切區域 (正方形縮圖)
|
||||||
|
const minDimension = Math.min(img.width, img.height)
|
||||||
|
const x = (img.width - minDimension) / 2
|
||||||
|
const y = (img.height - minDimension) / 2
|
||||||
|
|
||||||
|
ctx?.drawImage(img, x, y, minDimension, minDimension, 0, 0, size, size)
|
||||||
|
|
||||||
|
resolve(canvas.toDataURL(file.type, 0.7))
|
||||||
|
}
|
||||||
|
|
||||||
|
img.src = URL.createObjectURL(file)
|
||||||
|
})
|
||||||
|
}
|
330
lib/supabase-image-utils.ts
Normal file
330
lib/supabase-image-utils.ts
Normal file
@@ -0,0 +1,330 @@
|
|||||||
|
import { supabase } from "./supabase"
|
||||||
|
|
||||||
|
// Supabase 圖片相關的類型定義
|
||||||
|
export interface SupabaseImageFile {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
size: number
|
||||||
|
type: string
|
||||||
|
storage_path: string // Supabase Storage 中的路徑
|
||||||
|
public_url: string // 公開訪問 URL
|
||||||
|
uploaded_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImageUploadResult {
|
||||||
|
success: boolean
|
||||||
|
data?: SupabaseImageFile
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BatchUploadResult {
|
||||||
|
successful: SupabaseImageFile[]
|
||||||
|
failed: Array<{ file: File; error: string }>
|
||||||
|
total: number
|
||||||
|
}
|
||||||
|
|
||||||
|
// 圖片上傳服務
|
||||||
|
export class SupabaseImageService {
|
||||||
|
private static readonly BUCKET_NAME = "wish-images"
|
||||||
|
private static readonly MAX_FILE_SIZE = 5 * 1024 * 1024 // 5MB
|
||||||
|
private static readonly ALLOWED_TYPES = ["image/jpeg", "image/jpg", "image/png", "image/webp", "image/gif"]
|
||||||
|
|
||||||
|
// 驗證圖片文件
|
||||||
|
static validateImageFile(file: File): { isValid: boolean; error?: string } {
|
||||||
|
if (!this.ALLOWED_TYPES.includes(file.type)) {
|
||||||
|
return {
|
||||||
|
isValid: false,
|
||||||
|
error: `不支援的檔案格式: ${file.type}。請使用 JPG、PNG、WebP 或 GIF 格式。`,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (file.size > this.MAX_FILE_SIZE) {
|
||||||
|
const sizeMB = (file.size / (1024 * 1024)).toFixed(1)
|
||||||
|
return {
|
||||||
|
isValid: false,
|
||||||
|
error: `檔案過大: ${sizeMB}MB。請壓縮圖片至 5MB 以下。`,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { isValid: true }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成唯一的檔案路徑
|
||||||
|
static generateFilePath(file: File): string {
|
||||||
|
const timestamp = Date.now()
|
||||||
|
const randomId = Math.random().toString(36).substring(2, 15)
|
||||||
|
const extension = file.name.split(".").pop()?.toLowerCase() || "jpg"
|
||||||
|
return `${timestamp}_${randomId}.${extension}`
|
||||||
|
}
|
||||||
|
|
||||||
|
// 上傳單個圖片到 Supabase Storage
|
||||||
|
static async uploadImage(file: File): Promise<ImageUploadResult> {
|
||||||
|
try {
|
||||||
|
// 驗證檔案
|
||||||
|
const validation = this.validateImageFile(file)
|
||||||
|
if (!validation.isValid) {
|
||||||
|
return { success: false, error: validation.error }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成檔案路徑
|
||||||
|
const filePath = this.generateFilePath(file)
|
||||||
|
|
||||||
|
// 上傳到 Supabase Storage
|
||||||
|
const { data: uploadData, error: uploadError } = await supabase.storage
|
||||||
|
.from(this.BUCKET_NAME)
|
||||||
|
.upload(filePath, file, {
|
||||||
|
cacheControl: "3600",
|
||||||
|
upsert: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
if (uploadError) {
|
||||||
|
console.error("Upload error:", uploadError)
|
||||||
|
return { success: false, error: `上傳失敗: ${uploadError.message}` }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 獲取公開 URL
|
||||||
|
const { data: urlData } = supabase.storage.from(this.BUCKET_NAME).getPublicUrl(filePath)
|
||||||
|
|
||||||
|
if (!urlData.publicUrl) {
|
||||||
|
return { success: false, error: "無法獲取圖片 URL" }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 創建圖片記錄
|
||||||
|
const imageFile: SupabaseImageFile = {
|
||||||
|
id: `img_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
|
||||||
|
name: file.name,
|
||||||
|
size: file.size,
|
||||||
|
type: file.type,
|
||||||
|
storage_path: filePath,
|
||||||
|
public_url: urlData.publicUrl,
|
||||||
|
uploaded_at: new Date().toISOString(),
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true, data: imageFile }
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Image upload error:", error)
|
||||||
|
return { success: false, error: `上傳過程中發生錯誤: ${error}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 批量上傳圖片
|
||||||
|
static async uploadImages(files: File[]): Promise<BatchUploadResult> {
|
||||||
|
const result: BatchUploadResult = {
|
||||||
|
successful: [],
|
||||||
|
failed: [],
|
||||||
|
total: files.length,
|
||||||
|
}
|
||||||
|
|
||||||
|
// 並行上傳所有圖片
|
||||||
|
const uploadPromises = files.map(async (file) => {
|
||||||
|
const uploadResult = await this.uploadImage(file)
|
||||||
|
if (uploadResult.success && uploadResult.data) {
|
||||||
|
result.successful.push(uploadResult.data)
|
||||||
|
} else {
|
||||||
|
result.failed.push({
|
||||||
|
file,
|
||||||
|
error: uploadResult.error || "未知錯誤",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
await Promise.all(uploadPromises)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// 刪除圖片
|
||||||
|
static async deleteImage(storagePath: string): Promise<{ success: boolean; error?: string }> {
|
||||||
|
try {
|
||||||
|
const { error } = await supabase.storage.from(this.BUCKET_NAME).remove([storagePath])
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error("Delete error:", error)
|
||||||
|
return { success: false, error: `刪除失敗: ${error.message}` }
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true }
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Image delete error:", error)
|
||||||
|
return { success: false, error: `刪除過程中發生錯誤: ${error}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 批量刪除圖片
|
||||||
|
static async deleteImages(storagePaths: string[]): Promise<{ success: boolean; error?: string }> {
|
||||||
|
try {
|
||||||
|
const { error } = await supabase.storage.from(this.BUCKET_NAME).remove(storagePaths)
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error("Batch delete error:", error)
|
||||||
|
return { success: false, error: `批量刪除失敗: ${error.message}` }
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true }
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Batch delete error:", error)
|
||||||
|
return { success: false, error: `批量刪除過程中發生錯誤: ${error}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 獲取圖片的公開 URL
|
||||||
|
static getPublicUrl(storagePath: string): string {
|
||||||
|
const { data } = supabase.storage.from(this.BUCKET_NAME).getPublicUrl(storagePath)
|
||||||
|
return data.publicUrl
|
||||||
|
}
|
||||||
|
|
||||||
|
// 檢查存儲桶是否存在並可訪問
|
||||||
|
static async checkStorageHealth(): Promise<{ healthy: boolean; error?: string }> {
|
||||||
|
try {
|
||||||
|
const { data, error } = await supabase.storage.from(this.BUCKET_NAME).list("", { limit: 1 })
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return { healthy: false, error: `存儲檢查失敗: ${error.message}` }
|
||||||
|
}
|
||||||
|
|
||||||
|
return { healthy: true }
|
||||||
|
} catch (error) {
|
||||||
|
return { healthy: false, error: `存儲檢查過程中發生錯誤: ${error}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 獲取存儲使用統計
|
||||||
|
static async getStorageStats(): Promise<{
|
||||||
|
totalFiles: number
|
||||||
|
totalSize: number
|
||||||
|
error?: string
|
||||||
|
}> {
|
||||||
|
try {
|
||||||
|
const { data, error } = await supabase.storage.from(this.BUCKET_NAME).list("", { limit: 1000 })
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return { totalFiles: 0, totalSize: 0, error: error.message }
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalFiles = data?.length || 0
|
||||||
|
const totalSize = data?.reduce((sum, file) => sum + (file.metadata?.size || 0), 0) || 0
|
||||||
|
|
||||||
|
return { totalFiles, totalSize }
|
||||||
|
} catch (error) {
|
||||||
|
return { totalFiles: 0, totalSize: 0, error: `獲取統計失敗: ${error}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 圖片壓縮工具(在上傳前使用)
|
||||||
|
export class ImageCompressionService {
|
||||||
|
// 壓縮圖片
|
||||||
|
static async compressImage(file: File, maxWidth = 1920, quality = 0.8): Promise<File> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const canvas = document.createElement("canvas")
|
||||||
|
const ctx = canvas.getContext("2d")
|
||||||
|
const img = new Image()
|
||||||
|
|
||||||
|
img.onload = () => {
|
||||||
|
// 計算新尺寸
|
||||||
|
let { width, height } = img
|
||||||
|
|
||||||
|
if (width > maxWidth) {
|
||||||
|
height = (height * maxWidth) / width
|
||||||
|
width = maxWidth
|
||||||
|
}
|
||||||
|
|
||||||
|
canvas.width = width
|
||||||
|
canvas.height = height
|
||||||
|
|
||||||
|
// 繪製壓縮後的圖片
|
||||||
|
ctx?.drawImage(img, 0, 0, width, height)
|
||||||
|
|
||||||
|
canvas.toBlob(
|
||||||
|
(blob) => {
|
||||||
|
if (blob) {
|
||||||
|
const compressedFile = new File([blob], file.name, {
|
||||||
|
type: file.type,
|
||||||
|
lastModified: Date.now(),
|
||||||
|
})
|
||||||
|
resolve(compressedFile)
|
||||||
|
} else {
|
||||||
|
resolve(file) // 如果壓縮失敗,返回原檔案
|
||||||
|
}
|
||||||
|
},
|
||||||
|
file.type,
|
||||||
|
quality,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
img.onerror = () => resolve(file) // 如果載入失敗,返回原檔案
|
||||||
|
img.src = URL.createObjectURL(file)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 批量壓縮圖片
|
||||||
|
static async compressImages(files: File[]): Promise<File[]> {
|
||||||
|
const compressionPromises = files.map((file) => {
|
||||||
|
// 如果檔案小於 1MB,不需要壓縮
|
||||||
|
if (file.size < 1024 * 1024) {
|
||||||
|
return Promise.resolve(file)
|
||||||
|
}
|
||||||
|
return this.compressImage(file, 1920, 0.8)
|
||||||
|
})
|
||||||
|
|
||||||
|
return Promise.all(compressionPromises)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 從舊的 base64 格式遷移到 Supabase Storage
|
||||||
|
export class ImageMigrationService {
|
||||||
|
// 將 base64 圖片遷移到 Supabase Storage
|
||||||
|
static async migrateBase64ToStorage(base64Data: string, fileName: string): Promise<ImageUploadResult> {
|
||||||
|
try {
|
||||||
|
// 將 base64 轉換為 Blob
|
||||||
|
const response = await fetch(base64Data)
|
||||||
|
const blob = await response.blob()
|
||||||
|
|
||||||
|
// 創建 File 對象
|
||||||
|
const file = new File([blob], fileName, { type: blob.type })
|
||||||
|
|
||||||
|
// 上傳到 Supabase Storage
|
||||||
|
return await SupabaseImageService.uploadImage(file)
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Base64 migration error:", error)
|
||||||
|
return { success: false, error: `遷移失敗: ${error}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 批量遷移圖片
|
||||||
|
static async migrateImagesFromWish(wishImages: any[]): Promise<{
|
||||||
|
successful: SupabaseImageFile[]
|
||||||
|
failed: Array<{ originalImage: any; error: string }>
|
||||||
|
}> {
|
||||||
|
const result = {
|
||||||
|
successful: [] as SupabaseImageFile[],
|
||||||
|
failed: [] as Array<{ originalImage: any; error: string }>,
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const image of wishImages) {
|
||||||
|
try {
|
||||||
|
if (image.base64) {
|
||||||
|
// 遷移 base64 圖片
|
||||||
|
const migrationResult = await this.migrateBase64ToStorage(image.base64, image.name)
|
||||||
|
if (migrationResult.success && migrationResult.data) {
|
||||||
|
result.successful.push(migrationResult.data)
|
||||||
|
} else {
|
||||||
|
result.failed.push({
|
||||||
|
originalImage: image,
|
||||||
|
error: migrationResult.error || "遷移失敗",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} else if (image.storage_path) {
|
||||||
|
// 已經是 Supabase Storage 格式,直接保留
|
||||||
|
result.successful.push(image as SupabaseImageFile)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
result.failed.push({
|
||||||
|
originalImage: image,
|
||||||
|
error: `處理失敗: ${error}`,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
}
|
299
lib/supabase-service-updated.ts
Normal file
299
lib/supabase-service-updated.ts
Normal file
@@ -0,0 +1,299 @@
|
|||||||
|
import { supabase, type Database } from "./supabase"
|
||||||
|
import { SupabaseImageService, ImageMigrationService, type SupabaseImageFile } from "./supabase-image-utils"
|
||||||
|
|
||||||
|
// 更新的 Wish 類型定義
|
||||||
|
export type Wish = Database["public"]["Tables"]["wishes"]["Row"] & {
|
||||||
|
like_count?: number
|
||||||
|
images?: SupabaseImageFile[] // 使用新的圖片類型
|
||||||
|
}
|
||||||
|
|
||||||
|
export type WishInsert = Database["public"]["Tables"]["wishes"]["Insert"]
|
||||||
|
export type WishLike = Database["public"]["Tables"]["wish_likes"]["Row"]
|
||||||
|
export type UserSettings = Database["public"]["Tables"]["user_settings"]["Row"]
|
||||||
|
|
||||||
|
// 錯誤處理
|
||||||
|
export class SupabaseError extends Error {
|
||||||
|
constructor(
|
||||||
|
message: string,
|
||||||
|
public originalError?: any,
|
||||||
|
) {
|
||||||
|
super(message)
|
||||||
|
this.name = "SupabaseError"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新的困擾案例服務
|
||||||
|
export class WishService {
|
||||||
|
// 獲取所有公開的困擾案例(帶點讚數和圖片)
|
||||||
|
static async getPublicWishes(): Promise<Wish[]> {
|
||||||
|
try {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from("wishes_with_likes")
|
||||||
|
.select("*")
|
||||||
|
.eq("is_public", true)
|
||||||
|
.order("created_at", { ascending: false })
|
||||||
|
|
||||||
|
if (error) throw new SupabaseError("獲取公開困擾失敗", error)
|
||||||
|
|
||||||
|
// 轉換圖片格式
|
||||||
|
return (data || []).map((wish) => ({
|
||||||
|
...wish,
|
||||||
|
images: this.parseImages(wish.images),
|
||||||
|
}))
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching public wishes:", error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 獲取所有困擾案例(用於分析,包含私密的)
|
||||||
|
static async getAllWishes(): Promise<Wish[]> {
|
||||||
|
try {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from("wishes_with_likes")
|
||||||
|
.select("*")
|
||||||
|
.order("created_at", { ascending: false })
|
||||||
|
|
||||||
|
if (error) throw new SupabaseError("獲取所有困擾失敗", error)
|
||||||
|
|
||||||
|
// 轉換圖片格式
|
||||||
|
return (data || []).map((wish) => ({
|
||||||
|
...wish,
|
||||||
|
images: this.parseImages(wish.images),
|
||||||
|
}))
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching all wishes:", error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 創建新的困擾案例(支持 Supabase Storage 圖片)
|
||||||
|
static async createWish(wishData: {
|
||||||
|
title: string
|
||||||
|
currentPain: string
|
||||||
|
expectedSolution: string
|
||||||
|
expectedEffect?: string
|
||||||
|
isPublic?: boolean
|
||||||
|
email?: string
|
||||||
|
images?: SupabaseImageFile[]
|
||||||
|
}): Promise<Wish> {
|
||||||
|
try {
|
||||||
|
// 準備圖片數據
|
||||||
|
const imageData =
|
||||||
|
wishData.images?.map((img) => ({
|
||||||
|
id: img.id,
|
||||||
|
name: img.name,
|
||||||
|
size: img.size,
|
||||||
|
type: img.type,
|
||||||
|
storage_path: img.storage_path,
|
||||||
|
public_url: img.public_url,
|
||||||
|
uploaded_at: img.uploaded_at,
|
||||||
|
})) || []
|
||||||
|
|
||||||
|
const insertData: WishInsert = {
|
||||||
|
title: wishData.title,
|
||||||
|
current_pain: wishData.currentPain,
|
||||||
|
expected_solution: wishData.expectedSolution,
|
||||||
|
expected_effect: wishData.expectedEffect || null,
|
||||||
|
is_public: wishData.isPublic ?? true,
|
||||||
|
email: wishData.email || null,
|
||||||
|
images: imageData,
|
||||||
|
}
|
||||||
|
|
||||||
|
const { data, error } = await supabase.from("wishes").insert(insertData).select().single()
|
||||||
|
|
||||||
|
if (error) throw new SupabaseError("創建困擾失敗", error)
|
||||||
|
|
||||||
|
return {
|
||||||
|
...data,
|
||||||
|
images: this.parseImages(data.images),
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error creating wish:", error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 解析圖片數據
|
||||||
|
private static parseImages(imagesData: any): SupabaseImageFile[] {
|
||||||
|
if (!imagesData || !Array.isArray(imagesData)) return []
|
||||||
|
|
||||||
|
return imagesData.map((img) => ({
|
||||||
|
id: img.id || `img_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
|
||||||
|
name: img.name || "unknown.jpg",
|
||||||
|
size: img.size || 0,
|
||||||
|
type: img.type || "image/jpeg",
|
||||||
|
storage_path: img.storage_path || "",
|
||||||
|
public_url: img.public_url || img.url || "", // 向後兼容
|
||||||
|
uploaded_at: img.uploaded_at || new Date().toISOString(),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 獲取統計數據
|
||||||
|
static async getWishesStats() {
|
||||||
|
try {
|
||||||
|
const { data, error } = await supabase.rpc("get_wishes_stats")
|
||||||
|
|
||||||
|
if (error) throw new SupabaseError("獲取統計數據失敗", error)
|
||||||
|
return data
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching wishes stats:", error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 刪除困擾案例(包括相關圖片)
|
||||||
|
static async deleteWish(wishId: number): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
// 先獲取困擾案例的圖片信息
|
||||||
|
const { data: wish, error: fetchError } = await supabase.from("wishes").select("images").eq("id", wishId).single()
|
||||||
|
|
||||||
|
if (fetchError) throw new SupabaseError("獲取困擾案例失敗", fetchError)
|
||||||
|
|
||||||
|
// 刪除相關圖片
|
||||||
|
if (wish.images && Array.isArray(wish.images)) {
|
||||||
|
const storagePaths = wish.images.map((img: any) => img.storage_path).filter((path: string) => path)
|
||||||
|
|
||||||
|
if (storagePaths.length > 0) {
|
||||||
|
await SupabaseImageService.deleteImages(storagePaths)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 刪除困擾案例記錄
|
||||||
|
const { error: deleteError } = await supabase.from("wishes").delete().eq("id", wishId)
|
||||||
|
|
||||||
|
if (deleteError) throw new SupabaseError("刪除困擾案例失敗", deleteError)
|
||||||
|
|
||||||
|
return true
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error deleting wish:", error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新的數據遷移服務
|
||||||
|
export class MigrationService {
|
||||||
|
// 遷移 localStorage 中的困擾案例到 Supabase(包括圖片遷移)
|
||||||
|
static async migrateWishesFromLocalStorage(): Promise<{
|
||||||
|
success: number
|
||||||
|
failed: number
|
||||||
|
errors: string[]
|
||||||
|
}> {
|
||||||
|
const result = {
|
||||||
|
success: 0,
|
||||||
|
failed: 0,
|
||||||
|
errors: [] as string[],
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const localWishes = JSON.parse(localStorage.getItem("wishes") || "[]")
|
||||||
|
|
||||||
|
if (localWishes.length === 0) {
|
||||||
|
console.log("No local wishes to migrate")
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`Starting migration of ${localWishes.length} wishes...`)
|
||||||
|
|
||||||
|
for (const wish of localWishes) {
|
||||||
|
try {
|
||||||
|
let migratedImages: SupabaseImageFile[] = []
|
||||||
|
|
||||||
|
// 遷移圖片(如果有的話)
|
||||||
|
if (wish.images && Array.isArray(wish.images) && wish.images.length > 0) {
|
||||||
|
console.log(`Migrating ${wish.images.length} images for wish: ${wish.title}`)
|
||||||
|
|
||||||
|
const imageMigrationResult = await ImageMigrationService.migrateImagesFromWish(wish.images)
|
||||||
|
|
||||||
|
migratedImages = imageMigrationResult.successful
|
||||||
|
|
||||||
|
if (imageMigrationResult.failed.length > 0) {
|
||||||
|
console.warn(`Failed to migrate ${imageMigrationResult.failed.length} images for wish: ${wish.title}`)
|
||||||
|
// 記錄圖片遷移失敗,但不阻止整個 wish 的遷移
|
||||||
|
result.errors.push(`部分圖片遷移失敗 "${wish.title}": ${imageMigrationResult.failed.length} 張圖片`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 創建困擾案例
|
||||||
|
await WishService.createWish({
|
||||||
|
title: wish.title,
|
||||||
|
currentPain: wish.currentPain,
|
||||||
|
expectedSolution: wish.expectedSolution,
|
||||||
|
expectedEffect: wish.expectedEffect,
|
||||||
|
isPublic: wish.isPublic !== false,
|
||||||
|
email: wish.email,
|
||||||
|
images: migratedImages,
|
||||||
|
})
|
||||||
|
|
||||||
|
result.success++
|
||||||
|
console.log(`Successfully migrated wish: ${wish.title}`)
|
||||||
|
} catch (error) {
|
||||||
|
result.failed++
|
||||||
|
result.errors.push(`Failed to migrate wish "${wish.title}": ${error}`)
|
||||||
|
console.error(`Failed to migrate wish "${wish.title}":`, error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`Migration completed: ${result.success} success, ${result.failed} failed`)
|
||||||
|
return result
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Migration error:", error)
|
||||||
|
result.errors.push(`Migration process failed: ${error}`)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 清空 localStorage 中的舊數據
|
||||||
|
static clearLocalStorageData(): void {
|
||||||
|
const keysToRemove = ["wishes", "wishLikes", "userLikedWishes"]
|
||||||
|
keysToRemove.forEach((key) => {
|
||||||
|
localStorage.removeItem(key)
|
||||||
|
})
|
||||||
|
console.log("Local storage data cleared")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 存儲健康檢查服務
|
||||||
|
export class StorageHealthService {
|
||||||
|
// 檢查 Supabase Storage 健康狀態
|
||||||
|
static async checkStorageHealth(): Promise<{
|
||||||
|
healthy: boolean
|
||||||
|
stats?: { totalFiles: number; totalSize: number }
|
||||||
|
error?: string
|
||||||
|
}> {
|
||||||
|
try {
|
||||||
|
const healthCheck = await SupabaseImageService.checkStorageHealth()
|
||||||
|
if (!healthCheck.healthy) {
|
||||||
|
return { healthy: false, error: healthCheck.error }
|
||||||
|
}
|
||||||
|
|
||||||
|
const stats = await SupabaseImageService.getStorageStats()
|
||||||
|
return {
|
||||||
|
healthy: true,
|
||||||
|
stats: {
|
||||||
|
totalFiles: stats.totalFiles,
|
||||||
|
totalSize: stats.totalSize,
|
||||||
|
},
|
||||||
|
error: stats.error,
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
return { healthy: false, error: `健康檢查失敗: ${error}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 清理孤立的圖片
|
||||||
|
static async cleanupOrphanedImages(): Promise<{ cleaned: number; error?: string }> {
|
||||||
|
try {
|
||||||
|
const { data, error } = await supabase.rpc("cleanup_orphaned_images")
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return { cleaned: 0, error: error.message }
|
||||||
|
}
|
||||||
|
|
||||||
|
return { cleaned: data || 0 }
|
||||||
|
} catch (error) {
|
||||||
|
return { cleaned: 0, error: `清理過程失敗: ${error}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
322
lib/supabase-service.ts
Normal file
322
lib/supabase-service.ts
Normal file
@@ -0,0 +1,322 @@
|
|||||||
|
import { supabase, getUserSession, type Database } from "./supabase"
|
||||||
|
import type { ImageFile } from "./image-utils"
|
||||||
|
|
||||||
|
// 類型定義
|
||||||
|
export type Wish = Database["public"]["Tables"]["wishes"]["Row"] & {
|
||||||
|
like_count?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export type WishInsert = Database["public"]["Tables"]["wishes"]["Insert"]
|
||||||
|
export type WishLike = Database["public"]["Tables"]["wish_likes"]["Row"]
|
||||||
|
export type UserSettings = Database["public"]["Tables"]["user_settings"]["Row"]
|
||||||
|
|
||||||
|
// 錯誤處理
|
||||||
|
export class SupabaseError extends Error {
|
||||||
|
constructor(
|
||||||
|
message: string,
|
||||||
|
public originalError?: any,
|
||||||
|
) {
|
||||||
|
super(message)
|
||||||
|
this.name = "SupabaseError"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 困擾案例相關服務
|
||||||
|
export class WishService {
|
||||||
|
// 獲取所有公開的困擾案例(帶點讚數)
|
||||||
|
static async getPublicWishes(): Promise<Wish[]> {
|
||||||
|
try {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from("wishes_with_likes")
|
||||||
|
.select("*")
|
||||||
|
.eq("is_public", true)
|
||||||
|
.order("created_at", { ascending: false })
|
||||||
|
|
||||||
|
if (error) throw new SupabaseError("獲取公開困擾失敗", error)
|
||||||
|
return data || []
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching public wishes:", error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 獲取所有困擾案例(用於分析,包含私密的)
|
||||||
|
static async getAllWishes(): Promise<Wish[]> {
|
||||||
|
try {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from("wishes_with_likes")
|
||||||
|
.select("*")
|
||||||
|
.order("created_at", { ascending: false })
|
||||||
|
|
||||||
|
if (error) throw new SupabaseError("獲取所有困擾失敗", error)
|
||||||
|
return data || []
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching all wishes:", error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 創建新的困擾案例
|
||||||
|
static async createWish(wishData: {
|
||||||
|
title: string
|
||||||
|
currentPain: string
|
||||||
|
expectedSolution: string
|
||||||
|
expectedEffect?: string
|
||||||
|
isPublic?: boolean
|
||||||
|
email?: string
|
||||||
|
images?: ImageFile[]
|
||||||
|
}): Promise<Wish> {
|
||||||
|
try {
|
||||||
|
// 轉換圖片數據格式
|
||||||
|
const imageData =
|
||||||
|
wishData.images?.map((img) => ({
|
||||||
|
id: img.id,
|
||||||
|
name: img.name,
|
||||||
|
size: img.size,
|
||||||
|
type: img.type,
|
||||||
|
base64: img.base64 || img.url,
|
||||||
|
})) || []
|
||||||
|
|
||||||
|
const insertData: WishInsert = {
|
||||||
|
title: wishData.title,
|
||||||
|
current_pain: wishData.currentPain,
|
||||||
|
expected_solution: wishData.expectedSolution,
|
||||||
|
expected_effect: wishData.expectedEffect || null,
|
||||||
|
is_public: wishData.isPublic ?? true,
|
||||||
|
email: wishData.email || null,
|
||||||
|
images: imageData,
|
||||||
|
}
|
||||||
|
|
||||||
|
const { data, error } = await supabase.from("wishes").insert(insertData).select().single()
|
||||||
|
|
||||||
|
if (error) throw new SupabaseError("創建困擾失敗", error)
|
||||||
|
return data
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error creating wish:", error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 獲取統計數據
|
||||||
|
static async getWishesStats() {
|
||||||
|
try {
|
||||||
|
const { data, error } = await supabase.rpc("get_wishes_stats")
|
||||||
|
|
||||||
|
if (error) throw new SupabaseError("獲取統計數據失敗", error)
|
||||||
|
return data
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching wishes stats:", error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 點讚相關服務
|
||||||
|
export class LikeService {
|
||||||
|
// 為困擾案例點讚
|
||||||
|
static async likeWish(wishId: number): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const userSession = getUserSession()
|
||||||
|
|
||||||
|
const { error } = await supabase.from("wish_likes").insert({
|
||||||
|
wish_id: wishId,
|
||||||
|
user_session: userSession,
|
||||||
|
})
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
// 如果是重複點讚錯誤,返回 false
|
||||||
|
if (error.code === "23505") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
throw new SupabaseError("點讚失敗", error)
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error liking wish:", error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 檢查用戶是否已點讚
|
||||||
|
static async hasUserLiked(wishId: number): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const userSession = getUserSession()
|
||||||
|
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from("wish_likes")
|
||||||
|
.select("id")
|
||||||
|
.eq("wish_id", wishId)
|
||||||
|
.eq("user_session", userSession)
|
||||||
|
.single()
|
||||||
|
|
||||||
|
if (error && error.code !== "PGRST116") {
|
||||||
|
throw new SupabaseError("檢查點讚狀態失敗", error)
|
||||||
|
}
|
||||||
|
|
||||||
|
return !!data
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error checking like status:", error)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 獲取困擾案例的點讚數
|
||||||
|
static async getWishLikeCount(wishId: number): Promise<number> {
|
||||||
|
try {
|
||||||
|
const { count, error } = await supabase
|
||||||
|
.from("wish_likes")
|
||||||
|
.select("*", { count: "exact", head: true })
|
||||||
|
.eq("wish_id", wishId)
|
||||||
|
|
||||||
|
if (error) throw new SupabaseError("獲取點讚數失敗", error)
|
||||||
|
return count || 0
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching like count:", error)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 獲取用戶已點讚的困擾 ID 列表
|
||||||
|
static async getUserLikedWishes(): Promise<number[]> {
|
||||||
|
try {
|
||||||
|
const userSession = getUserSession()
|
||||||
|
|
||||||
|
const { data, error } = await supabase.from("wish_likes").select("wish_id").eq("user_session", userSession)
|
||||||
|
|
||||||
|
if (error) throw new SupabaseError("獲取用戶點讚記錄失敗", error)
|
||||||
|
return data?.map((item) => item.wish_id) || []
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching user liked wishes:", error)
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 用戶設定相關服務
|
||||||
|
export class UserSettingsService {
|
||||||
|
// 獲取用戶設定
|
||||||
|
static async getUserSettings(): Promise<UserSettings | null> {
|
||||||
|
try {
|
||||||
|
const userSession = getUserSession()
|
||||||
|
|
||||||
|
const { data, error } = await supabase.from("user_settings").select("*").eq("user_session", userSession).single()
|
||||||
|
|
||||||
|
if (error && error.code !== "PGRST116") {
|
||||||
|
throw new SupabaseError("獲取用戶設定失敗", error)
|
||||||
|
}
|
||||||
|
|
||||||
|
return data
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching user settings:", error)
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新或創建用戶設定
|
||||||
|
static async updateUserSettings(settings: {
|
||||||
|
backgroundMusicEnabled?: boolean
|
||||||
|
backgroundMusicVolume?: number
|
||||||
|
backgroundMusicPlaying?: boolean
|
||||||
|
}): Promise<UserSettings> {
|
||||||
|
try {
|
||||||
|
const userSession = getUserSession()
|
||||||
|
|
||||||
|
// 先嘗試更新
|
||||||
|
const { data: updateData, error: updateError } = await supabase
|
||||||
|
.from("user_settings")
|
||||||
|
.update({
|
||||||
|
background_music_enabled: settings.backgroundMusicEnabled,
|
||||||
|
background_music_volume: settings.backgroundMusicVolume,
|
||||||
|
background_music_playing: settings.backgroundMusicPlaying,
|
||||||
|
})
|
||||||
|
.eq("user_session", userSession)
|
||||||
|
.select()
|
||||||
|
.single()
|
||||||
|
|
||||||
|
if (updateError && updateError.code === "PGRST116") {
|
||||||
|
// 如果記錄不存在,創建新記錄
|
||||||
|
const { data: insertData, error: insertError } = await supabase
|
||||||
|
.from("user_settings")
|
||||||
|
.insert({
|
||||||
|
user_session: userSession,
|
||||||
|
background_music_enabled: settings.backgroundMusicEnabled ?? false,
|
||||||
|
background_music_volume: settings.backgroundMusicVolume ?? 0.3,
|
||||||
|
background_music_playing: settings.backgroundMusicPlaying ?? false,
|
||||||
|
})
|
||||||
|
.select()
|
||||||
|
.single()
|
||||||
|
|
||||||
|
if (insertError) throw new SupabaseError("創建用戶設定失敗", insertError)
|
||||||
|
return insertData
|
||||||
|
}
|
||||||
|
|
||||||
|
if (updateError) throw new SupabaseError("更新用戶設定失敗", updateError)
|
||||||
|
return updateData
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error updating user settings:", error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 數據遷移服務(從 localStorage 遷移到 Supabase)
|
||||||
|
export class MigrationService {
|
||||||
|
// 遷移 localStorage 中的困擾案例到 Supabase
|
||||||
|
static async migrateWishesFromLocalStorage(): Promise<{
|
||||||
|
success: number
|
||||||
|
failed: number
|
||||||
|
errors: string[]
|
||||||
|
}> {
|
||||||
|
const result = {
|
||||||
|
success: 0,
|
||||||
|
failed: 0,
|
||||||
|
errors: [] as string[],
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const localWishes = JSON.parse(localStorage.getItem("wishes") || "[]")
|
||||||
|
|
||||||
|
if (localWishes.length === 0) {
|
||||||
|
console.log("No local wishes to migrate")
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`Starting migration of ${localWishes.length} wishes...`)
|
||||||
|
|
||||||
|
for (const wish of localWishes) {
|
||||||
|
try {
|
||||||
|
await WishService.createWish({
|
||||||
|
title: wish.title,
|
||||||
|
currentPain: wish.currentPain,
|
||||||
|
expectedSolution: wish.expectedSolution,
|
||||||
|
expectedEffect: wish.expectedEffect,
|
||||||
|
isPublic: wish.isPublic !== false, // 默認為 true
|
||||||
|
email: wish.email,
|
||||||
|
images: wish.images || [],
|
||||||
|
})
|
||||||
|
result.success++
|
||||||
|
} catch (error) {
|
||||||
|
result.failed++
|
||||||
|
result.errors.push(`Failed to migrate wish "${wish.title}": ${error}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`Migration completed: ${result.success} success, ${result.failed} failed`)
|
||||||
|
return result
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Migration error:", error)
|
||||||
|
result.errors.push(`Migration process failed: ${error}`)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 清空 localStorage 中的舊數據
|
||||||
|
static clearLocalStorageData(): void {
|
||||||
|
const keysToRemove = ["wishes", "wishLikes", "userLikedWishes"]
|
||||||
|
keysToRemove.forEach((key) => {
|
||||||
|
localStorage.removeItem(key)
|
||||||
|
})
|
||||||
|
console.log("Local storage data cleared")
|
||||||
|
}
|
||||||
|
}
|
152
lib/supabase.ts
Normal file
152
lib/supabase.ts
Normal file
@@ -0,0 +1,152 @@
|
|||||||
|
import { createClient } from "@supabase/supabase-js"
|
||||||
|
|
||||||
|
// Supabase 配置
|
||||||
|
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!
|
||||||
|
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
|
||||||
|
|
||||||
|
// 創建 Supabase 客戶端(單例模式)
|
||||||
|
export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
|
||||||
|
auth: {
|
||||||
|
persistSession: false, // 我們不需要用戶認證
|
||||||
|
},
|
||||||
|
db: {
|
||||||
|
schema: "public",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 數據庫類型定義
|
||||||
|
export interface Database {
|
||||||
|
public: {
|
||||||
|
Tables: {
|
||||||
|
wishes: {
|
||||||
|
Row: {
|
||||||
|
id: number
|
||||||
|
title: string
|
||||||
|
current_pain: string
|
||||||
|
expected_solution: string
|
||||||
|
expected_effect: string | null
|
||||||
|
is_public: boolean
|
||||||
|
email: string | null
|
||||||
|
images: any[] | null
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
}
|
||||||
|
Insert: {
|
||||||
|
title: string
|
||||||
|
current_pain: string
|
||||||
|
expected_solution: string
|
||||||
|
expected_effect?: string | null
|
||||||
|
is_public?: boolean
|
||||||
|
email?: string | null
|
||||||
|
images?: any[] | null
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
title?: string
|
||||||
|
current_pain?: string
|
||||||
|
expected_solution?: string
|
||||||
|
expected_effect?: string | null
|
||||||
|
is_public?: boolean
|
||||||
|
email?: string | null
|
||||||
|
images?: any[] | null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wish_likes: {
|
||||||
|
Row: {
|
||||||
|
id: number
|
||||||
|
wish_id: number
|
||||||
|
user_session: string
|
||||||
|
created_at: string
|
||||||
|
}
|
||||||
|
Insert: {
|
||||||
|
wish_id: number
|
||||||
|
user_session: string
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
wish_id?: number
|
||||||
|
user_session?: string
|
||||||
|
}
|
||||||
|
}
|
||||||
|
user_settings: {
|
||||||
|
Row: {
|
||||||
|
id: number
|
||||||
|
user_session: string
|
||||||
|
background_music_enabled: boolean
|
||||||
|
background_music_volume: number
|
||||||
|
background_music_playing: boolean
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
}
|
||||||
|
Insert: {
|
||||||
|
user_session: string
|
||||||
|
background_music_enabled?: boolean
|
||||||
|
background_music_volume?: number
|
||||||
|
background_music_playing?: boolean
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
background_music_enabled?: boolean
|
||||||
|
background_music_volume?: number
|
||||||
|
background_music_playing?: boolean
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Views: {
|
||||||
|
wishes_with_likes: {
|
||||||
|
Row: {
|
||||||
|
id: number
|
||||||
|
title: string
|
||||||
|
current_pain: string
|
||||||
|
expected_solution: string
|
||||||
|
expected_effect: string | null
|
||||||
|
is_public: boolean
|
||||||
|
email: string | null
|
||||||
|
images: any[] | null
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
like_count: number
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Functions: {
|
||||||
|
get_wishes_stats: {
|
||||||
|
Args: {}
|
||||||
|
Returns: {
|
||||||
|
total_wishes: number
|
||||||
|
public_wishes: number
|
||||||
|
private_wishes: number
|
||||||
|
this_week: number
|
||||||
|
last_week: number
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成用戶會話 ID(用於匿名識別)
|
||||||
|
export function getUserSession(): string {
|
||||||
|
if (typeof window === "undefined") return "server-session"
|
||||||
|
|
||||||
|
let session = localStorage.getItem("user_session")
|
||||||
|
if (!session) {
|
||||||
|
session = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
|
||||||
|
localStorage.setItem("user_session", session)
|
||||||
|
}
|
||||||
|
return session
|
||||||
|
}
|
||||||
|
|
||||||
|
// 測試 Supabase 連接
|
||||||
|
export async function testSupabaseConnection(): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const { data, error } = await supabase.from("wishes").select("count").limit(1)
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error("Supabase connection test failed:", error)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("✅ Supabase connection successful")
|
||||||
|
return true
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Supabase connection test error:", error)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
13
package.json
13
package.json
@@ -37,23 +37,26 @@
|
|||||||
"@radix-ui/react-toggle": "1.1.1",
|
"@radix-ui/react-toggle": "1.1.1",
|
||||||
"@radix-ui/react-toggle-group": "1.1.1",
|
"@radix-ui/react-toggle-group": "1.1.1",
|
||||||
"@radix-ui/react-tooltip": "1.1.6",
|
"@radix-ui/react-tooltip": "1.1.6",
|
||||||
|
"@supabase/supabase-js": "latest",
|
||||||
"autoprefixer": "^10.4.20",
|
"autoprefixer": "^10.4.20",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"cmdk": "1.0.4",
|
"cmdk": "1.0.4",
|
||||||
"date-fns": "4.1.0",
|
"date-fns": "4.1.0",
|
||||||
|
"dotenv": "latest",
|
||||||
"embla-carousel-react": "8.5.1",
|
"embla-carousel-react": "8.5.1",
|
||||||
"input-otp": "1.4.1",
|
"input-otp": "1.4.1",
|
||||||
"lucide-react": "^0.454.0",
|
"lucide-react": "^0.454.0",
|
||||||
"next": "15.2.4",
|
"next": "14.2.16",
|
||||||
"next-themes": "^0.4.4",
|
"next-themes": "^0.4.4",
|
||||||
"react": "^19",
|
"react": "^18",
|
||||||
"react-day-picker": "8.10.1",
|
"react-day-picker": "8.10.1",
|
||||||
"react-dom": "^19",
|
"react-dom": "^18",
|
||||||
"react-hook-form": "^7.54.1",
|
"react-hook-form": "^7.54.1",
|
||||||
"react-resizable-panels": "^2.1.7",
|
"react-resizable-panels": "^2.1.7",
|
||||||
"recharts": "2.15.0",
|
"recharts": "2.15.0",
|
||||||
"shadcn": "latest",
|
"shadcn": "latest",
|
||||||
|
"sharp": "^0.34.3",
|
||||||
"sonner": "^1.7.1",
|
"sonner": "^1.7.1",
|
||||||
"tailwind-merge": "^2.5.5",
|
"tailwind-merge": "^2.5.5",
|
||||||
"tailwindcss-animate": "^1.0.7",
|
"tailwindcss-animate": "^1.0.7",
|
||||||
@@ -62,8 +65,8 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^22",
|
"@types/node": "^22",
|
||||||
"@types/react": "^19",
|
"@types/react": "^18",
|
||||||
"@types/react-dom": "^19",
|
"@types/react-dom": "^18",
|
||||||
"postcss": "^8.5",
|
"postcss": "^8.5",
|
||||||
"tailwindcss": "^3.4.17",
|
"tailwindcss": "^3.4.17",
|
||||||
"typescript": "^5"
|
"typescript": "^5"
|
||||||
|
5657
pnpm-lock.yaml
generated
5657
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
118
scripts/01-create-tables.sql
Normal file
118
scripts/01-create-tables.sql
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
-- 心願星河 - 基礎表格創建
|
||||||
|
-- 執行順序:第 1 步
|
||||||
|
-- 說明:創建應用程式所需的基礎數據表格
|
||||||
|
|
||||||
|
-- 開始事務
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
-- 1. 創建 wishes 表格(困擾案例主表)
|
||||||
|
CREATE TABLE IF NOT EXISTS wishes (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
title TEXT NOT NULL CHECK (length(title) >= 1 AND length(title) <= 200),
|
||||||
|
current_pain TEXT NOT NULL CHECK (length(current_pain) >= 1 AND length(current_pain) <= 2000),
|
||||||
|
expected_solution TEXT NOT NULL CHECK (length(expected_solution) >= 1 AND length(expected_solution) <= 2000),
|
||||||
|
expected_effect TEXT CHECK (length(expected_effect) <= 1000),
|
||||||
|
is_public BOOLEAN DEFAULT true NOT NULL,
|
||||||
|
email TEXT CHECK (email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$'),
|
||||||
|
images JSONB DEFAULT '[]'::jsonb NOT NULL,
|
||||||
|
user_session TEXT NOT NULL DEFAULT gen_random_uuid()::text,
|
||||||
|
status TEXT DEFAULT 'active' CHECK (status IN ('active', 'archived', 'deleted')),
|
||||||
|
category TEXT CHECK (category IN ('工作效率', '人際關係', '技術問題', '職涯發展', '工作環境', '其他')),
|
||||||
|
priority INTEGER DEFAULT 3 CHECK (priority >= 1 AND priority <= 5),
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,
|
||||||
|
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 2. 創建 wish_likes 表格(點讚記錄)
|
||||||
|
CREATE TABLE IF NOT EXISTS wish_likes (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
wish_id BIGINT NOT NULL REFERENCES wishes(id) ON DELETE CASCADE,
|
||||||
|
user_session TEXT NOT NULL,
|
||||||
|
ip_address INET,
|
||||||
|
user_agent TEXT,
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,
|
||||||
|
UNIQUE(wish_id, user_session)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 3. 創建 user_settings 表格(用戶設定)
|
||||||
|
CREATE TABLE IF NOT EXISTS user_settings (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
user_session TEXT UNIQUE NOT NULL,
|
||||||
|
background_music_enabled BOOLEAN DEFAULT false NOT NULL,
|
||||||
|
background_music_volume DECIMAL(3,2) DEFAULT 0.30 CHECK (background_music_volume >= 0 AND background_music_volume <= 1),
|
||||||
|
background_music_playing BOOLEAN DEFAULT false NOT NULL,
|
||||||
|
theme_preference TEXT DEFAULT 'auto' CHECK (theme_preference IN ('light', 'dark', 'auto')),
|
||||||
|
language_preference TEXT DEFAULT 'zh-TW' CHECK (language_preference IN ('zh-TW', 'en-US')),
|
||||||
|
notification_enabled BOOLEAN DEFAULT true NOT NULL,
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,
|
||||||
|
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 4. 創建 migration_log 表格(遷移記錄)
|
||||||
|
CREATE TABLE IF NOT EXISTS migration_log (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
user_session TEXT NOT NULL,
|
||||||
|
migration_type TEXT NOT NULL CHECK (migration_type IN ('wishes', 'likes', 'settings')),
|
||||||
|
source_data JSONB,
|
||||||
|
target_records INTEGER DEFAULT 0,
|
||||||
|
success BOOLEAN DEFAULT false NOT NULL,
|
||||||
|
error_message TEXT,
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 5. 創建 system_stats 表格(系統統計)
|
||||||
|
CREATE TABLE IF NOT EXISTS system_stats (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
stat_date DATE DEFAULT CURRENT_DATE NOT NULL,
|
||||||
|
total_wishes INTEGER DEFAULT 0,
|
||||||
|
public_wishes INTEGER DEFAULT 0,
|
||||||
|
private_wishes INTEGER DEFAULT 0,
|
||||||
|
total_likes INTEGER DEFAULT 0,
|
||||||
|
active_users INTEGER DEFAULT 0,
|
||||||
|
storage_used_mb DECIMAL(10,2) DEFAULT 0,
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,
|
||||||
|
UNIQUE(stat_date)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 提交事務
|
||||||
|
COMMIT;
|
||||||
|
|
||||||
|
-- 添加表格註釋
|
||||||
|
COMMENT ON TABLE wishes IS '用戶提交的工作困擾案例主表';
|
||||||
|
COMMENT ON TABLE wish_likes IS '困擾案例的點讚記錄表';
|
||||||
|
COMMENT ON TABLE user_settings IS '用戶個人設定表(音樂、主題等)';
|
||||||
|
COMMENT ON TABLE migration_log IS '數據遷移記錄表';
|
||||||
|
COMMENT ON TABLE system_stats IS '系統統計數據表';
|
||||||
|
|
||||||
|
-- 添加欄位註釋
|
||||||
|
COMMENT ON COLUMN wishes.title IS '困擾案例標題';
|
||||||
|
COMMENT ON COLUMN wishes.current_pain IS '目前遇到的困擾描述';
|
||||||
|
COMMENT ON COLUMN wishes.expected_solution IS '期望的解決方案';
|
||||||
|
COMMENT ON COLUMN wishes.expected_effect IS '預期效果描述';
|
||||||
|
COMMENT ON COLUMN wishes.is_public IS '是否公開顯示';
|
||||||
|
COMMENT ON COLUMN wishes.images IS '相關圖片資訊(JSON格式)';
|
||||||
|
COMMENT ON COLUMN wishes.user_session IS '用戶會話標識';
|
||||||
|
COMMENT ON COLUMN wishes.category IS '困擾類別';
|
||||||
|
COMMENT ON COLUMN wishes.priority IS '優先級(1-5,5最高)';
|
||||||
|
|
||||||
|
COMMENT ON COLUMN wish_likes.wish_id IS '被點讚的困擾案例ID';
|
||||||
|
COMMENT ON COLUMN wish_likes.user_session IS '點讚用戶的會話標識';
|
||||||
|
COMMENT ON COLUMN wish_likes.ip_address IS '點讚用戶的IP地址';
|
||||||
|
|
||||||
|
COMMENT ON COLUMN user_settings.background_music_enabled IS '背景音樂是否啟用';
|
||||||
|
COMMENT ON COLUMN user_settings.background_music_volume IS '背景音樂音量(0-1)';
|
||||||
|
COMMENT ON COLUMN user_settings.theme_preference IS '主題偏好設定';
|
||||||
|
|
||||||
|
-- 顯示創建結果
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
RAISE NOTICE '✅ 基礎表格創建完成!';
|
||||||
|
RAISE NOTICE '📊 創建的表格:';
|
||||||
|
RAISE NOTICE ' - wishes(困擾案例)';
|
||||||
|
RAISE NOTICE ' - wish_likes(點讚記錄)';
|
||||||
|
RAISE NOTICE ' - user_settings(用戶設定)';
|
||||||
|
RAISE NOTICE ' - migration_log(遷移記錄)';
|
||||||
|
RAISE NOTICE ' - system_stats(系統統計)';
|
||||||
|
RAISE NOTICE '';
|
||||||
|
RAISE NOTICE '🔄 下一步:執行 02-create-indexes.sql';
|
||||||
|
END $$;
|
174
scripts/02-create-indexes.sql
Normal file
174
scripts/02-create-indexes.sql
Normal file
@@ -0,0 +1,174 @@
|
|||||||
|
-- 心願星河 - 索引和觸發器創建
|
||||||
|
-- 執行順序:第 2 步
|
||||||
|
-- 說明:創建性能優化索引和自動更新觸發器
|
||||||
|
|
||||||
|
-- 開始事務
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
-- 1. wishes 表格索引
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_wishes_created_at ON wishes(created_at DESC);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_wishes_is_public ON wishes(is_public) WHERE is_public = true;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_wishes_status ON wishes(status) WHERE status = 'active';
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_wishes_category ON wishes(category) WHERE category IS NOT NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_wishes_priority ON wishes(priority DESC);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_wishes_user_session ON wishes(user_session);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_wishes_email ON wishes(email) WHERE email IS NOT NULL;
|
||||||
|
|
||||||
|
-- 全文搜索索引 (使用 simple 配置以支持多语言)
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_wishes_search ON wishes USING gin(
|
||||||
|
to_tsvector('simple', title || ' ' || current_pain || ' ' || expected_solution)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 2. wish_likes 表格索引
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_wish_likes_wish_id ON wish_likes(wish_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_wish_likes_user_session ON wish_likes(user_session);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_wish_likes_created_at ON wish_likes(created_at DESC);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_wish_likes_ip_address ON wish_likes(ip_address);
|
||||||
|
|
||||||
|
-- 3. user_settings 表格索引
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_settings_session ON user_settings(user_session);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_settings_updated_at ON user_settings(updated_at DESC);
|
||||||
|
|
||||||
|
-- 4. migration_log 表格索引
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_migration_log_user_session ON migration_log(user_session);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_migration_log_type ON migration_log(migration_type);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_migration_log_success ON migration_log(success);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_migration_log_created_at ON migration_log(created_at DESC);
|
||||||
|
|
||||||
|
-- 5. system_stats 表格索引
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_system_stats_date ON system_stats(stat_date DESC);
|
||||||
|
|
||||||
|
-- 6. 創建更新時間觸發器函數
|
||||||
|
CREATE OR REPLACE FUNCTION update_updated_at_column()
|
||||||
|
RETURNS TRIGGER AS $$
|
||||||
|
BEGIN
|
||||||
|
NEW.updated_at = NOW();
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
-- 7. 為需要的表格添加更新時間觸發器
|
||||||
|
DROP TRIGGER IF EXISTS update_wishes_updated_at ON wishes;
|
||||||
|
CREATE TRIGGER update_wishes_updated_at
|
||||||
|
BEFORE UPDATE ON wishes
|
||||||
|
FOR EACH ROW
|
||||||
|
EXECUTE FUNCTION update_updated_at_column();
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS update_user_settings_updated_at ON user_settings;
|
||||||
|
CREATE TRIGGER update_user_settings_updated_at
|
||||||
|
BEFORE UPDATE ON user_settings
|
||||||
|
FOR EACH ROW
|
||||||
|
EXECUTE FUNCTION update_updated_at_column();
|
||||||
|
|
||||||
|
-- 8. 創建統計更新觸發器函數
|
||||||
|
CREATE OR REPLACE FUNCTION update_system_stats()
|
||||||
|
RETURNS TRIGGER AS $$
|
||||||
|
BEGIN
|
||||||
|
INSERT INTO system_stats (
|
||||||
|
stat_date,
|
||||||
|
total_wishes,
|
||||||
|
public_wishes,
|
||||||
|
private_wishes,
|
||||||
|
total_likes,
|
||||||
|
active_users
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
CURRENT_DATE,
|
||||||
|
COUNT(*) as total_wishes,
|
||||||
|
COUNT(*) FILTER (WHERE is_public = true) as public_wishes,
|
||||||
|
COUNT(*) FILTER (WHERE is_public = false) as private_wishes,
|
||||||
|
(SELECT COUNT(*) FROM wish_likes) as total_likes,
|
||||||
|
COUNT(DISTINCT user_session) as active_users
|
||||||
|
FROM wishes
|
||||||
|
WHERE status = 'active'
|
||||||
|
ON CONFLICT (stat_date)
|
||||||
|
DO UPDATE SET
|
||||||
|
total_wishes = EXCLUDED.total_wishes,
|
||||||
|
public_wishes = EXCLUDED.public_wishes,
|
||||||
|
private_wishes = EXCLUDED.private_wishes,
|
||||||
|
total_likes = EXCLUDED.total_likes,
|
||||||
|
active_users = EXCLUDED.active_users;
|
||||||
|
|
||||||
|
RETURN COALESCE(NEW, OLD);
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
-- 9. 為 wishes 和 wish_likes 添加統計更新觸發器
|
||||||
|
DROP TRIGGER IF EXISTS update_stats_on_wish_change ON wishes;
|
||||||
|
CREATE TRIGGER update_stats_on_wish_change
|
||||||
|
AFTER INSERT OR UPDATE OR DELETE ON wishes
|
||||||
|
FOR EACH STATEMENT
|
||||||
|
EXECUTE FUNCTION update_system_stats();
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS update_stats_on_like_change ON wish_likes;
|
||||||
|
CREATE TRIGGER update_stats_on_like_change
|
||||||
|
AFTER INSERT OR DELETE ON wish_likes
|
||||||
|
FOR EACH STATEMENT
|
||||||
|
EXECUTE FUNCTION update_system_stats();
|
||||||
|
|
||||||
|
-- 10. 創建圖片清理觸發器函數
|
||||||
|
CREATE OR REPLACE FUNCTION cleanup_wish_images()
|
||||||
|
RETURNS TRIGGER AS $$
|
||||||
|
BEGIN
|
||||||
|
-- 當 wish 被刪除時,記錄需要清理的圖片
|
||||||
|
IF TG_OP = 'DELETE' THEN
|
||||||
|
INSERT INTO migration_log (
|
||||||
|
user_session,
|
||||||
|
migration_type,
|
||||||
|
source_data,
|
||||||
|
success,
|
||||||
|
error_message
|
||||||
|
) VALUES (
|
||||||
|
OLD.user_session,
|
||||||
|
'image_cleanup',
|
||||||
|
OLD.images,
|
||||||
|
false,
|
||||||
|
'Images marked for cleanup'
|
||||||
|
);
|
||||||
|
RETURN OLD;
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
-- 11. 為 wishes 添加圖片清理觸發器
|
||||||
|
DROP TRIGGER IF EXISTS cleanup_images_on_wish_delete ON wishes;
|
||||||
|
CREATE TRIGGER cleanup_images_on_wish_delete
|
||||||
|
AFTER DELETE ON wishes
|
||||||
|
FOR EACH ROW
|
||||||
|
EXECUTE FUNCTION cleanup_wish_images();
|
||||||
|
|
||||||
|
-- 提交事務
|
||||||
|
COMMIT;
|
||||||
|
|
||||||
|
-- 顯示創建結果
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
index_count INTEGER;
|
||||||
|
trigger_count INTEGER;
|
||||||
|
BEGIN
|
||||||
|
-- 計算索引數量
|
||||||
|
SELECT COUNT(*) INTO index_count
|
||||||
|
FROM pg_indexes
|
||||||
|
WHERE schemaname = 'public'
|
||||||
|
AND indexname LIKE 'idx_%';
|
||||||
|
|
||||||
|
-- 計算觸發器數量
|
||||||
|
SELECT COUNT(*) INTO trigger_count
|
||||||
|
FROM pg_trigger
|
||||||
|
WHERE tgname LIKE '%wish%' OR tgname LIKE '%update%';
|
||||||
|
|
||||||
|
RAISE NOTICE '✅ 索引和觸發器創建完成!';
|
||||||
|
RAISE NOTICE '📊 創建統計:';
|
||||||
|
RAISE NOTICE ' - 性能索引:% 個', index_count;
|
||||||
|
RAISE NOTICE ' - 自動觸發器:% 個', trigger_count;
|
||||||
|
RAISE NOTICE '';
|
||||||
|
RAISE NOTICE '🚀 性能優化功能:';
|
||||||
|
RAISE NOTICE ' - 快速查詢索引';
|
||||||
|
RAISE NOTICE ' - 全文搜索支援';
|
||||||
|
RAISE NOTICE ' - 自動統計更新';
|
||||||
|
RAISE NOTICE ' - 圖片清理追蹤';
|
||||||
|
RAISE NOTICE '';
|
||||||
|
RAISE NOTICE '🔄 下一步:執行 03-create-views-functions.sql';
|
||||||
|
END $$;
|
376
scripts/03-create-views-functions.sql
Normal file
376
scripts/03-create-views-functions.sql
Normal file
@@ -0,0 +1,376 @@
|
|||||||
|
-- 心願星河 - 視圖和函數創建
|
||||||
|
-- 執行順序:第 3 步
|
||||||
|
-- 說明:創建便利視圖和業務邏輯函數
|
||||||
|
|
||||||
|
-- 開始事務
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
-- 1. 創建帶點讚數的困擾案例視圖
|
||||||
|
CREATE OR REPLACE VIEW wishes_with_likes AS
|
||||||
|
SELECT
|
||||||
|
w.*,
|
||||||
|
COALESCE(like_counts.like_count, 0) as like_count,
|
||||||
|
CASE
|
||||||
|
WHEN w.created_at >= NOW() - INTERVAL '24 hours' THEN 'new'
|
||||||
|
WHEN like_counts.like_count >= 10 THEN 'popular'
|
||||||
|
WHEN w.priority >= 4 THEN 'urgent'
|
||||||
|
ELSE 'normal'
|
||||||
|
END as badge_type
|
||||||
|
FROM wishes w
|
||||||
|
LEFT JOIN (
|
||||||
|
SELECT
|
||||||
|
wish_id,
|
||||||
|
COUNT(*) as like_count
|
||||||
|
FROM wish_likes
|
||||||
|
GROUP BY wish_id
|
||||||
|
) like_counts ON w.id = like_counts.wish_id
|
||||||
|
WHERE w.status = 'active';
|
||||||
|
|
||||||
|
-- 2. 創建公開困擾案例視圖
|
||||||
|
CREATE OR REPLACE VIEW public_wishes AS
|
||||||
|
SELECT *
|
||||||
|
FROM wishes_with_likes
|
||||||
|
WHERE is_public = true
|
||||||
|
ORDER BY created_at DESC;
|
||||||
|
|
||||||
|
-- 3. 創建熱門困擾案例視圖
|
||||||
|
CREATE OR REPLACE VIEW popular_wishes AS
|
||||||
|
SELECT *
|
||||||
|
FROM wishes_with_likes
|
||||||
|
WHERE is_public = true
|
||||||
|
AND like_count >= 3
|
||||||
|
ORDER BY like_count DESC, created_at DESC;
|
||||||
|
|
||||||
|
-- 4. 創建統計摘要視圖
|
||||||
|
CREATE OR REPLACE VIEW wishes_summary AS
|
||||||
|
SELECT
|
||||||
|
COUNT(*) as total_wishes,
|
||||||
|
COUNT(*) FILTER (WHERE is_public = true) as public_wishes,
|
||||||
|
COUNT(*) FILTER (WHERE is_public = false) as private_wishes,
|
||||||
|
COUNT(*) FILTER (WHERE created_at >= NOW() - INTERVAL '7 days') as this_week,
|
||||||
|
COUNT(*) FILTER (WHERE created_at >= NOW() - INTERVAL '14 days' AND created_at < NOW() - INTERVAL '7 days') as last_week,
|
||||||
|
COUNT(*) FILTER (WHERE created_at >= NOW() - INTERVAL '24 hours') as today,
|
||||||
|
AVG(COALESCE(like_counts.like_count, 0))::DECIMAL(10,2) as avg_likes,
|
||||||
|
COUNT(DISTINCT user_session) as unique_users
|
||||||
|
FROM wishes w
|
||||||
|
LEFT JOIN (
|
||||||
|
SELECT wish_id, COUNT(*) as like_count
|
||||||
|
FROM wish_likes
|
||||||
|
GROUP BY wish_id
|
||||||
|
) like_counts ON w.id = like_counts.wish_id
|
||||||
|
WHERE w.status = 'active';
|
||||||
|
|
||||||
|
-- 5. 創建類別統計視圖
|
||||||
|
CREATE OR REPLACE VIEW category_stats AS
|
||||||
|
SELECT
|
||||||
|
COALESCE(category, '未分類') as category,
|
||||||
|
COUNT(*) as wish_count,
|
||||||
|
COUNT(*) FILTER (WHERE is_public = true) as public_count,
|
||||||
|
AVG(COALESCE(like_counts.like_count, 0))::DECIMAL(10,2) as avg_likes,
|
||||||
|
MAX(created_at) as latest_wish
|
||||||
|
FROM wishes w
|
||||||
|
LEFT JOIN (
|
||||||
|
SELECT wish_id, COUNT(*) as like_count
|
||||||
|
FROM wish_likes
|
||||||
|
GROUP BY wish_id
|
||||||
|
) like_counts ON w.id = like_counts.wish_id
|
||||||
|
WHERE w.status = 'active'
|
||||||
|
GROUP BY category
|
||||||
|
ORDER BY wish_count DESC;
|
||||||
|
|
||||||
|
-- 6. 創建獲取統計數據的函數
|
||||||
|
CREATE OR REPLACE FUNCTION get_wishes_stats()
|
||||||
|
RETURNS JSON AS $$
|
||||||
|
DECLARE
|
||||||
|
result JSON;
|
||||||
|
BEGIN
|
||||||
|
SELECT json_build_object(
|
||||||
|
'summary', (SELECT row_to_json(wishes_summary.*) FROM wishes_summary),
|
||||||
|
'categories', (
|
||||||
|
SELECT json_agg(row_to_json(category_stats.*))
|
||||||
|
FROM category_stats
|
||||||
|
),
|
||||||
|
'recent_activity', (
|
||||||
|
SELECT json_agg(
|
||||||
|
json_build_object(
|
||||||
|
'date', date_trunc('day', created_at),
|
||||||
|
'count', count(*)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
FROM wishes
|
||||||
|
WHERE created_at >= NOW() - INTERVAL '30 days'
|
||||||
|
AND status = 'active'
|
||||||
|
GROUP BY date_trunc('day', created_at)
|
||||||
|
ORDER BY date_trunc('day', created_at) DESC
|
||||||
|
LIMIT 30
|
||||||
|
)
|
||||||
|
) INTO result;
|
||||||
|
|
||||||
|
RETURN result;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
-- 7. 創建搜索困擾案例的函數
|
||||||
|
CREATE OR REPLACE FUNCTION search_wishes(
|
||||||
|
search_query TEXT,
|
||||||
|
limit_count INTEGER DEFAULT 20,
|
||||||
|
offset_count INTEGER DEFAULT 0
|
||||||
|
)
|
||||||
|
RETURNS TABLE(
|
||||||
|
id BIGINT,
|
||||||
|
title TEXT,
|
||||||
|
current_pain TEXT,
|
||||||
|
expected_solution TEXT,
|
||||||
|
like_count BIGINT,
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE,
|
||||||
|
relevance REAL
|
||||||
|
) AS $$
|
||||||
|
BEGIN
|
||||||
|
RETURN QUERY
|
||||||
|
SELECT
|
||||||
|
w.id,
|
||||||
|
w.title,
|
||||||
|
w.current_pain,
|
||||||
|
w.expected_solution,
|
||||||
|
COALESCE(like_counts.like_count, 0) as like_count,
|
||||||
|
w.created_at,
|
||||||
|
ts_rank(
|
||||||
|
to_tsvector('chinese', w.title || ' ' || w.current_pain || ' ' || w.expected_solution),
|
||||||
|
plainto_tsquery('chinese', search_query)
|
||||||
|
) as relevance
|
||||||
|
FROM wishes w
|
||||||
|
LEFT JOIN (
|
||||||
|
SELECT wish_id, COUNT(*) as like_count
|
||||||
|
FROM wish_likes
|
||||||
|
GROUP BY wish_id
|
||||||
|
) like_counts ON w.id = like_counts.wish_id
|
||||||
|
WHERE w.status = 'active'
|
||||||
|
AND w.is_public = true
|
||||||
|
AND (
|
||||||
|
to_tsvector('chinese', w.title || ' ' || w.current_pain || ' ' || w.expected_solution)
|
||||||
|
@@ plainto_tsquery('chinese', search_query)
|
||||||
|
)
|
||||||
|
ORDER BY relevance DESC, like_count DESC, w.created_at DESC
|
||||||
|
LIMIT limit_count
|
||||||
|
OFFSET offset_count;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
-- 8. 創建獲取用戶統計的函數
|
||||||
|
CREATE OR REPLACE FUNCTION get_user_stats(session_id TEXT)
|
||||||
|
RETURNS JSON AS $$
|
||||||
|
DECLARE
|
||||||
|
result JSON;
|
||||||
|
BEGIN
|
||||||
|
SELECT json_build_object(
|
||||||
|
'total_wishes', (
|
||||||
|
SELECT COUNT(*)
|
||||||
|
FROM wishes
|
||||||
|
WHERE user_session = session_id AND status = 'active'
|
||||||
|
),
|
||||||
|
'total_likes_received', (
|
||||||
|
SELECT COALESCE(SUM(like_counts.like_count), 0)
|
||||||
|
FROM wishes w
|
||||||
|
LEFT JOIN (
|
||||||
|
SELECT wish_id, COUNT(*) as like_count
|
||||||
|
FROM wish_likes
|
||||||
|
GROUP BY wish_id
|
||||||
|
) like_counts ON w.id = like_counts.wish_id
|
||||||
|
WHERE w.user_session = session_id AND w.status = 'active'
|
||||||
|
),
|
||||||
|
'total_likes_given', (
|
||||||
|
SELECT COUNT(*)
|
||||||
|
FROM wish_likes
|
||||||
|
WHERE user_session = session_id
|
||||||
|
),
|
||||||
|
'recent_wishes', (
|
||||||
|
SELECT json_agg(
|
||||||
|
json_build_object(
|
||||||
|
'id', id,
|
||||||
|
'title', title,
|
||||||
|
'created_at', created_at,
|
||||||
|
'like_count', COALESCE(like_counts.like_count, 0)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
FROM wishes w
|
||||||
|
LEFT JOIN (
|
||||||
|
SELECT wish_id, COUNT(*) as like_count
|
||||||
|
FROM wish_likes
|
||||||
|
GROUP BY wish_id
|
||||||
|
) like_counts ON w.id = like_counts.wish_id
|
||||||
|
WHERE w.user_session = session_id
|
||||||
|
AND w.status = 'active'
|
||||||
|
ORDER BY w.created_at DESC
|
||||||
|
LIMIT 5
|
||||||
|
)
|
||||||
|
) INTO result;
|
||||||
|
|
||||||
|
RETURN result;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
-- 9. 創建清理孤立圖片的函數
|
||||||
|
CREATE OR REPLACE FUNCTION cleanup_orphaned_images()
|
||||||
|
RETURNS INTEGER AS $$
|
||||||
|
DECLARE
|
||||||
|
deleted_count INTEGER := 0;
|
||||||
|
image_record RECORD;
|
||||||
|
BEGIN
|
||||||
|
-- 記錄清理開始
|
||||||
|
INSERT INTO migration_log (
|
||||||
|
user_session,
|
||||||
|
migration_type,
|
||||||
|
success,
|
||||||
|
error_message
|
||||||
|
) VALUES (
|
||||||
|
'system',
|
||||||
|
'image_cleanup',
|
||||||
|
false,
|
||||||
|
'Starting orphaned image cleanup'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 這裡只是標記,實際的 Storage 清理需要在應用層面處理
|
||||||
|
-- 因為 SQL 無法直接操作 Supabase Storage
|
||||||
|
|
||||||
|
-- 找出需要清理的圖片記錄
|
||||||
|
FOR image_record IN
|
||||||
|
SELECT DISTINCT jsonb_array_elements(images)->>'storage_path' as image_path
|
||||||
|
FROM wishes
|
||||||
|
WHERE status = 'deleted'
|
||||||
|
AND images IS NOT NULL
|
||||||
|
AND jsonb_array_length(images) > 0
|
||||||
|
LOOP
|
||||||
|
-- 標記為需要清理
|
||||||
|
INSERT INTO migration_log (
|
||||||
|
user_session,
|
||||||
|
migration_type,
|
||||||
|
source_data,
|
||||||
|
success,
|
||||||
|
error_message
|
||||||
|
) VALUES (
|
||||||
|
'system',
|
||||||
|
'image_cleanup',
|
||||||
|
json_build_object('image_path', image_record.image_path),
|
||||||
|
false,
|
||||||
|
'Image marked for cleanup: ' || image_record.image_path
|
||||||
|
);
|
||||||
|
|
||||||
|
deleted_count := deleted_count + 1;
|
||||||
|
END LOOP;
|
||||||
|
|
||||||
|
-- 記錄清理完成
|
||||||
|
INSERT INTO migration_log (
|
||||||
|
user_session,
|
||||||
|
migration_type,
|
||||||
|
target_records,
|
||||||
|
success,
|
||||||
|
error_message
|
||||||
|
) VALUES (
|
||||||
|
'system',
|
||||||
|
'image_cleanup',
|
||||||
|
deleted_count,
|
||||||
|
true,
|
||||||
|
'Orphaned image cleanup completed. Marked ' || deleted_count || ' images for cleanup.'
|
||||||
|
);
|
||||||
|
|
||||||
|
RETURN deleted_count;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
-- 10. 創建性能檢查函數
|
||||||
|
CREATE OR REPLACE FUNCTION get_performance_stats()
|
||||||
|
RETURNS JSON AS $$
|
||||||
|
DECLARE
|
||||||
|
result JSON;
|
||||||
|
BEGIN
|
||||||
|
SELECT json_build_object(
|
||||||
|
'table_sizes', (
|
||||||
|
SELECT json_object_agg(
|
||||||
|
table_name,
|
||||||
|
pg_size_pretty(pg_total_relation_size(quote_ident(table_name)))
|
||||||
|
)
|
||||||
|
FROM (
|
||||||
|
SELECT 'wishes' as table_name
|
||||||
|
UNION SELECT 'wish_likes'
|
||||||
|
UNION SELECT 'user_settings'
|
||||||
|
UNION SELECT 'migration_log'
|
||||||
|
UNION SELECT 'system_stats'
|
||||||
|
) tables
|
||||||
|
),
|
||||||
|
'index_usage', (
|
||||||
|
SELECT json_object_agg(
|
||||||
|
indexname,
|
||||||
|
json_build_object(
|
||||||
|
'size', pg_size_pretty(pg_relation_size(indexname::regclass)),
|
||||||
|
'scans', idx_scan,
|
||||||
|
'tuples_read', idx_tup_read,
|
||||||
|
'tuples_fetched', idx_tup_fetch
|
||||||
|
)
|
||||||
|
)
|
||||||
|
FROM pg_stat_user_indexes
|
||||||
|
WHERE schemaname = 'public'
|
||||||
|
AND indexname LIKE 'idx_%'
|
||||||
|
),
|
||||||
|
'query_performance', (
|
||||||
|
SELECT json_build_object(
|
||||||
|
'avg_query_time', COALESCE(AVG(mean_exec_time), 0),
|
||||||
|
'total_queries', COALESCE(SUM(calls), 0),
|
||||||
|
'slowest_queries', (
|
||||||
|
SELECT json_agg(
|
||||||
|
json_build_object(
|
||||||
|
'query', LEFT(query, 100) || '...',
|
||||||
|
'avg_time', mean_exec_time,
|
||||||
|
'calls', calls
|
||||||
|
)
|
||||||
|
)
|
||||||
|
FROM pg_stat_statements
|
||||||
|
WHERE query LIKE '%wishes%'
|
||||||
|
ORDER BY mean_exec_time DESC
|
||||||
|
LIMIT 5
|
||||||
|
)
|
||||||
|
)
|
||||||
|
FROM pg_stat_statements
|
||||||
|
WHERE query LIKE '%wishes%'
|
||||||
|
)
|
||||||
|
) INTO result;
|
||||||
|
|
||||||
|
RETURN result;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
-- 提交事務
|
||||||
|
COMMIT;
|
||||||
|
|
||||||
|
-- 顯示創建結果
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
view_count INTEGER;
|
||||||
|
function_count INTEGER;
|
||||||
|
BEGIN
|
||||||
|
-- 計算視圖數量
|
||||||
|
SELECT COUNT(*) INTO view_count
|
||||||
|
FROM pg_views
|
||||||
|
WHERE schemaname = 'public';
|
||||||
|
|
||||||
|
-- 計算函數數量
|
||||||
|
SELECT COUNT(*) INTO function_count
|
||||||
|
FROM pg_proc p
|
||||||
|
JOIN pg_namespace n ON p.pronamespace = n.oid
|
||||||
|
WHERE n.nspname = 'public'
|
||||||
|
AND p.proname LIKE '%wish%' OR p.proname LIKE 'get_%' OR p.proname LIKE 'cleanup_%';
|
||||||
|
|
||||||
|
RAISE NOTICE '✅ 視圖和函數創建完成!';
|
||||||
|
RAISE NOTICE '📊 創建統計:';
|
||||||
|
RAISE NOTICE ' - 便利視圖:% 個', view_count;
|
||||||
|
RAISE NOTICE ' - 業務函數:% 個', function_count;
|
||||||
|
RAISE NOTICE '';
|
||||||
|
RAISE NOTICE '🎯 主要功能:';
|
||||||
|
RAISE NOTICE ' - wishes_with_likes(帶點讚數的困擾案例)';
|
||||||
|
RAISE NOTICE ' - public_wishes(公開困擾案例)';
|
||||||
|
RAISE NOTICE ' - popular_wishes(熱門困擾案例)';
|
||||||
|
RAISE NOTICE ' - search_wishes()(全文搜索)';
|
||||||
|
RAISE NOTICE ' - get_wishes_stats()(統計數據)';
|
||||||
|
RAISE NOTICE ' - cleanup_orphaned_images()(圖片清理)';
|
||||||
|
RAISE NOTICE '';
|
||||||
|
RAISE NOTICE '🔄 下一步:執行 04-setup-storage.sql';
|
||||||
|
END $$;
|
284
scripts/04-setup-storage.sql
Normal file
284
scripts/04-setup-storage.sql
Normal file
@@ -0,0 +1,284 @@
|
|||||||
|
-- 心願星河 - 存儲服務設置
|
||||||
|
-- 執行順序:第 4 步
|
||||||
|
-- 說明:設置 Supabase Storage 桶和相關政策
|
||||||
|
|
||||||
|
-- 注意:此腳本需要在 Supabase Dashboard 的 SQL Editor 中執行
|
||||||
|
-- 某些 Storage 操作可能需要 service_role 權限
|
||||||
|
|
||||||
|
-- 開始事務
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
-- 1. 創建主要圖片存儲桶
|
||||||
|
INSERT INTO storage.buckets (
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
public,
|
||||||
|
file_size_limit,
|
||||||
|
allowed_mime_types,
|
||||||
|
avif_autodetection
|
||||||
|
) VALUES (
|
||||||
|
'wish-images',
|
||||||
|
'wish-images',
|
||||||
|
true,
|
||||||
|
5242880, -- 5MB
|
||||||
|
ARRAY['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif'],
|
||||||
|
true
|
||||||
|
) ON CONFLICT (id) DO UPDATE SET
|
||||||
|
file_size_limit = EXCLUDED.file_size_limit,
|
||||||
|
allowed_mime_types = EXCLUDED.allowed_mime_types,
|
||||||
|
avif_autodetection = EXCLUDED.avif_autodetection;
|
||||||
|
|
||||||
|
-- 2. 創建縮圖存儲桶
|
||||||
|
INSERT INTO storage.buckets (
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
public,
|
||||||
|
file_size_limit,
|
||||||
|
allowed_mime_types,
|
||||||
|
avif_autodetection
|
||||||
|
) VALUES (
|
||||||
|
'wish-thumbnails',
|
||||||
|
'wish-thumbnails',
|
||||||
|
true,
|
||||||
|
1048576, -- 1MB
|
||||||
|
ARRAY['image/jpeg', 'image/jpg', 'image/png', 'image/webp'],
|
||||||
|
true
|
||||||
|
) ON CONFLICT (id) DO UPDATE SET
|
||||||
|
file_size_limit = EXCLUDED.file_size_limit,
|
||||||
|
allowed_mime_types = EXCLUDED.allowed_mime_types,
|
||||||
|
avif_autodetection = EXCLUDED.avif_autodetection;
|
||||||
|
|
||||||
|
-- 3. 創建存儲使用統計表
|
||||||
|
CREATE TABLE IF NOT EXISTS storage_usage (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
bucket_name TEXT NOT NULL,
|
||||||
|
total_files INTEGER DEFAULT 0,
|
||||||
|
total_size_bytes BIGINT DEFAULT 0,
|
||||||
|
last_cleanup_at TIMESTAMP WITH TIME ZONE,
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,
|
||||||
|
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,
|
||||||
|
UNIQUE(bucket_name)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 4. 插入初始存儲統計記錄
|
||||||
|
INSERT INTO storage_usage (bucket_name, total_files, total_size_bytes)
|
||||||
|
VALUES
|
||||||
|
('wish-images', 0, 0),
|
||||||
|
('wish-thumbnails', 0, 0)
|
||||||
|
ON CONFLICT (bucket_name) DO NOTHING;
|
||||||
|
|
||||||
|
-- 5. 創建存儲統計更新函數
|
||||||
|
CREATE OR REPLACE FUNCTION update_storage_usage()
|
||||||
|
RETURNS VOID AS $$
|
||||||
|
BEGIN
|
||||||
|
-- 更新 wish-images 桶統計
|
||||||
|
INSERT INTO storage_usage (bucket_name, total_files, total_size_bytes, updated_at)
|
||||||
|
SELECT
|
||||||
|
'wish-images',
|
||||||
|
COUNT(*),
|
||||||
|
COALESCE(SUM(metadata->>'size')::BIGINT, 0),
|
||||||
|
NOW()
|
||||||
|
FROM storage.objects
|
||||||
|
WHERE bucket_id = 'wish-images'
|
||||||
|
ON CONFLICT (bucket_name)
|
||||||
|
DO UPDATE SET
|
||||||
|
total_files = EXCLUDED.total_files,
|
||||||
|
total_size_bytes = EXCLUDED.total_size_bytes,
|
||||||
|
updated_at = EXCLUDED.updated_at;
|
||||||
|
|
||||||
|
-- 更新 wish-thumbnails 桶統計
|
||||||
|
INSERT INTO storage_usage (bucket_name, total_files, total_size_bytes, updated_at)
|
||||||
|
SELECT
|
||||||
|
'wish-thumbnails',
|
||||||
|
COUNT(*),
|
||||||
|
COALESCE(SUM(metadata->>'size')::BIGINT, 0),
|
||||||
|
NOW()
|
||||||
|
FROM storage.objects
|
||||||
|
WHERE bucket_id = 'wish-thumbnails'
|
||||||
|
ON CONFLICT (bucket_name)
|
||||||
|
DO UPDATE SET
|
||||||
|
total_files = EXCLUDED.total_files,
|
||||||
|
total_size_bytes = EXCLUDED.total_size_bytes,
|
||||||
|
updated_at = EXCLUDED.updated_at;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
-- 6. 創建存儲清理記錄表
|
||||||
|
CREATE TABLE IF NOT EXISTS storage_cleanup_log (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
bucket_name TEXT NOT NULL,
|
||||||
|
file_path TEXT NOT NULL,
|
||||||
|
file_size BIGINT,
|
||||||
|
cleanup_reason TEXT,
|
||||||
|
cleanup_status TEXT DEFAULT 'pending' CHECK (cleanup_status IN ('pending', 'completed', 'failed')),
|
||||||
|
error_message TEXT,
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,
|
||||||
|
completed_at TIMESTAMP WITH TIME ZONE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 7. 創建獲取存儲統計的函數
|
||||||
|
CREATE OR REPLACE FUNCTION get_storage_stats()
|
||||||
|
RETURNS JSON AS $$
|
||||||
|
DECLARE
|
||||||
|
result JSON;
|
||||||
|
BEGIN
|
||||||
|
-- 更新統計數據
|
||||||
|
PERFORM update_storage_usage();
|
||||||
|
|
||||||
|
SELECT json_build_object(
|
||||||
|
'buckets', (
|
||||||
|
SELECT json_agg(
|
||||||
|
json_build_object(
|
||||||
|
'name', bucket_name,
|
||||||
|
'total_files', total_files,
|
||||||
|
'total_size_mb', ROUND(total_size_bytes / 1024.0 / 1024.0, 2),
|
||||||
|
'last_updated', updated_at
|
||||||
|
)
|
||||||
|
)
|
||||||
|
FROM storage_usage
|
||||||
|
),
|
||||||
|
'cleanup_pending', (
|
||||||
|
SELECT COUNT(*)
|
||||||
|
FROM storage_cleanup_log
|
||||||
|
WHERE cleanup_status = 'pending'
|
||||||
|
),
|
||||||
|
'total_storage_mb', (
|
||||||
|
SELECT ROUND(SUM(total_size_bytes) / 1024.0 / 1024.0, 2)
|
||||||
|
FROM storage_usage
|
||||||
|
)
|
||||||
|
) INTO result;
|
||||||
|
|
||||||
|
RETURN result;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
-- 8. 創建標記孤立圖片的函數
|
||||||
|
CREATE OR REPLACE FUNCTION mark_orphaned_images_for_cleanup()
|
||||||
|
RETURNS INTEGER AS $$
|
||||||
|
DECLARE
|
||||||
|
marked_count INTEGER := 0;
|
||||||
|
image_record RECORD;
|
||||||
|
referenced_images TEXT[];
|
||||||
|
BEGIN
|
||||||
|
-- 獲取所有被引用的圖片路徑
|
||||||
|
SELECT ARRAY_AGG(DISTINCT image_path) INTO referenced_images
|
||||||
|
FROM (
|
||||||
|
SELECT jsonb_array_elements_text(
|
||||||
|
jsonb_path_query_array(images, '$[*].storage_path')
|
||||||
|
) as image_path
|
||||||
|
FROM wishes
|
||||||
|
WHERE status = 'active'
|
||||||
|
AND images IS NOT NULL
|
||||||
|
AND jsonb_array_length(images) > 0
|
||||||
|
) referenced;
|
||||||
|
|
||||||
|
-- 標記孤立的圖片
|
||||||
|
FOR image_record IN
|
||||||
|
SELECT name, metadata->>'size' as file_size
|
||||||
|
FROM storage.objects
|
||||||
|
WHERE bucket_id IN ('wish-images', 'wish-thumbnails')
|
||||||
|
AND (referenced_images IS NULL OR name != ALL(referenced_images))
|
||||||
|
LOOP
|
||||||
|
INSERT INTO storage_cleanup_log (
|
||||||
|
bucket_name,
|
||||||
|
file_path,
|
||||||
|
file_size,
|
||||||
|
cleanup_reason,
|
||||||
|
cleanup_status
|
||||||
|
) VALUES (
|
||||||
|
CASE
|
||||||
|
WHEN image_record.name LIKE '%/thumbnails/%' THEN 'wish-thumbnails'
|
||||||
|
ELSE 'wish-images'
|
||||||
|
END,
|
||||||
|
image_record.name,
|
||||||
|
image_record.file_size::BIGINT,
|
||||||
|
'Orphaned image - not referenced by any active wish',
|
||||||
|
'pending'
|
||||||
|
) ON CONFLICT DO NOTHING;
|
||||||
|
|
||||||
|
marked_count := marked_count + 1;
|
||||||
|
END LOOP;
|
||||||
|
|
||||||
|
-- 記錄清理操作
|
||||||
|
INSERT INTO migration_log (
|
||||||
|
user_session,
|
||||||
|
migration_type,
|
||||||
|
target_records,
|
||||||
|
success,
|
||||||
|
error_message
|
||||||
|
) VALUES (
|
||||||
|
'system',
|
||||||
|
'storage_cleanup',
|
||||||
|
marked_count,
|
||||||
|
true,
|
||||||
|
'Marked ' || marked_count || ' orphaned images for cleanup'
|
||||||
|
);
|
||||||
|
|
||||||
|
RETURN marked_count;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
-- 9. 創建存儲使用量更新觸發器
|
||||||
|
CREATE OR REPLACE FUNCTION trigger_storage_usage_update()
|
||||||
|
RETURNS TRIGGER AS $$
|
||||||
|
BEGIN
|
||||||
|
-- 異步更新存儲統計(避免阻塞主要操作)
|
||||||
|
PERFORM pg_notify('storage_usage_update', 'update_needed');
|
||||||
|
RETURN COALESCE(NEW, OLD);
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
-- 10. 為 wishes 表添加存儲使用量更新觸發器
|
||||||
|
DROP TRIGGER IF EXISTS update_storage_on_wish_change ON wishes;
|
||||||
|
CREATE TRIGGER update_storage_on_wish_change
|
||||||
|
AFTER INSERT OR UPDATE OR DELETE ON wishes
|
||||||
|
FOR EACH STATEMENT
|
||||||
|
EXECUTE FUNCTION trigger_storage_usage_update();
|
||||||
|
|
||||||
|
-- 提交事務
|
||||||
|
COMMIT;
|
||||||
|
|
||||||
|
-- 顯示創建結果
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
bucket_count INTEGER;
|
||||||
|
storage_table_count INTEGER;
|
||||||
|
BEGIN
|
||||||
|
-- 計算存儲桶數量
|
||||||
|
SELECT COUNT(*) INTO bucket_count
|
||||||
|
FROM storage.buckets
|
||||||
|
WHERE id LIKE 'wish-%';
|
||||||
|
|
||||||
|
-- 計算存儲相關表格數量
|
||||||
|
SELECT COUNT(*) INTO storage_table_count
|
||||||
|
FROM information_schema.tables
|
||||||
|
WHERE table_schema = 'public'
|
||||||
|
AND table_name LIKE '%storage%';
|
||||||
|
|
||||||
|
RAISE NOTICE '✅ 存儲服務設置完成!';
|
||||||
|
RAISE NOTICE '📊 創建統計:';
|
||||||
|
RAISE NOTICE ' - 存儲桶:% 個', bucket_count;
|
||||||
|
RAISE NOTICE ' - 存儲管理表:% 個', storage_table_count;
|
||||||
|
RAISE NOTICE '';
|
||||||
|
RAISE NOTICE '🗂️ 存儲桶配置:';
|
||||||
|
RAISE NOTICE ' - wish-images(主圖片,5MB限制)';
|
||||||
|
RAISE NOTICE ' - wish-thumbnails(縮圖,1MB限制)';
|
||||||
|
RAISE NOTICE '';
|
||||||
|
RAISE NOTICE '🛠️ 管理功能:';
|
||||||
|
RAISE NOTICE ' - 自動統計更新';
|
||||||
|
RAISE NOTICE ' - 孤立圖片檢測';
|
||||||
|
RAISE NOTICE ' - 清理記錄追蹤';
|
||||||
|
RAISE NOTICE '';
|
||||||
|
RAISE NOTICE '🔄 下一步:執行 05-setup-rls.sql';
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- 重要提醒
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
RAISE NOTICE '';
|
||||||
|
RAISE NOTICE '⚠️ 重要提醒:';
|
||||||
|
RAISE NOTICE ' 1. 請確認存儲桶已在 Supabase Dashboard 中顯示';
|
||||||
|
RAISE NOTICE ' 2. 檢查 Storage → Settings 中的政策設置';
|
||||||
|
RAISE NOTICE ' 3. 測試圖片上傳功能是否正常';
|
||||||
|
RAISE NOTICE ' 4. 定期執行 mark_orphaned_images_for_cleanup() 清理孤立圖片';
|
||||||
|
END $$;
|
151
scripts/05-setup-rls.sql
Normal file
151
scripts/05-setup-rls.sql
Normal file
@@ -0,0 +1,151 @@
|
|||||||
|
-- 心願星河 - Row Level Security (RLS) 政策設置
|
||||||
|
-- 執行順序:第 5 步(最後一步)
|
||||||
|
-- 說明:設置完整的安全政策,保護數據安全
|
||||||
|
|
||||||
|
-- 開始事務
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
-- 1. 啟用所有表格的 RLS
|
||||||
|
ALTER TABLE wishes ENABLE ROW LEVEL SECURITY;
|
||||||
|
ALTER TABLE wish_likes ENABLE ROW LEVEL SECURITY;
|
||||||
|
ALTER TABLE user_settings ENABLE ROW LEVEL SECURITY;
|
||||||
|
ALTER TABLE migration_log ENABLE ROW LEVEL SECURITY;
|
||||||
|
ALTER TABLE system_stats ENABLE ROW LEVEL SECURITY;
|
||||||
|
ALTER TABLE storage_usage ENABLE ROW LEVEL SECURITY;
|
||||||
|
ALTER TABLE storage_cleanup_log ENABLE ROW LEVEL SECURITY;
|
||||||
|
|
||||||
|
-- 2. wishes 表格的 RLS 政策
|
||||||
|
|
||||||
|
-- 2.1 查看政策:公開的困擾案例所有人都可以查看
|
||||||
|
DROP POLICY IF EXISTS "Public wishes are viewable by everyone" ON wishes;
|
||||||
|
CREATE POLICY "Public wishes are viewable by everyone" ON wishes
|
||||||
|
FOR SELECT
|
||||||
|
USING (is_public = true AND status = 'active');
|
||||||
|
|
||||||
|
-- 2.2 查看政策:用戶可以查看自己的所有困擾案例
|
||||||
|
DROP POLICY IF EXISTS "Users can view own wishes" ON wishes;
|
||||||
|
CREATE POLICY "Users can view own wishes" ON wishes
|
||||||
|
FOR SELECT
|
||||||
|
USING (user_session = current_setting('request.jwt.claims', true)::json->>'user_session' OR
|
||||||
|
user_session = current_setting('app.user_session', true));
|
||||||
|
|
||||||
|
-- 2.3 插入政策:所有人都可以提交困擾案例
|
||||||
|
DROP POLICY IF EXISTS "Anyone can insert wishes" ON wishes;
|
||||||
|
CREATE POLICY "Anyone can insert wishes" ON wishes
|
||||||
|
FOR INSERT
|
||||||
|
WITH CHECK (true);
|
||||||
|
|
||||||
|
-- 2.4 更新政策:用戶只能更新自己的困擾案例
|
||||||
|
DROP POLICY IF EXISTS "Users can update own wishes" ON wishes;
|
||||||
|
CREATE POLICY "Users can update own wishes" ON wishes
|
||||||
|
FOR UPDATE
|
||||||
|
USING (user_session = current_setting('request.jwt.claims', true)::json->>'user_session' OR
|
||||||
|
user_session = current_setting('app.user_session', true))
|
||||||
|
WITH CHECK (user_session = current_setting('request.jwt.claims', true)::json->>'user_session' OR
|
||||||
|
user_session = current_setting('app.user_session', true));
|
||||||
|
|
||||||
|
-- 2.5 刪除政策:用戶只能軟刪除自己的困擾案例
|
||||||
|
DROP POLICY IF EXISTS "Users can delete own wishes" ON wishes;
|
||||||
|
CREATE POLICY "Users can delete own wishes" ON wishes
|
||||||
|
FOR UPDATE
|
||||||
|
USING (user_session = current_setting('request.jwt.claims', true)::json->>'user_session' OR
|
||||||
|
user_session = current_setting('app.user_session', true))
|
||||||
|
WITH CHECK (status = 'deleted');
|
||||||
|
|
||||||
|
-- 3. wish_likes 表格的 RLS 政策
|
||||||
|
|
||||||
|
-- 3.1 查看政策:所有人都可以查看點讚記錄(用於統計)
|
||||||
|
DROP POLICY IF EXISTS "Wish likes are viewable by everyone" ON wish_likes;
|
||||||
|
CREATE POLICY "Wish likes are viewable by everyone" ON wish_likes
|
||||||
|
FOR SELECT
|
||||||
|
USING (true);
|
||||||
|
|
||||||
|
-- 3.2 插入政策:所有人都可以點讚
|
||||||
|
DROP POLICY IF EXISTS "Anyone can insert wish likes" ON wish_likes;
|
||||||
|
CREATE POLICY "Anyone can insert wish likes" ON wish_likes
|
||||||
|
FOR INSERT
|
||||||
|
WITH CHECK (true);
|
||||||
|
|
||||||
|
-- 3.3 刪除政策:用戶只能取消自己的點讚
|
||||||
|
DROP POLICY IF EXISTS "Users can delete own likes" ON wish_likes;
|
||||||
|
CREATE POLICY "Users can delete own likes" ON wish_likes
|
||||||
|
FOR DELETE
|
||||||
|
USING (user_session = current_setting('request.jwt.claims', true)::json->>'user_session' OR
|
||||||
|
user_session = current_setting('app.user_session', true));
|
||||||
|
|
||||||
|
-- 4. user_settings 表格的 RLS 政策
|
||||||
|
|
||||||
|
-- 4.1 查看政策:用戶只能查看自己的設定
|
||||||
|
DROP POLICY IF EXISTS "Users can view own settings" ON user_settings;
|
||||||
|
CREATE POLICY "Users can view own settings" ON user_settings
|
||||||
|
FOR SELECT
|
||||||
|
USING (user_session = current_setting('request.jwt.claims', true)::json->>'user_session' OR
|
||||||
|
user_session = current_setting('app.user_session', true));
|
||||||
|
|
||||||
|
-- 4.2 插入政策:用戶可以創建自己的設定
|
||||||
|
DROP POLICY IF EXISTS "Users can insert own settings" ON user_settings;
|
||||||
|
CREATE POLICY "Users can insert own settings" ON user_settings
|
||||||
|
FOR INSERT
|
||||||
|
WITH CHECK (user_session = current_setting('request.jwt.claims', true)::json->>'user_session' OR
|
||||||
|
user_session = current_setting('app.user_session', true));
|
||||||
|
|
||||||
|
-- 4.3 更新政策:用戶只能更新自己的設定
|
||||||
|
DROP POLICY IF EXISTS "Users can update own settings" ON user_settings;
|
||||||
|
CREATE POLICY "Users can update own settings" ON user_settings
|
||||||
|
FOR UPDATE
|
||||||
|
USING (user_session = current_setting('request.jwt.claims', true)::json->>'user_session' OR
|
||||||
|
user_session = current_setting('app.user_session', true))
|
||||||
|
WITH CHECK (user_session = current_setting('request.jwt.claims', true)::json->>'user_session' OR
|
||||||
|
user_session = current_setting('app.user_session', true));
|
||||||
|
|
||||||
|
-- 5. migration_log 表格的 RLS 政策
|
||||||
|
|
||||||
|
-- 5.1 查看政策:用戶可以查看自己的遷移記錄
|
||||||
|
DROP POLICY IF EXISTS "Users can view own migration logs" ON migration_log;
|
||||||
|
CREATE POLICY "Users can view own migration logs" ON migration_log
|
||||||
|
FOR SELECT
|
||||||
|
USING (user_session = current_setting('request.jwt.claims', true)::json->>'user_session' OR
|
||||||
|
user_session = current_setting('app.user_session', true) OR
|
||||||
|
user_session = 'system');
|
||||||
|
|
||||||
|
-- 5.2 插入政策:系統和用戶都可以插入遷移記錄
|
||||||
|
DROP POLICY IF EXISTS "System and users can insert migration logs" ON migration_log;
|
||||||
|
CREATE POLICY "System and users can insert migration logs" ON migration_log
|
||||||
|
FOR INSERT
|
||||||
|
WITH CHECK (true);
|
||||||
|
|
||||||
|
-- 6. system_stats 表格的 RLS 政策
|
||||||
|
|
||||||
|
-- 6.1 查看政策:所有人都可以查看系統統計(公開數據)
|
||||||
|
DROP POLICY IF EXISTS "System stats are viewable by everyone" ON system_stats;
|
||||||
|
CREATE POLICY "System stats are viewable by everyone" ON system_stats
|
||||||
|
FOR SELECT
|
||||||
|
USING (true);
|
||||||
|
|
||||||
|
-- 6.2 插入/更新政策:只有系統可以修改統計數據
|
||||||
|
DROP POLICY IF EXISTS "Only system can modify stats" ON system_stats;
|
||||||
|
CREATE POLICY "Only system can modify stats" ON system_stats
|
||||||
|
FOR ALL
|
||||||
|
USING (current_user = 'postgres' OR current_setting('role', true) = 'service_role');
|
||||||
|
|
||||||
|
-- 7. storage_usage 表格的 RLS 政策
|
||||||
|
|
||||||
|
-- 7.1 查看政策:所有人都可以查看存儲使用統計
|
||||||
|
DROP POLICY IF EXISTS "Storage usage is viewable by everyone" ON storage_usage;
|
||||||
|
CREATE POLICY "Storage usage is viewable by everyone" ON storage_usage
|
||||||
|
FOR SELECT
|
||||||
|
USING (true);
|
||||||
|
|
||||||
|
-- 7.2 修改政策:只有系統可以修改存儲統計
|
||||||
|
DROP POLICY IF EXISTS "Only system can modify storage usage" ON storage_usage;
|
||||||
|
CREATE POLICY "Only system can modify storage usage" ON storage_usage
|
||||||
|
FOR ALL
|
||||||
|
USING (current_user = 'postgres' OR current_setting('role', true) = 'service_role');
|
||||||
|
|
||||||
|
-- 8. storage_cleanup_log 表格的 RLS 政策
|
||||||
|
|
||||||
|
-- 8.1 查看政策:所有人都可以查看清理記錄
|
||||||
|
DROP POLICY IF EXISTS "Storage cleanup logs are viewable by everyone" ON storage_cleanup_log;
|
||||||
|
CREATE POLICY "Storage cleanup logs are viewable by everyone" ON storage_cleanup_log
|
||||||
|
FOR SELECT
|
||||||
|
USING (true);
|
135
scripts/README-CLEAR-DATA.md
Normal file
135
scripts/README-CLEAR-DATA.md
Normal file
@@ -0,0 +1,135 @@
|
|||||||
|
# 心願星河 - 數據清空指南
|
||||||
|
|
||||||
|
⚠️ **重要警告**:以下操作將永久刪除所有數據,請謹慎使用!
|
||||||
|
|
||||||
|
## 可用的清空腳本
|
||||||
|
|
||||||
|
### 1. 綜合清空腳本(推薦)
|
||||||
|
```bash
|
||||||
|
node scripts/clear-all.js
|
||||||
|
```
|
||||||
|
**功能**:一次性清空所有數據
|
||||||
|
- 清空 Supabase Storage 中的所有圖片
|
||||||
|
- 清空資料庫中的所有表格
|
||||||
|
- 重置自增序列
|
||||||
|
- 重新插入初始數據
|
||||||
|
- 驗證清空結果
|
||||||
|
|
||||||
|
### 2. 單獨清空 Storage
|
||||||
|
```bash
|
||||||
|
node scripts/clear-storage.js
|
||||||
|
```
|
||||||
|
**功能**:僅清空圖片存儲
|
||||||
|
- 清空 `wish-images` 存儲桶
|
||||||
|
- 清空 `wish-thumbnails` 存儲桶
|
||||||
|
|
||||||
|
### 3. 單獨清空資料庫
|
||||||
|
在 Supabase Dashboard 的 SQL Editor 中執行:
|
||||||
|
```sql
|
||||||
|
-- 執行 scripts/clear-all-data.sql 文件的內容
|
||||||
|
```
|
||||||
|
|
||||||
|
## 使用前準備
|
||||||
|
|
||||||
|
### 1. 確認環境變數
|
||||||
|
確保以下環境變數已正確設置(在 `.env.local` 文件中):
|
||||||
|
```env
|
||||||
|
NEXT_PUBLIC_SUPABASE_URL=your_supabase_url
|
||||||
|
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_anon_key
|
||||||
|
SUPABASE_SERVICE_ROLE_KEY=your_service_role_key # 可選,但建議設置
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 安裝依賴
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
# 或
|
||||||
|
pnpm install
|
||||||
|
```
|
||||||
|
|
||||||
|
## 使用步驟
|
||||||
|
|
||||||
|
### 方案 A:一鍵清空(推薦)
|
||||||
|
```bash
|
||||||
|
# 執行綜合清空腳本
|
||||||
|
node scripts/clear-all.js
|
||||||
|
|
||||||
|
# 腳本會顯示 10 秒倒計時,按 Ctrl+C 可以取消
|
||||||
|
```
|
||||||
|
|
||||||
|
### 方案 B:分步驟清空
|
||||||
|
```bash
|
||||||
|
# 1. 先清空 Storage
|
||||||
|
node scripts/clear-storage.js
|
||||||
|
|
||||||
|
# 2. 再清空資料庫(在 Supabase Dashboard 中執行)
|
||||||
|
# 將 scripts/clear-all-data.sql 的內容貼到 SQL Editor 中執行
|
||||||
|
```
|
||||||
|
|
||||||
|
## 清空後的檢查
|
||||||
|
|
||||||
|
### 1. 驗證 Storage
|
||||||
|
在 Supabase Dashboard → Storage 中檢查:
|
||||||
|
- `wish-images` 桶應該是空的
|
||||||
|
- `wish-thumbnails` 桶應該是空的
|
||||||
|
|
||||||
|
### 2. 驗證資料庫
|
||||||
|
在 Supabase Dashboard → Table Editor 中檢查:
|
||||||
|
- `wishes` 表應該沒有記錄
|
||||||
|
- `wish_likes` 表應該沒有記錄
|
||||||
|
- `user_settings` 表應該沒有記錄
|
||||||
|
- 其他管理表格會有基礎的初始記錄
|
||||||
|
|
||||||
|
### 3. 測試應用程式
|
||||||
|
```bash
|
||||||
|
# 重新啟動開發服務器
|
||||||
|
npm run dev
|
||||||
|
# 或
|
||||||
|
pnpm dev
|
||||||
|
```
|
||||||
|
|
||||||
|
在瀏覽器中:
|
||||||
|
1. 清除 localStorage(開發者工具 → Application → Local Storage → Clear All)
|
||||||
|
2. 重新載入頁面
|
||||||
|
3. 測試提交新的困擾案例
|
||||||
|
4. 確認功能正常運行
|
||||||
|
|
||||||
|
## 故障排除
|
||||||
|
|
||||||
|
### 1. 權限錯誤
|
||||||
|
```
|
||||||
|
Error: Insufficient permissions
|
||||||
|
```
|
||||||
|
**解決方案**:確保使用 `SUPABASE_SERVICE_ROLE_KEY` 而不是 `ANON_KEY`
|
||||||
|
|
||||||
|
### 2. 存儲桶不存在
|
||||||
|
```
|
||||||
|
Error: Bucket does not exist
|
||||||
|
```
|
||||||
|
**解決方案**:正常現象,腳本會自動跳過不存在的存儲桶
|
||||||
|
|
||||||
|
### 3. 網路錯誤
|
||||||
|
```
|
||||||
|
Error: fetch failed
|
||||||
|
```
|
||||||
|
**解決方案**:檢查網路連接和 Supabase URL 是否正確
|
||||||
|
|
||||||
|
### 4. 資料庫連接錯誤
|
||||||
|
**解決方案**:
|
||||||
|
1. 檢查 Supabase 專案是否暫停
|
||||||
|
2. 驗證 URL 和密鑰是否正確
|
||||||
|
3. 確認專案是否有足夠的配額
|
||||||
|
|
||||||
|
## 注意事項
|
||||||
|
|
||||||
|
1. **備份重要數據**:在生產環境中執行前,請先備份重要數據
|
||||||
|
2. **測試環境優先**:建議先在測試環境中驗證腳本功能
|
||||||
|
3. **瀏覽器清除**:清空數據後記得清除瀏覽器的 localStorage
|
||||||
|
4. **應用重啟**:清空後建議重新啟動應用程式
|
||||||
|
|
||||||
|
## 聯絡支援
|
||||||
|
|
||||||
|
如果遇到問題,請檢查:
|
||||||
|
1. 控制台錯誤訊息
|
||||||
|
2. Supabase Dashboard 中的 Logs
|
||||||
|
3. 網路連接狀態
|
||||||
|
4. 環境變數配置
|
@@ -1,55 +0,0 @@
|
|||||||
// 清空所有本地存儲資料的腳本
|
|
||||||
// 執行此腳本將清除所有測試數據,讓應用回到初始狀態
|
|
||||||
|
|
||||||
console.log("🧹 開始清空所有測試資料...")
|
|
||||||
|
|
||||||
// 清空的資料項目
|
|
||||||
const dataKeys = [
|
|
||||||
"wishes", // 所有許願/困擾案例
|
|
||||||
"wishLikes", // 點讚數據
|
|
||||||
"userLikedWishes", // 用戶點讚記錄
|
|
||||||
"backgroundMusicState", // 背景音樂狀態
|
|
||||||
]
|
|
||||||
|
|
||||||
let clearedCount = 0
|
|
||||||
|
|
||||||
// 清空每個資料項目
|
|
||||||
dataKeys.forEach((key) => {
|
|
||||||
const existingData = localStorage.getItem(key)
|
|
||||||
if (existingData) {
|
|
||||||
localStorage.removeItem(key)
|
|
||||||
console.log(`✅ 已清空: ${key}`)
|
|
||||||
clearedCount++
|
|
||||||
} else {
|
|
||||||
console.log(`ℹ️ ${key} 已經是空的`)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
// 顯示清理結果
|
|
||||||
console.log(`\n🎉 資料清理完成!`)
|
|
||||||
console.log(`📊 清理統計:`)
|
|
||||||
console.log(` - 清空了 ${clearedCount} 個資料項目`)
|
|
||||||
console.log(` - 檢查了 ${dataKeys.length} 個資料項目`)
|
|
||||||
|
|
||||||
// 驗證清理結果
|
|
||||||
console.log(`\n🔍 驗證清理結果:`)
|
|
||||||
dataKeys.forEach((key) => {
|
|
||||||
const data = localStorage.getItem(key)
|
|
||||||
if (data) {
|
|
||||||
console.log(`❌ ${key}: 仍有資料殘留`)
|
|
||||||
} else {
|
|
||||||
console.log(`✅ ${key}: 已完全清空`)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
console.log(`\n🚀 應用程式已準備好進行正式佈署!`)
|
|
||||||
console.log(`💡 建議接下來的步驟:`)
|
|
||||||
console.log(` 1. 重新整理頁面確認所有資料已清空`)
|
|
||||||
console.log(` 2. 測試各個功能頁面的初始狀態`)
|
|
||||||
console.log(` 3. 確認沒有錯誤訊息或異常行為`)
|
|
||||||
console.log(` 4. 準備佈署到正式環境`)
|
|
||||||
|
|
||||||
// 提供重新載入頁面的選項
|
|
||||||
if (confirm("是否要重新載入頁面以確認清理效果?")) {
|
|
||||||
window.location.reload()
|
|
||||||
}
|
|
134
scripts/clear-all-data.sql
Normal file
134
scripts/clear-all-data.sql
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
-- 心願星河 - 清空所有數據
|
||||||
|
-- ⚠️ 警告:此腳本將永久刪除所有數據,請謹慎使用!
|
||||||
|
-- 建議:在生產環境執行前請備份重要數據
|
||||||
|
|
||||||
|
-- 開始事務
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
-- 0. 修復 migration_log 表約束問題
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
-- 移除舊的約束
|
||||||
|
ALTER TABLE migration_log DROP CONSTRAINT IF EXISTS migration_log_migration_type_check;
|
||||||
|
|
||||||
|
-- 添加新的約束,包含所有需要的類型
|
||||||
|
ALTER TABLE migration_log ADD CONSTRAINT migration_log_migration_type_check
|
||||||
|
CHECK (migration_type IN ('wishes', 'likes', 'settings', 'storage_cleanup', 'data_cleanup', 'image_cleanup'));
|
||||||
|
|
||||||
|
RAISE NOTICE '🔧 migration_log 表約束已修復';
|
||||||
|
EXCEPTION
|
||||||
|
WHEN OTHERS THEN
|
||||||
|
RAISE NOTICE '⚠️ 修復約束時發生錯誤,但繼續執行: %', SQLERRM;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- 顯示警告訊息
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
RAISE NOTICE '';
|
||||||
|
RAISE NOTICE '🚨 準備清空所有數據...';
|
||||||
|
RAISE NOTICE '⚠️ 這將永久刪除:';
|
||||||
|
RAISE NOTICE ' - 所有困擾案例 (wishes)';
|
||||||
|
RAISE NOTICE ' - 所有點讚記錄 (wish_likes)';
|
||||||
|
RAISE NOTICE ' - 所有用戶設定 (user_settings)';
|
||||||
|
RAISE NOTICE ' - 遷移記錄 (migration_log)';
|
||||||
|
RAISE NOTICE ' - 系統統計 (system_stats)';
|
||||||
|
RAISE NOTICE ' - 存儲使用記錄 (storage_usage)';
|
||||||
|
RAISE NOTICE ' - 存儲清理記錄 (storage_cleanup_log)';
|
||||||
|
RAISE NOTICE '';
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- 1. 清空所有數據表(按依賴關係順序)
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
table_count INTEGER;
|
||||||
|
BEGIN
|
||||||
|
-- 清空有外鍵關係的表格
|
||||||
|
DELETE FROM wish_likes;
|
||||||
|
GET DIAGNOSTICS table_count = ROW_COUNT;
|
||||||
|
RAISE NOTICE '🗑️ 已清空 wish_likes 表,刪除 % 條記錄', table_count;
|
||||||
|
|
||||||
|
DELETE FROM wishes;
|
||||||
|
GET DIAGNOSTICS table_count = ROW_COUNT;
|
||||||
|
RAISE NOTICE '🗑️ 已清空 wishes 表,刪除 % 條記錄', table_count;
|
||||||
|
|
||||||
|
DELETE FROM user_settings;
|
||||||
|
GET DIAGNOSTICS table_count = ROW_COUNT;
|
||||||
|
RAISE NOTICE '🗑️ 已清空 user_settings 表,刪除 % 條記錄', table_count;
|
||||||
|
|
||||||
|
DELETE FROM migration_log;
|
||||||
|
GET DIAGNOSTICS table_count = ROW_COUNT;
|
||||||
|
RAISE NOTICE '🗑️ 已清空 migration_log 表,刪除 % 條記錄', table_count;
|
||||||
|
|
||||||
|
DELETE FROM system_stats;
|
||||||
|
GET DIAGNOSTICS table_count = ROW_COUNT;
|
||||||
|
RAISE NOTICE '🗑️ 已清空 system_stats 表,刪除 % 條記錄', table_count;
|
||||||
|
|
||||||
|
DELETE FROM storage_usage;
|
||||||
|
GET DIAGNOSTICS table_count = ROW_COUNT;
|
||||||
|
RAISE NOTICE '🗑️ 已清空 storage_usage 表,刪除 % 條記錄', table_count;
|
||||||
|
|
||||||
|
DELETE FROM storage_cleanup_log;
|
||||||
|
GET DIAGNOSTICS table_count = ROW_COUNT;
|
||||||
|
RAISE NOTICE '🗑️ 已清空 storage_cleanup_log 表,刪除 % 條記錄', table_count;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- 2. 重置自增序列
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
RAISE NOTICE '';
|
||||||
|
RAISE NOTICE '🔄 重置自增序列...';
|
||||||
|
|
||||||
|
-- 重置所有表格的序列
|
||||||
|
ALTER SEQUENCE wishes_id_seq RESTART WITH 1;
|
||||||
|
ALTER SEQUENCE wish_likes_id_seq RESTART WITH 1;
|
||||||
|
ALTER SEQUENCE user_settings_id_seq RESTART WITH 1;
|
||||||
|
ALTER SEQUENCE migration_log_id_seq RESTART WITH 1;
|
||||||
|
ALTER SEQUENCE system_stats_id_seq RESTART WITH 1;
|
||||||
|
ALTER SEQUENCE storage_usage_id_seq RESTART WITH 1;
|
||||||
|
ALTER SEQUENCE storage_cleanup_log_id_seq RESTART WITH 1;
|
||||||
|
|
||||||
|
RAISE NOTICE '✅ 所有序列已重置為 1';
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- 3. 重新插入初始統計記錄
|
||||||
|
INSERT INTO storage_usage (bucket_name, total_files, total_size_bytes)
|
||||||
|
VALUES
|
||||||
|
('wish-images', 0, 0),
|
||||||
|
('wish-thumbnails', 0, 0);
|
||||||
|
|
||||||
|
INSERT INTO system_stats (stat_date, total_wishes, public_wishes, private_wishes, total_likes, active_users, storage_used_mb)
|
||||||
|
VALUES (CURRENT_DATE, 0, 0, 0, 0, 0, 0);
|
||||||
|
|
||||||
|
-- 4. 記錄清空操作
|
||||||
|
INSERT INTO migration_log (
|
||||||
|
user_session,
|
||||||
|
migration_type,
|
||||||
|
target_records,
|
||||||
|
success,
|
||||||
|
error_message
|
||||||
|
) VALUES (
|
||||||
|
'system-admin',
|
||||||
|
'data_cleanup',
|
||||||
|
0,
|
||||||
|
true,
|
||||||
|
'All data cleared by admin request at ' || NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 提交事務
|
||||||
|
COMMIT;
|
||||||
|
|
||||||
|
-- 顯示完成訊息
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
RAISE NOTICE '';
|
||||||
|
RAISE NOTICE '✅ 資料庫清空完成!';
|
||||||
|
RAISE NOTICE '📊 重置統計:';
|
||||||
|
RAISE NOTICE ' - 所有表格已清空';
|
||||||
|
RAISE NOTICE ' - 自增序列已重置';
|
||||||
|
RAISE NOTICE ' - 初始統計記錄已重新建立';
|
||||||
|
RAISE NOTICE '';
|
||||||
|
RAISE NOTICE '⚠️ 注意:';
|
||||||
|
RAISE NOTICE ' - Storage 中的檔案需要手動清空';
|
||||||
|
RAISE NOTICE ' - 可以使用 clear-storage.js 腳本清空圖片';
|
||||||
|
RAISE NOTICE '';
|
||||||
|
END $$;
|
357
scripts/clear-all.js
Normal file
357
scripts/clear-all.js
Normal file
@@ -0,0 +1,357 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 心願星河 - 綜合清空腳本
|
||||||
|
*
|
||||||
|
* ⚠️ 警告:此腳本將永久刪除所有數據和文件!
|
||||||
|
*
|
||||||
|
* 功能:
|
||||||
|
* 1. 清空 Supabase Storage 中的所有圖片
|
||||||
|
* 2. 清空資料庫中的所有數據
|
||||||
|
* 3. 重置自增序列
|
||||||
|
* 4. 重新初始化基礎數據
|
||||||
|
*
|
||||||
|
* 使用方法:
|
||||||
|
* node scripts/clear-all.js
|
||||||
|
*/
|
||||||
|
|
||||||
|
const { createClient } = require('@supabase/supabase-js');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
// 載入環境變數
|
||||||
|
require('dotenv').config({ path: '.env.local' });
|
||||||
|
|
||||||
|
// Supabase 配置
|
||||||
|
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
|
||||||
|
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
|
||||||
|
|
||||||
|
// 檢查必要的環境變數
|
||||||
|
if (!supabaseUrl || !supabaseServiceKey) {
|
||||||
|
console.error('❌ 錯誤:缺少必要的環境變數');
|
||||||
|
console.error('請確保已設置以下環境變數:');
|
||||||
|
console.error('- NEXT_PUBLIC_SUPABASE_URL');
|
||||||
|
console.error('- SUPABASE_SERVICE_ROLE_KEY 或 NEXT_PUBLIC_SUPABASE_ANON_KEY');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化 Supabase 客戶端
|
||||||
|
const supabase = createClient(supabaseUrl, supabaseServiceKey);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清空存儲桶中的所有文件
|
||||||
|
*/
|
||||||
|
async function clearStorage() {
|
||||||
|
console.log('\n📁 開始清空 Storage...');
|
||||||
|
|
||||||
|
const buckets = ['wish-images', 'wish-thumbnails'];
|
||||||
|
let allSuccess = true;
|
||||||
|
|
||||||
|
for (const bucketName of buckets) {
|
||||||
|
try {
|
||||||
|
console.log(`\n🗂️ 正在處理存儲桶:${bucketName}`);
|
||||||
|
|
||||||
|
// 列出所有文件
|
||||||
|
const { data: files, error: listError } = await supabase.storage
|
||||||
|
.from(bucketName)
|
||||||
|
.list('', { limit: 1000 });
|
||||||
|
|
||||||
|
if (listError) {
|
||||||
|
if (listError.message.includes('not found') || listError.message.includes('does not exist')) {
|
||||||
|
console.log(`⚠️ 存儲桶 ${bucketName} 不存在,跳過`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
console.error(`❌ 列出 ${bucketName} 文件時出錯:`, listError.message);
|
||||||
|
allSuccess = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!files || files.length === 0) {
|
||||||
|
console.log(`✅ ${bucketName} 已經是空的`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 獲取所有文件路徑
|
||||||
|
const allFilePaths = [];
|
||||||
|
for (const file of files) {
|
||||||
|
if (file.name && file.name !== '.emptyFolderPlaceholder') {
|
||||||
|
if (!file.metadata) {
|
||||||
|
// 處理目錄
|
||||||
|
const { data: subFiles } = await supabase.storage
|
||||||
|
.from(bucketName)
|
||||||
|
.list(file.name, { limit: 1000 });
|
||||||
|
|
||||||
|
if (subFiles) {
|
||||||
|
subFiles.forEach(subFile => {
|
||||||
|
if (subFile.name && subFile.name !== '.emptyFolderPlaceholder') {
|
||||||
|
allFilePaths.push(`${file.name}/${subFile.name}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
allFilePaths.push(file.name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (allFilePaths.length === 0) {
|
||||||
|
console.log(`✅ ${bucketName} 中沒有需要刪除的文件`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`🗑️ 刪除 ${allFilePaths.length} 個文件...`);
|
||||||
|
|
||||||
|
// 批量刪除
|
||||||
|
const batchSize = 50;
|
||||||
|
for (let i = 0; i < allFilePaths.length; i += batchSize) {
|
||||||
|
const batch = allFilePaths.slice(i, i + batchSize);
|
||||||
|
const { error } = await supabase.storage.from(bucketName).remove(batch);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error(`❌ 刪除批次失敗:`, error.message);
|
||||||
|
allSuccess = false;
|
||||||
|
} else {
|
||||||
|
console.log(`✅ 已刪除 ${Math.min(i + batchSize, allFilePaths.length)}/${allFilePaths.length} 個文件`);
|
||||||
|
}
|
||||||
|
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 100));
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`❌ 處理 ${bucketName} 時發生錯誤:`, error.message);
|
||||||
|
allSuccess = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return allSuccess;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 修復 migration_log 表的約束問題
|
||||||
|
*/
|
||||||
|
async function fixMigrationLogConstraint() {
|
||||||
|
console.log('\n🔧 修復 migration_log 表約束...');
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 使用 rpc 調用執行 SQL,修復約束
|
||||||
|
const { error } = await supabase.rpc('exec_sql', {
|
||||||
|
sql_query: `
|
||||||
|
ALTER TABLE migration_log DROP CONSTRAINT IF EXISTS migration_log_migration_type_check;
|
||||||
|
ALTER TABLE migration_log ADD CONSTRAINT migration_log_migration_type_check
|
||||||
|
CHECK (migration_type IN ('wishes', 'likes', 'settings', 'storage_cleanup', 'data_cleanup', 'image_cleanup'));
|
||||||
|
`
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.log('⚠️ 無法通過 RPC 修復約束,嘗試其他方法...');
|
||||||
|
// 如果 RPC 方法失敗,我們繼續執行,但會在日誌中使用允許的類型
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('✅ migration_log 表約束已修復');
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
console.log('⚠️ 修復約束時發生錯誤,但繼續執行:', error.message);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清空資料庫數據
|
||||||
|
*/
|
||||||
|
async function clearDatabase() {
|
||||||
|
console.log('\n🗄️ 開始清空資料庫...');
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 清空有外鍵關係的表格(按依賴順序)
|
||||||
|
const tablesToClear = [
|
||||||
|
{ name: 'wish_likes', description: '點讚記錄' },
|
||||||
|
{ name: 'wishes', description: '困擾案例' },
|
||||||
|
{ name: 'user_settings', description: '用戶設定' },
|
||||||
|
{ name: 'system_stats', description: '系統統計' },
|
||||||
|
{ name: 'storage_usage', description: '存儲使用記錄' },
|
||||||
|
{ name: 'storage_cleanup_log', description: '存儲清理記錄' },
|
||||||
|
{ name: 'migration_log', description: '遷移記錄' }
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const table of tablesToClear) {
|
||||||
|
try {
|
||||||
|
const { error } = await supabase.from(table.name).delete().neq('id', 0);
|
||||||
|
if (error) {
|
||||||
|
console.error(`❌ 清空 ${table.name} (${table.description}) 表失敗:`, error.message);
|
||||||
|
// 如果不是 migration_log 表,則返回失敗
|
||||||
|
if (table.name !== 'migration_log') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// migration_log 表清空失敗可以忽略,因為我們稍後會重新插入
|
||||||
|
console.log(`⚠️ ${table.name} 表清空失敗,將在後續步驟中處理`);
|
||||||
|
} else {
|
||||||
|
console.log(`✅ 已清空 ${table.name} (${table.description}) 表`);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`❌ 處理 ${table.name} 表時發生錯誤:`, err.message);
|
||||||
|
if (table.name !== 'migration_log') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 重新插入初始數據
|
||||||
|
console.log('\n🔧 重新插入初始數據...');
|
||||||
|
|
||||||
|
// 插入初始存儲統計
|
||||||
|
await supabase.from('storage_usage').insert([
|
||||||
|
{ bucket_name: 'wish-images', total_files: 0, total_size_bytes: 0 },
|
||||||
|
{ bucket_name: 'wish-thumbnails', total_files: 0, total_size_bytes: 0 }
|
||||||
|
]);
|
||||||
|
|
||||||
|
// 插入今日初始統計
|
||||||
|
await supabase.from('system_stats').insert([{
|
||||||
|
stat_date: new Date().toISOString().split('T')[0],
|
||||||
|
total_wishes: 0,
|
||||||
|
public_wishes: 0,
|
||||||
|
private_wishes: 0,
|
||||||
|
total_likes: 0,
|
||||||
|
active_users: 0,
|
||||||
|
storage_used_mb: 0
|
||||||
|
}]);
|
||||||
|
|
||||||
|
// 記錄清空操作(最後執行,避免約束衝突)
|
||||||
|
try {
|
||||||
|
await supabase.from('migration_log').insert([{
|
||||||
|
user_session: 'system-admin',
|
||||||
|
migration_type: 'data_cleanup',
|
||||||
|
target_records: 0,
|
||||||
|
success: true,
|
||||||
|
error_message: `All data cleared by admin request at ${new Date().toISOString()}`
|
||||||
|
}]);
|
||||||
|
console.log('✅ 清空操作記錄已插入');
|
||||||
|
} catch (logError) {
|
||||||
|
console.log('⚠️ 無法插入清空操作記錄,但不影響清空結果:', logError.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('✅ 初始數據插入完成');
|
||||||
|
return true;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ 清空資料庫時發生錯誤:', error.message);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 驗證清空結果
|
||||||
|
*/
|
||||||
|
async function verifyCleanup() {
|
||||||
|
console.log('\n🔍 驗證清空結果...');
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 檢查主要數據表
|
||||||
|
const { data: wishes, error: wishesError } = await supabase
|
||||||
|
.from('wishes')
|
||||||
|
.select('count', { count: 'exact', head: true });
|
||||||
|
|
||||||
|
const { data: likes, error: likesError } = await supabase
|
||||||
|
.from('wish_likes')
|
||||||
|
.select('count', { count: 'exact', head: true });
|
||||||
|
|
||||||
|
if (wishesError || likesError) {
|
||||||
|
console.error('❌ 驗證時發生錯誤');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`📊 驗證結果:`);
|
||||||
|
console.log(` - wishes 表:${wishes || 0} 條記錄`);
|
||||||
|
console.log(` - wish_likes 表:${likes || 0} 條記錄`);
|
||||||
|
|
||||||
|
// 檢查存儲
|
||||||
|
const buckets = ['wish-images', 'wish-thumbnails'];
|
||||||
|
for (const bucket of buckets) {
|
||||||
|
const { data: files } = await supabase.storage.from(bucket).list('', { limit: 1 });
|
||||||
|
console.log(` - ${bucket} 存儲桶:${files ? files.length : 0} 個文件`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ 驗證時發生錯誤:', error.message);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 主函數
|
||||||
|
*/
|
||||||
|
async function main() {
|
||||||
|
console.log('🚀 心願星河 - 綜合數據清空');
|
||||||
|
console.log('⚠️ 警告:這將永久刪除所有數據和文件!');
|
||||||
|
console.log('\n包含:');
|
||||||
|
console.log('- 所有困擾案例和點讚記錄');
|
||||||
|
console.log('- 所有用戶設定');
|
||||||
|
console.log('- Storage 中的所有圖片文件');
|
||||||
|
console.log('- 系統統計和記錄');
|
||||||
|
|
||||||
|
// 給用戶考慮時間
|
||||||
|
console.log('\n⏰ 10 秒後開始清空... (按 Ctrl+C 取消)');
|
||||||
|
for (let i = 10; i > 0; i--) {
|
||||||
|
process.stdout.write(`\r倒計時:${i} 秒 `);
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||||
|
}
|
||||||
|
console.log('\n\n開始執行清空操作...\n');
|
||||||
|
|
||||||
|
let success = true;
|
||||||
|
|
||||||
|
// 0. 修復約束問題
|
||||||
|
const constraintFixed = await fixMigrationLogConstraint();
|
||||||
|
|
||||||
|
// 1. 清空存儲
|
||||||
|
const storageSuccess = await clearStorage();
|
||||||
|
if (!storageSuccess) {
|
||||||
|
console.log('⚠️ Storage 清空過程中有錯誤,但繼續執行資料庫清空');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 清空資料庫
|
||||||
|
const dbSuccess = await clearDatabase();
|
||||||
|
if (!dbSuccess) {
|
||||||
|
console.error('❌ 資料庫清空失敗');
|
||||||
|
success = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 驗證結果
|
||||||
|
if (success) {
|
||||||
|
await verifyCleanup();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 顯示最終結果
|
||||||
|
console.log('\n' + '='.repeat(60));
|
||||||
|
if (success) {
|
||||||
|
console.log('✅ 所有數據清空完成!');
|
||||||
|
console.log('\n📝 建議後續步驟:');
|
||||||
|
console.log('1. 重新啟動應用程式');
|
||||||
|
console.log('2. 在瀏覽器中清除 localStorage');
|
||||||
|
console.log('3. 確認應用程式正常運行');
|
||||||
|
} else {
|
||||||
|
console.log('❌ 清空過程中有錯誤,請檢查上述訊息');
|
||||||
|
}
|
||||||
|
|
||||||
|
process.exit(success ? 0 : 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 錯誤處理
|
||||||
|
process.on('unhandledRejection', (error) => {
|
||||||
|
console.error('❌ 未處理的錯誤:', error);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
process.on('SIGINT', () => {
|
||||||
|
console.log('\n❌ 用戶取消操作');
|
||||||
|
process.exit(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 執行主函數
|
||||||
|
if (require.main === module) {
|
||||||
|
main().catch(error => {
|
||||||
|
console.error('❌ 腳本執行失敗:', error);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
}
|
221
scripts/clear-storage.js
Normal file
221
scripts/clear-storage.js
Normal file
@@ -0,0 +1,221 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 心願星河 - 清空 Supabase Storage
|
||||||
|
*
|
||||||
|
* ⚠️ 警告:此腳本將永久刪除所有存儲的圖片文件!
|
||||||
|
*
|
||||||
|
* 使用方法:
|
||||||
|
* 1. 確保已安裝依賴:npm install
|
||||||
|
* 2. 設置環境變數或在 .env.local 中配置 Supabase 連接
|
||||||
|
* 3. 執行腳本:node scripts/clear-storage.js
|
||||||
|
*/
|
||||||
|
|
||||||
|
const { createClient } = require('@supabase/supabase-js');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
// 載入環境變數
|
||||||
|
require('dotenv').config({ path: '.env.local' });
|
||||||
|
|
||||||
|
// Supabase 配置
|
||||||
|
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
|
||||||
|
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
|
||||||
|
|
||||||
|
// 檢查必要的環境變數
|
||||||
|
if (!supabaseUrl || !supabaseServiceKey) {
|
||||||
|
console.error('❌ 錯誤:缺少必要的環境變數');
|
||||||
|
console.error('請確保已設置以下環境變數:');
|
||||||
|
console.error('- NEXT_PUBLIC_SUPABASE_URL');
|
||||||
|
console.error('- SUPABASE_SERVICE_ROLE_KEY 或 NEXT_PUBLIC_SUPABASE_ANON_KEY');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化 Supabase 客戶端
|
||||||
|
const supabase = createClient(supabaseUrl, supabaseServiceKey);
|
||||||
|
|
||||||
|
// 存儲桶名稱
|
||||||
|
const BUCKETS = ['wish-images', 'wish-thumbnails'];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清空指定存儲桶中的所有文件
|
||||||
|
*/
|
||||||
|
async function clearBucket(bucketName) {
|
||||||
|
try {
|
||||||
|
console.log(`\n🗂️ 正在處理存儲桶:${bucketName}`);
|
||||||
|
|
||||||
|
// 列出所有文件
|
||||||
|
const { data: files, error: listError } = await supabase.storage
|
||||||
|
.from(bucketName)
|
||||||
|
.list('', {
|
||||||
|
limit: 1000,
|
||||||
|
sortBy: { column: 'created_at', order: 'desc' }
|
||||||
|
});
|
||||||
|
|
||||||
|
if (listError) {
|
||||||
|
console.error(`❌ 列出 ${bucketName} 文件時出錯:`, listError.message);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!files || files.length === 0) {
|
||||||
|
console.log(`✅ ${bucketName} 已經是空的`);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`📊 找到 ${files.length} 個文件`);
|
||||||
|
|
||||||
|
// 獲取所有文件路徑(包括子目錄)
|
||||||
|
const allFilePaths = [];
|
||||||
|
|
||||||
|
for (const file of files) {
|
||||||
|
if (file.name && file.name !== '.emptyFolderPlaceholder') {
|
||||||
|
// 如果是目錄,遞歸獲取其中的文件
|
||||||
|
if (!file.metadata) {
|
||||||
|
const { data: subFiles, error: subListError } = await supabase.storage
|
||||||
|
.from(bucketName)
|
||||||
|
.list(file.name, { limit: 1000 });
|
||||||
|
|
||||||
|
if (!subListError && subFiles) {
|
||||||
|
subFiles.forEach(subFile => {
|
||||||
|
if (subFile.name && subFile.name !== '.emptyFolderPlaceholder') {
|
||||||
|
allFilePaths.push(`${file.name}/${subFile.name}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
allFilePaths.push(file.name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (allFilePaths.length === 0) {
|
||||||
|
console.log(`✅ ${bucketName} 中沒有需要刪除的文件`);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`🗑️ 準備刪除 ${allFilePaths.length} 個文件...`);
|
||||||
|
|
||||||
|
// 批量刪除文件
|
||||||
|
const batchSize = 50; // Supabase 建議的批量操作大小
|
||||||
|
let totalDeleted = 0;
|
||||||
|
let hasErrors = false;
|
||||||
|
|
||||||
|
for (let i = 0; i < allFilePaths.length; i += batchSize) {
|
||||||
|
const batch = allFilePaths.slice(i, i + batchSize);
|
||||||
|
|
||||||
|
const { data, error } = await supabase.storage
|
||||||
|
.from(bucketName)
|
||||||
|
.remove(batch);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error(`❌ 刪除批次 ${Math.floor(i/batchSize) + 1} 時出錯:`, error.message);
|
||||||
|
hasErrors = true;
|
||||||
|
} else {
|
||||||
|
totalDeleted += batch.length;
|
||||||
|
console.log(`✅ 已刪除批次 ${Math.floor(i/batchSize) + 1}/${Math.ceil(allFilePaths.length/batchSize)} (${batch.length} 個文件)`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 避免請求過於頻繁
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 100));
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`📊 ${bucketName} 清空完成:刪除了 ${totalDeleted}/${allFilePaths.length} 個文件`);
|
||||||
|
return !hasErrors;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`❌ 清空 ${bucketName} 時發生未預期錯誤:`, error.message);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 驗證存儲桶是否存在
|
||||||
|
*/
|
||||||
|
async function verifyBuckets() {
|
||||||
|
try {
|
||||||
|
const { data: buckets, error } = await supabase.storage.listBuckets();
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error('❌ 無法獲取存儲桶列表:', error.message);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingBuckets = buckets.map(bucket => bucket.id);
|
||||||
|
const missingBuckets = BUCKETS.filter(bucket => !existingBuckets.includes(bucket));
|
||||||
|
|
||||||
|
if (missingBuckets.length > 0) {
|
||||||
|
console.warn('⚠️ 以下存儲桶不存在,將跳過:', missingBuckets.join(', '));
|
||||||
|
return BUCKETS.filter(bucket => existingBuckets.includes(bucket));
|
||||||
|
}
|
||||||
|
|
||||||
|
return BUCKETS;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ 驗證存儲桶時發生錯誤:', error.message);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 主函數
|
||||||
|
*/
|
||||||
|
async function main() {
|
||||||
|
console.log('🚀 開始清空 Supabase Storage...');
|
||||||
|
console.log('⚠️ 警告:這將永久刪除所有存儲的圖片文件!');
|
||||||
|
|
||||||
|
// 驗證存儲桶
|
||||||
|
const bucketsToProcess = await verifyBuckets();
|
||||||
|
if (!bucketsToProcess || bucketsToProcess.length === 0) {
|
||||||
|
console.error('❌ 沒有可處理的存儲桶');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`📋 將處理 ${bucketsToProcess.length} 個存儲桶:`, bucketsToProcess.join(', '));
|
||||||
|
|
||||||
|
// 給用戶 5 秒鐘考慮時間
|
||||||
|
console.log('\n⏰ 5 秒後開始刪除... (按 Ctrl+C 取消)');
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 5000));
|
||||||
|
|
||||||
|
let allSuccess = true;
|
||||||
|
|
||||||
|
// 清空每個存儲桶
|
||||||
|
for (const bucket of bucketsToProcess) {
|
||||||
|
const success = await clearBucket(bucket);
|
||||||
|
if (!success) {
|
||||||
|
allSuccess = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 顯示最終結果
|
||||||
|
console.log('\n' + '='.repeat(50));
|
||||||
|
if (allSuccess) {
|
||||||
|
console.log('✅ 所有存儲桶清空完成!');
|
||||||
|
} else {
|
||||||
|
console.log('⚠️ 存儲桶清空完成,但過程中有一些錯誤');
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('\n📝 建議後續步驟:');
|
||||||
|
console.log('1. 在 Supabase Dashboard 中確認 Storage 已清空');
|
||||||
|
console.log('2. 執行 clear-all-data.sql 清空資料庫');
|
||||||
|
console.log('3. 重新啟動應用程式');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 錯誤處理
|
||||||
|
process.on('unhandledRejection', (error) => {
|
||||||
|
console.error('❌ 未處理的錯誤:', error);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
process.on('SIGINT', () => {
|
||||||
|
console.log('\n❌ 用戶取消操作');
|
||||||
|
process.exit(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 執行主函數
|
||||||
|
if (require.main === module) {
|
||||||
|
main().catch(error => {
|
||||||
|
console.error('❌ 腳本執行失敗:', error);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { clearBucket, verifyBuckets };
|
26
scripts/fix-migration-log-constraint.sql
Normal file
26
scripts/fix-migration-log-constraint.sql
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
-- 修復 migration_log 表的約束問題
|
||||||
|
-- 允許 'storage_cleanup' 和 'data_cleanup' 類型
|
||||||
|
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
-- 移除舊的約束
|
||||||
|
ALTER TABLE migration_log DROP CONSTRAINT IF EXISTS migration_log_migration_type_check;
|
||||||
|
|
||||||
|
-- 添加新的約束,包含所有需要的類型
|
||||||
|
ALTER TABLE migration_log ADD CONSTRAINT migration_log_migration_type_check
|
||||||
|
CHECK (migration_type IN ('wishes', 'likes', 'settings', 'storage_cleanup', 'data_cleanup', 'image_cleanup'));
|
||||||
|
|
||||||
|
-- 顯示結果
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
RAISE NOTICE '✅ migration_log 表約束已更新';
|
||||||
|
RAISE NOTICE '📋 允許的 migration_type 值:';
|
||||||
|
RAISE NOTICE ' - wishes(困擾案例遷移)';
|
||||||
|
RAISE NOTICE ' - likes(點讚記錄遷移)';
|
||||||
|
RAISE NOTICE ' - settings(用戶設定遷移)';
|
||||||
|
RAISE NOTICE ' - storage_cleanup(存儲清理)';
|
||||||
|
RAISE NOTICE ' - data_cleanup(數據清空)';
|
||||||
|
RAISE NOTICE ' - image_cleanup(圖片清理)';
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
COMMIT;
|
139
scripts/production-cleanup.js
Normal file
139
scripts/production-cleanup.js
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
// 正式環境佈署前的完整資料清理腳本
|
||||||
|
// 執行此腳本將清除所有測試資料,重置到正式環境狀態
|
||||||
|
|
||||||
|
console.log("🚀 開始準備正式環境佈署...")
|
||||||
|
console.log("=".repeat(50))
|
||||||
|
|
||||||
|
// 1. 清空所有本地存儲資料
|
||||||
|
console.log("📋 第一步:清理本地存儲資料")
|
||||||
|
|
||||||
|
const dataKeys = [
|
||||||
|
"wishes", // 所有許願/困擾案例
|
||||||
|
"wishLikes", // 點讚數據
|
||||||
|
"userLikedWishes", // 用戶點讚記錄
|
||||||
|
"backgroundMusicState", // 背景音樂狀態
|
||||||
|
]
|
||||||
|
|
||||||
|
let clearedCount = 0
|
||||||
|
let totalDataSize = 0
|
||||||
|
|
||||||
|
// 計算清理前的資料大小
|
||||||
|
dataKeys.forEach((key) => {
|
||||||
|
const data = localStorage.getItem(key)
|
||||||
|
if (data) {
|
||||||
|
totalDataSize += data.length
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
console.log(`📊 清理前資料統計:`)
|
||||||
|
console.log(` - 總資料大小: ${(totalDataSize / 1024).toFixed(2)} KB`)
|
||||||
|
|
||||||
|
// 清空每個資料項目
|
||||||
|
dataKeys.forEach((key) => {
|
||||||
|
const existingData = localStorage.getItem(key)
|
||||||
|
if (existingData) {
|
||||||
|
const dataSize = existingData.length
|
||||||
|
localStorage.removeItem(key)
|
||||||
|
console.log(`✅ 已清空: ${key} (${(dataSize / 1024).toFixed(2)} KB)`)
|
||||||
|
clearedCount++
|
||||||
|
} else {
|
||||||
|
console.log(`ℹ️ ${key} 已經是空的`)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
console.log("\n" + "=".repeat(50))
|
||||||
|
|
||||||
|
// 2. 設定正式環境的初始狀態
|
||||||
|
console.log("⚙️ 第二步:設定正式環境初始狀態")
|
||||||
|
|
||||||
|
const productionDefaults = {
|
||||||
|
wishes: [],
|
||||||
|
wishLikes: {},
|
||||||
|
userLikedWishes: [],
|
||||||
|
backgroundMusicState: {
|
||||||
|
enabled: false,
|
||||||
|
volume: 0.3,
|
||||||
|
isPlaying: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 設定初始狀態
|
||||||
|
Object.entries(productionDefaults).forEach(([key, value]) => {
|
||||||
|
localStorage.setItem(key, JSON.stringify(value))
|
||||||
|
console.log(`✅ 已設定: ${key} 初始狀態`)
|
||||||
|
})
|
||||||
|
|
||||||
|
console.log("\n" + "=".repeat(50))
|
||||||
|
|
||||||
|
// 3. 驗證清理結果
|
||||||
|
console.log("🔍 第三步:驗證清理結果")
|
||||||
|
|
||||||
|
let verificationPassed = true
|
||||||
|
|
||||||
|
dataKeys.forEach((key) => {
|
||||||
|
const data = localStorage.getItem(key)
|
||||||
|
if (data) {
|
||||||
|
const parsedData = JSON.parse(data)
|
||||||
|
|
||||||
|
// 檢查是否為空狀態
|
||||||
|
if (key === "wishes" && Array.isArray(parsedData) && parsedData.length === 0) {
|
||||||
|
console.log(`✅ ${key}: 已重置為空陣列`)
|
||||||
|
} else if (
|
||||||
|
(key === "wishLikes" || key === "userLikedWishes") &&
|
||||||
|
((Array.isArray(parsedData) && parsedData.length === 0) ||
|
||||||
|
(typeof parsedData === "object" && Object.keys(parsedData).length === 0))
|
||||||
|
) {
|
||||||
|
console.log(`✅ ${key}: 已重置為空狀態`)
|
||||||
|
} else if (key === "backgroundMusicState" && typeof parsedData === "object") {
|
||||||
|
console.log(`✅ ${key}: 已重置為預設狀態`)
|
||||||
|
} else {
|
||||||
|
console.log(`❌ ${key}: 狀態異常`)
|
||||||
|
verificationPassed = false
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.log(`❌ ${key}: 資料遺失`)
|
||||||
|
verificationPassed = false
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
console.log("\n" + "=".repeat(50))
|
||||||
|
|
||||||
|
// 4. 顯示最終結果
|
||||||
|
console.log("🎉 清理完成報告:")
|
||||||
|
console.log(`📊 清理統計:`)
|
||||||
|
console.log(` - 清空了 ${clearedCount} 個資料項目`)
|
||||||
|
console.log(` - 檢查了 ${dataKeys.length} 個資料項目`)
|
||||||
|
console.log(` - 釋放了 ${(totalDataSize / 1024).toFixed(2)} KB 空間`)
|
||||||
|
console.log(` - 驗證結果: ${verificationPassed ? "✅ 通過" : "❌ 失敗"}`)
|
||||||
|
|
||||||
|
console.log("\n🚀 正式環境準備狀態:")
|
||||||
|
console.log(" ✅ 困擾案例: 0 個")
|
||||||
|
console.log(" ✅ 點讚記錄: 已清空")
|
||||||
|
console.log(" ✅ 背景音樂: 預設關閉")
|
||||||
|
console.log(" ✅ 本地存儲: 已重置")
|
||||||
|
|
||||||
|
console.log("\n" + "=".repeat(50))
|
||||||
|
|
||||||
|
if (verificationPassed) {
|
||||||
|
console.log("🎯 佈署準備完成!")
|
||||||
|
console.log("✨ 應用程式已準備好進行正式佈署")
|
||||||
|
console.log("\n📋 建議的佈署檢查清單:")
|
||||||
|
console.log(" □ 重新整理頁面確認所有資料已清空")
|
||||||
|
console.log(" □ 測試各個功能頁面的初始狀態")
|
||||||
|
console.log(" □ 確認沒有錯誤訊息或異常行為")
|
||||||
|
console.log(" □ 檢查響應式設計在各裝置正常")
|
||||||
|
console.log(" □ 測試音效和背景音樂功能")
|
||||||
|
console.log(" □ 驗證隱私設定功能")
|
||||||
|
console.log(" □ 準備佈署到正式環境")
|
||||||
|
|
||||||
|
// 提供重新載入頁面的選項
|
||||||
|
setTimeout(() => {
|
||||||
|
if (confirm("✅ 清理完成!是否要重新載入頁面以確認效果?")) {
|
||||||
|
window.location.reload()
|
||||||
|
}
|
||||||
|
}, 2000)
|
||||||
|
} else {
|
||||||
|
console.log("⚠️ 清理過程中發現問題,請檢查後重新執行")
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("\n🌟 感謝使用心願星河!準備為用戶提供優質服務!")
|
@@ -1,42 +0,0 @@
|
|||||||
// 重置應用到正式環境狀態
|
|
||||||
// 這個腳本會清空所有測試資料並設定適合正式環境的初始狀態
|
|
||||||
|
|
||||||
console.log("🔄 正在重置應用到正式環境狀態...")
|
|
||||||
|
|
||||||
// 1. 清空所有本地存儲資料
|
|
||||||
const dataKeys = ["wishes", "wishLikes", "userLikedWishes", "backgroundMusicState"]
|
|
||||||
|
|
||||||
dataKeys.forEach((key) => {
|
|
||||||
localStorage.removeItem(key)
|
|
||||||
})
|
|
||||||
|
|
||||||
// 2. 設定正式環境的初始狀態
|
|
||||||
const productionDefaults = {
|
|
||||||
wishes: [],
|
|
||||||
wishLikes: {},
|
|
||||||
userLikedWishes: [],
|
|
||||||
backgroundMusicState: {
|
|
||||||
enabled: false,
|
|
||||||
volume: 0.3,
|
|
||||||
isPlaying: false,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
// 設定初始狀態
|
|
||||||
Object.entries(productionDefaults).forEach(([key, value]) => {
|
|
||||||
localStorage.setItem(key, JSON.stringify(value))
|
|
||||||
})
|
|
||||||
|
|
||||||
console.log("✅ 應用已重置到正式環境狀態")
|
|
||||||
console.log("📋 初始狀態設定:")
|
|
||||||
console.log(" - 困擾案例: 0 個")
|
|
||||||
console.log(" - 點讚記錄: 已清空")
|
|
||||||
console.log(" - 背景音樂: 預設關閉")
|
|
||||||
|
|
||||||
console.log("\n🎯 正式環境準備完成!")
|
|
||||||
console.log("🚀 可以開始佈署了")
|
|
||||||
|
|
||||||
// 重新載入頁面
|
|
||||||
setTimeout(() => {
|
|
||||||
window.location.reload()
|
|
||||||
}, 2000)
|
|
137
scripts/test-supabase-connection.js
Normal file
137
scripts/test-supabase-connection.js
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
// 心願星河 - Supabase 連接測試腳本
|
||||||
|
// 使用方法: npm run test-supabase
|
||||||
|
|
||||||
|
const { createClient } = require("@supabase/supabase-js")
|
||||||
|
require("dotenv").config({ path: ".env.local" })
|
||||||
|
|
||||||
|
async function testSupabaseConnection() {
|
||||||
|
console.log("🔍 測試 Supabase 連接...\n")
|
||||||
|
|
||||||
|
// 檢查環境變數
|
||||||
|
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
|
||||||
|
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
|
||||||
|
|
||||||
|
if (!supabaseUrl || !supabaseKey) {
|
||||||
|
console.error("❌ 環境變數未設置")
|
||||||
|
console.log("請確認 .env.local 檔案中包含:")
|
||||||
|
console.log("- NEXT_PUBLIC_SUPABASE_URL")
|
||||||
|
console.log("- NEXT_PUBLIC_SUPABASE_ANON_KEY")
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("✅ 環境變數已設置")
|
||||||
|
console.log(`📍 Supabase URL: ${supabaseUrl}`)
|
||||||
|
console.log(`🔑 API Key: ${supabaseKey.substring(0, 20)}...`)
|
||||||
|
|
||||||
|
// 創建 Supabase 客戶端
|
||||||
|
const supabase = createClient(supabaseUrl, supabaseKey)
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 測試基本連接
|
||||||
|
console.log("\n🔗 測試基本連接...")
|
||||||
|
const { data, error } = await supabase.from("wishes").select("count").limit(1)
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error("❌ 連接失敗:", error.message)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("✅ 基本連接成功")
|
||||||
|
|
||||||
|
// 測試表格存在性
|
||||||
|
console.log("\n📊 檢查表格結構...")
|
||||||
|
const tables = ["wishes", "wish_likes", "user_settings", "migration_log", "system_stats"]
|
||||||
|
|
||||||
|
for (const table of tables) {
|
||||||
|
try {
|
||||||
|
const { data, error } = await supabase.from(table).select("*").limit(1)
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.log(`❌ 表格 ${table}: ${error.message}`)
|
||||||
|
} else {
|
||||||
|
console.log(`✅ 表格 ${table}: 正常`)
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.log(`❌ 表格 ${table}: ${err.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 測試視圖
|
||||||
|
console.log("\n👁️ 檢查視圖...")
|
||||||
|
const views = ["wishes_with_likes", "public_wishes", "popular_wishes"]
|
||||||
|
|
||||||
|
for (const view of views) {
|
||||||
|
try {
|
||||||
|
const { data, error } = await supabase.from(view).select("*").limit(1)
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.log(`❌ 視圖 ${view}: ${error.message}`)
|
||||||
|
} else {
|
||||||
|
console.log(`✅ 視圖 ${view}: 正常`)
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.log(`❌ 視圖 ${view}: ${err.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 測試函數
|
||||||
|
console.log("\n⚙️ 測試函數...")
|
||||||
|
try {
|
||||||
|
const { data, error } = await supabase.rpc("get_wishes_stats")
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.log(`❌ 函數 get_wishes_stats: ${error.message}`)
|
||||||
|
} else {
|
||||||
|
console.log("✅ 函數 get_wishes_stats: 正常")
|
||||||
|
console.log("📈 統計數據:", JSON.stringify(data, null, 2))
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.log(`❌ 函數測試失敗: ${err.message}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 測試存儲
|
||||||
|
console.log("\n🗂️ 檢查存儲桶...")
|
||||||
|
try {
|
||||||
|
const { data: buckets, error } = await supabase.storage.listBuckets()
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.log(`❌ 存儲桶檢查失敗: ${error.message}`)
|
||||||
|
} else {
|
||||||
|
const wishBuckets = buckets.filter((bucket) => bucket.id === "wish-images" || bucket.id === "wish-thumbnails")
|
||||||
|
|
||||||
|
if (wishBuckets.length === 2) {
|
||||||
|
console.log("✅ 存儲桶設置完成")
|
||||||
|
wishBuckets.forEach((bucket) => {
|
||||||
|
console.log(` - ${bucket.id}: ${bucket.public ? "公開" : "私密"}`)
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
console.log(`⚠️ 存儲桶不完整,找到 ${wishBuckets.length}/2 個`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.log(`❌ 存儲桶檢查失敗: ${err.message}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("\n🎉 Supabase 連接測試完成!")
|
||||||
|
return true
|
||||||
|
} catch (error) {
|
||||||
|
console.error("❌ 測試過程中發生錯誤:", error)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 執行測試
|
||||||
|
testSupabaseConnection()
|
||||||
|
.then((success) => {
|
||||||
|
if (success) {
|
||||||
|
console.log("\n✅ 所有測試通過,可以開始使用 Supabase!")
|
||||||
|
process.exit(0)
|
||||||
|
} else {
|
||||||
|
console.log("\n❌ 測試失敗,請檢查配置")
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.error("測試腳本執行失敗:", error)
|
||||||
|
process.exit(1)
|
||||||
|
})
|
91
setup-supabase.sh
Normal file
91
setup-supabase.sh
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# 心願星河 - Supabase 快速設置腳本
|
||||||
|
# 使用方法: chmod +x setup-supabase.sh && ./setup-supabase.sh
|
||||||
|
|
||||||
|
echo "🚀 心願星河 - Supabase 整合設置開始..."
|
||||||
|
|
||||||
|
# 檢查 Node.js
|
||||||
|
if ! command -v node &> /dev/null; then
|
||||||
|
echo "❌ 請先安裝 Node.js"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 檢查 npm
|
||||||
|
if ! command -v npm &> /dev/null; then
|
||||||
|
echo "❌ 請先安裝 npm"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "✅ Node.js 和 npm 已安裝"
|
||||||
|
|
||||||
|
# 安裝依賴
|
||||||
|
echo "📦 安裝專案依賴..."
|
||||||
|
npm install
|
||||||
|
|
||||||
|
# 安裝 Supabase 客戶端
|
||||||
|
echo "📦 安裝 Supabase 客戶端..."
|
||||||
|
npm install @supabase/supabase-js
|
||||||
|
|
||||||
|
# 檢查環境變數檔案
|
||||||
|
if [ ! -f ".env.local" ]; then
|
||||||
|
if [ -f ".env.local.example" ]; then
|
||||||
|
echo "📝 複製環境變數範本..."
|
||||||
|
cp .env.local.example .env.local
|
||||||
|
echo "⚠️ 請編輯 .env.local 檔案,填入你的 Supabase 配置"
|
||||||
|
else
|
||||||
|
echo "📝 創建環境變數檔案..."
|
||||||
|
cat > .env.local << EOF
|
||||||
|
# Supabase 配置
|
||||||
|
NEXT_PUBLIC_SUPABASE_URL=your_supabase_project_url
|
||||||
|
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key
|
||||||
|
|
||||||
|
# 可選:Supabase Service Role Key
|
||||||
|
SUPABASE_SERVICE_ROLE_KEY=your_service_role_key
|
||||||
|
EOF
|
||||||
|
echo "⚠️ 請編輯 .env.local 檔案,填入你的 Supabase 配置"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo "✅ .env.local 檔案已存在"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 檢查 SQL 腳本
|
||||||
|
echo "🗄️ 檢查 SQL 腳本..."
|
||||||
|
sql_files=(
|
||||||
|
"scripts/01-create-tables.sql"
|
||||||
|
"scripts/02-create-indexes.sql"
|
||||||
|
"scripts/03-create-views-functions.sql"
|
||||||
|
"scripts/04-setup-storage.sql"
|
||||||
|
"scripts/05-setup-rls.sql"
|
||||||
|
)
|
||||||
|
|
||||||
|
missing_files=()
|
||||||
|
for file in "${sql_files[@]}"; do
|
||||||
|
if [ ! -f "$file" ]; then
|
||||||
|
missing_files+=("$file")
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ ${#missing_files[@]} -eq 0 ]; then
|
||||||
|
echo "✅ 所有 SQL 腳本檔案都存在"
|
||||||
|
else
|
||||||
|
echo "❌ 缺少以下 SQL 腳本檔案:"
|
||||||
|
for file in "${missing_files[@]}"; do
|
||||||
|
echo " - $file"
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "🎉 設置完成!"
|
||||||
|
echo ""
|
||||||
|
echo "📋 下一步操作:"
|
||||||
|
echo "1. 前往 https://supabase.com/dashboard 創建新項目"
|
||||||
|
echo "2. 編輯 .env.local 檔案,填入 Supabase 配置"
|
||||||
|
echo "3. 在 Supabase SQL Editor 中按順序執行 SQL 腳本:"
|
||||||
|
for i in "${!sql_files[@]}"; do
|
||||||
|
echo " $((i+1)). ${sql_files[$i]}"
|
||||||
|
done
|
||||||
|
echo "4. 執行 npm run dev 測試本地環境"
|
||||||
|
echo "5. 部署到 Vercel: npx vercel --prod"
|
||||||
|
echo ""
|
||||||
|
echo "📖 詳細說明請參考 SUPABASE-COMPLETE-SETUP.md"
|
@@ -1,17 +1,14 @@
|
|||||||
import type { Config } from "tailwindcss"
|
/** @type {import('tailwindcss').Config} */
|
||||||
import defaultConfig from "shadcn/ui/tailwind.config"
|
const config = {
|
||||||
|
darkMode: ["class"],
|
||||||
const config: Config = {
|
|
||||||
...defaultConfig,
|
|
||||||
content: [
|
content: [
|
||||||
...defaultConfig.content,
|
|
||||||
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
|
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
|
||||||
"./components/**/*.{js,ts,jsx,tsx,mdx}",
|
"./components/**/*.{js,ts,jsx,tsx,mdx}",
|
||||||
"./app/**/*.{js,ts,jsx,tsx,mdx}",
|
"./app/**/*.{js,ts,jsx,tsx,mdx}",
|
||||||
"*.{js,ts,jsx,tsx,mdx}",
|
"*.{js,ts,jsx,tsx,mdx}",
|
||||||
],
|
],
|
||||||
|
prefix: "",
|
||||||
theme: {
|
theme: {
|
||||||
...defaultConfig.theme,
|
|
||||||
container: {
|
container: {
|
||||||
center: true,
|
center: true,
|
||||||
padding: "2rem",
|
padding: "2rem",
|
||||||
@@ -20,7 +17,6 @@ const config: Config = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
extend: {
|
extend: {
|
||||||
...defaultConfig.theme.extend,
|
|
||||||
colors: {
|
colors: {
|
||||||
border: "hsl(var(--border))",
|
border: "hsl(var(--border))",
|
||||||
input: "hsl(var(--input))",
|
input: "hsl(var(--input))",
|
||||||
@@ -55,6 +51,23 @@ const config: Config = {
|
|||||||
DEFAULT: "hsl(var(--card))",
|
DEFAULT: "hsl(var(--card))",
|
||||||
foreground: "hsl(var(--card-foreground))",
|
foreground: "hsl(var(--card-foreground))",
|
||||||
},
|
},
|
||||||
|
sidebar: {
|
||||||
|
DEFAULT: "hsl(var(--sidebar-background))",
|
||||||
|
foreground: "hsl(var(--sidebar-foreground))",
|
||||||
|
primary: "hsl(var(--sidebar-primary))",
|
||||||
|
"primary-foreground": "hsl(var(--sidebar-primary-foreground))",
|
||||||
|
accent: "hsl(var(--sidebar-accent))",
|
||||||
|
"accent-foreground": "hsl(var(--sidebar-accent-foreground))",
|
||||||
|
border: "hsl(var(--sidebar-border))",
|
||||||
|
ring: "hsl(var(--sidebar-ring))",
|
||||||
|
},
|
||||||
|
chart: {
|
||||||
|
"1": "hsl(var(--chart-1))",
|
||||||
|
"2": "hsl(var(--chart-2))",
|
||||||
|
"3": "hsl(var(--chart-3))",
|
||||||
|
"4": "hsl(var(--chart-4))",
|
||||||
|
"5": "hsl(var(--chart-5))",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
borderRadius: {
|
borderRadius: {
|
||||||
lg: "var(--radius)",
|
lg: "var(--radius)",
|
||||||
@@ -173,7 +186,7 @@ const config: Config = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
plugins: [...defaultConfig.plugins, require("tailwindcss-animate")],
|
plugins: [require("tailwindcss-animate")],
|
||||||
} satisfies Config
|
}
|
||||||
|
|
||||||
export default config
|
export default config
|
||||||
|
Reference in New Issue
Block a user