17 KiB
17 KiB
DramaLing 後端開發計劃文件
📋 文件摘要
- 版本: 1.0.0
- 日期: 2025-01-16
- 作者: DramaLing Development Team
- 狀態: 初稿
📚 引用文件
1. 專案概述
1.1 目標
建立一個可擴展、高效能的後端系統,支援 DramaLing 英語學習平台的所有核心功能。
1.2 技術棧確認
根據 技術需求規格書 1.2節:
- API Framework: Next.js 14 API Routes
- Database: Supabase (PostgreSQL)
- Authentication: Supabase Auth
- File Storage: Supabase Storage
- AI Service: Google Gemini API
- Cache: Redis (Upstash) - 待確認
1.3 開發原則
- API First 設計
- RESTful 架構
- 錯誤處理標準化
- 安全性優先
- 可測試性設計
2. 資料庫設計
2.1 資料模型更新
基於 技術需求規格書 2.1節 和 功能需求規格書,需要擴展以下資料表:
-- 用戶擴展表
users_profile (
id UUID PRIMARY KEY,
user_id UUID REFERENCES auth.users(id),
username VARCHAR(20) UNIQUE,
avatar_url TEXT,
learning_streak INTEGER DEFAULT 0,
last_study_date DATE,
daily_goal INTEGER DEFAULT 10,
subscription_tier VARCHAR(20) DEFAULT 'free',
subscription_expires_at TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
)
-- 詞卡詳細資料表(更新)
flashcards (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES auth.users(id),
deck_id UUID REFERENCES decks(id),
word VARCHAR(255) NOT NULL,
part_of_speech VARCHAR(50),
pronunciation_ipa TEXT,
definition_en TEXT,
translation_zh TEXT,
example_sentence TEXT,
example_translation TEXT,
example_image_url TEXT,
synonyms TEXT[], -- Array of synonyms
antonyms TEXT[],
difficulty_cefr VARCHAR(2), -- A1, A2, B1, B2, C1, C2
-- SM-2 Algorithm fields
ease_factor DECIMAL DEFAULT 2.5,
interval_days INTEGER DEFAULT 1,
repetitions INTEGER DEFAULT 0,
next_review_date DATE DEFAULT CURRENT_DATE,
-- Metadata
is_favorite BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
deleted_at TIMESTAMP -- Soft delete
)
-- 卡組表(新增)
decks (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES auth.users(id),
name VARCHAR(255) NOT NULL,
description TEXT,
cover_image_url TEXT,
is_public BOOLEAN DEFAULT FALSE,
cards_count INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
)
-- 學習記錄表(更新)
study_sessions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES auth.users(id),
flashcard_id UUID REFERENCES flashcards(id),
deck_id UUID REFERENCES decks(id),
study_mode VARCHAR(50), -- flip, quiz, fill, listening, speaking
rating INTEGER, -- 1-5 for SM-2
time_spent_seconds INTEGER,
is_correct BOOLEAN,
studied_at TIMESTAMP DEFAULT NOW()
)
-- AI 生成記錄表(新增)
ai_generation_logs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES auth.users(id),
input_text TEXT,
input_type VARCHAR(50), -- manual, screenshot
extraction_type VARCHAR(50), -- vocabulary, smart
generated_cards_count INTEGER,
tokens_used INTEGER,
created_at TIMESTAMP DEFAULT NOW()
)
-- 錯誤回報表(新增)
error_reports (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES auth.users(id),
flashcard_id UUID REFERENCES flashcards(id),
test_mode VARCHAR(50),
error_reason TEXT,
status VARCHAR(20) DEFAULT 'pending', -- pending, reviewing, resolved
resolved_at TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW()
)
-- 每日統計表(新增)
daily_stats (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES auth.users(id),
date DATE NOT NULL,
cards_studied INTEGER DEFAULT 0,
cards_new INTEGER DEFAULT 0,
cards_reviewed INTEGER DEFAULT 0,
study_time_minutes INTEGER DEFAULT 0,
UNIQUE(user_id, date)
)
2.2 索引策略
-- Performance indexes
CREATE INDEX idx_flashcards_user_deck ON flashcards(user_id, deck_id);
CREATE INDEX idx_flashcards_next_review ON flashcards(user_id, next_review_date);
CREATE INDEX idx_study_sessions_user_date ON study_sessions(user_id, studied_at);
CREATE INDEX idx_daily_stats_user_date ON daily_stats(user_id, date DESC);
3. API 端點設計
3.1 認證相關 API
根據 功能需求規格書 1.1節:
// /api/auth/register
POST /api/auth/register
Body: {
email: string,
password: string,
username: string
}
Response: {
user: User,
session: Session
}
// /api/auth/login
POST /api/auth/login
Body: {
email: string,
password: string,
remember_me?: boolean
}
// /api/auth/google
POST /api/auth/google
Body: {
id_token: string
}
// /api/auth/reset-password
POST /api/auth/reset-password
Body: {
email: string
}
3.2 詞卡管理 API
根據 功能需求規格書 1.3節:
// 卡組 CRUD
GET /api/decks // 獲取用戶所有卡組
POST /api/decks // 創建新卡組
GET /api/decks/:id // 獲取單個卡組詳情
PUT /api/decks/:id // 更新卡組
DELETE /api/decks/:id // 刪除卡組
// 詞卡 CRUD
GET /api/flashcards // 獲取詞卡列表(支援篩選)
POST /api/flashcards // 創建新詞卡
GET /api/flashcards/:id // 獲取單個詞卡
PUT /api/flashcards/:id // 更新詞卡
DELETE /api/flashcards/:id // 刪除詞卡(軟刪除)
POST /api/flashcards/batch // 批量操作
// 標籤管理
GET /api/tags // 獲取所有標籤
POST /api/tags // 創建標籤
DELETE /api/tags/:id // 刪除標籤
3.3 AI 生成 API
根據 功能需求規格書 1.2節:
// AI 詞卡生成
POST /api/ai/generate
Body: {
input_text?: string,
input_type: 'manual' | 'screenshot',
extraction_type: 'vocabulary' | 'smart',
difficulty?: string, // A1-C2
count?: number // 5-20
}
Response: {
cards: FlashCard[],
usage: {
tokens_used: number,
credits_remaining: number
}
}
// 智能檢測
POST /api/ai/check
Body: {
flashcard_id?: string,
error_report_ids?: string[]
}
Response: {
corrections: {
flashcard_id: string,
field: string,
original: string,
corrected: string,
reason: string
}[]
}
3.4 學習系統 API
根據 功能需求規格書 1.4節:
// 獲取今日複習詞卡
GET /api/study/today
Response: {
review_cards: FlashCard[], // 需要複習的
new_cards: FlashCard[] // 新學習的
}
// 記錄學習結果
POST /api/study/record
Body: {
flashcard_id: string,
rating: 1-5,
study_mode: string,
time_spent: number
}
// 錯誤回報
POST /api/study/report-error
Body: {
flashcard_id: string,
test_mode: string,
error_reason?: string
}
3.5 統計分析 API
根據 功能需求規格書 1.5節:
// 學習統計
GET /api/stats/overview // 總覽數據
GET /api/stats/daily?days=30 // 每日統計
GET /api/stats/progress // 學習進度
GET /api/stats/achievements // 成就系統
4. 實作細節
4.1 認證系統實作
使用 Supabase Auth:
// lib/supabase/auth.ts
import { createServerClient } from '@supabase/ssr'
export async function registerUser(email: string, password: string, username: string) {
const supabase = createServerClient()
// 1. 註冊用戶
const { data: authData, error: authError } = await supabase.auth.signUp({
email,
password,
options: {
data: { username }
}
})
// 2. 創建用戶 profile
if (authData?.user) {
await supabase.from('users_profile').insert({
user_id: authData.user.id,
username,
avatar_url: authData.user.user_metadata.avatar_url
})
}
return { data: authData, error: authError }
}
4.2 SM-2 算法實作
根據 功能需求規格書 1.4.1節:
// lib/sm2/algorithm.ts
export function calculateNextReview(
rating: number,
currentEaseFactor: number,
currentInterval: number,
repetitions: number
) {
let easeFactor = currentEaseFactor
let interval = currentInterval
let reps = repetitions
if (rating >= 3) {
// 正確回答
if (reps === 0) {
interval = 1
} else if (reps === 1) {
interval = 6
} else {
interval = Math.round(interval * easeFactor)
}
reps += 1
// 調整難度係數
easeFactor = easeFactor + (0.1 - (5 - rating) * (0.08 + (5 - rating) * 0.02))
if (easeFactor < 1.3) easeFactor = 1.3
} else {
// 錯誤回答,重置
reps = 0
interval = 1
easeFactor = Math.max(1.3, easeFactor - 0.2)
}
return {
interval,
easeFactor,
repetitions: reps,
nextReviewDate: new Date(Date.now() + interval * 24 * 60 * 60 * 1000)
}
}
4.3 AI 整合實作
// lib/ai/gemini.ts
import { GoogleGenerativeAI } from '@google/generative-ai'
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!)
export async function generateFlashcards(
text: string,
options: GenerateOptions
) {
const model = genAI.getGenerativeModel({ model: 'gemini-pro' })
const prompt = buildPrompt(text, options)
const result = await model.generateContent(prompt)
return parseAIResponse(result.response.text())
}
function buildPrompt(text: string, options: GenerateOptions) {
return `
Extract vocabulary from the following text and create flashcards.
Requirements:
- Difficulty level: ${options.difficulty || 'B1'}
- Number of cards: ${options.count || 10}
- Include: word, part of speech, IPA pronunciation, English definition (A1-A2 level),
Chinese translation, example sentence, synonyms
Text: ${text}
Return in JSON format.
`
}
5. 開發階段
Phase 1: 基礎設施 (第1週)
- Supabase 專案設置
- 資料庫 Schema 建立
- 環境變數配置
- 基礎 API 路由架構
- 錯誤處理中間件
- CORS 設置
Phase 2: 認證系統 (第1-2週)
- Email 註冊/登入 API
- Google OAuth 整合
- Session 管理
- 密碼重設功能
- 用戶 Profile CRUD
- Rate limiting 實作
Phase 3: 核心功能 API (第2-3週)
- 卡組管理 API
- 詞卡 CRUD API
- 標籤系統 API
- 批量操作 API
- 搜尋篩選 API
- 軟刪除與回收站
Phase 4: AI 整合 (第3-4週)
- Gemini API 整合
- 詞彙萃取邏輯
- 智能萃取功能
- 錯誤檢測 API
- Token 使用追蹤
- 快取機制
Phase 5: 學習系統 (第4-5週)
- SM-2 算法實作
- 今日學習 API
- 學習記錄 API
- 複習排程邏輯
- 錯誤回報系統
- 學習提醒功能
Phase 6: 統計與分析 (第5-6週)
- 統計數據聚合
- 圖表數據 API
- 成就系統邏輯
- 學習報告生成
- 資料匯出功能
Phase 7: 優化與測試 (第6-7週)
- API 效能優化
- 資料庫查詢優化
- 快取策略實作
- 單元測試
- 整合測試
- 壓力測試
Phase 8: 部署與監控 (第7-8週)
- 生產環境配置
- CI/CD 設置
- 監控系統
- 日誌管理
- 備份策略
- 文檔完善
6. 技術債務與待確認項目
6.1 待確認
- Redis 快取是否使用 Upstash
- Email 服務選擇 (Resend vs SendGrid)
- 檔案上傳大小限制
- API Rate Limiting 具體數值
- 訂閱方案定價策略
6.2 技術債務
- 從 mock data 遷移到真實資料庫
- 實作真實的圖片生成服務
- 音頻 TTS 服務整合
- 支付系統整合
- 多語言支援
7. 安全考量
根據 技術需求規格書 4節:
7.1 實作清單
- Supabase Row Level Security (RLS) 規則
- API 輸入驗證 (Zod)
- SQL Injection 防護 (參數化查詢)
- XSS Protection Headers
- CORS 白名單設置
- 環境變數加密
- API Key 輪替機制
- 錯誤訊息標準化(不洩漏敏感資訊)
7.2 合規性
- GDPR 用戶資料導出
- 用戶資料刪除(真刪除)
- 隱私政策 API
- 使用條款同意記錄
8. 監控指標
根據 技術需求規格書 8節:
8.1 關鍵指標
- API 回應時間 (P50, P95, P99)
- 錯誤率 (4xx, 5xx)
- 資料庫連線池使用率
- AI API 使用量與成本
- 活躍用戶數 (DAU, MAU)
- 學習完成率
8.2 告警設置
- API 回應時間 > 1s
- 錯誤率 > 1%
- 資料庫連線池 > 80%
- AI API 配額 > 80%
9. 測試策略
9.1 測試類型
- 單元測試: 業務邏輯、工具函數
- 整合測試: API 端點、資料庫操作
- E2E 測試: 關鍵用戶流程
- 負載測試: 併發處理能力
9.2 測試覆蓋率目標
- 整體覆蓋率: > 70%
- 關鍵路徑: 100%
- API 端點: > 90%
- 工具函數: 100%
10. 文檔需求
10.1 API 文檔
- OpenAPI/Swagger 規範
- Postman Collection
- 範例程式碼
- 錯誤碼對照表
10.2 開發文檔
- 資料庫 ER Diagram
- 系統架構圖
- 部署指南
- 環境設置指南
11. 風險評估
11.1 技術風險
- Gemini API 限制: 準備備用 AI 服務 (OpenAI)
- Supabase 免費層限制: 監控使用量,準備升級方案
- 圖片儲存成本: 實作圖片壓縮與 CDN 快取
11.2 時程風險
- AI 整合複雜度: 預留額外時間進行調試
- SM-2 算法調優: 需要實際用戶數據進行優化
- 第三方服務整合: 預留 buffer 處理 API 變更
12. 下一步行動
立即執行 (本週)
- 設置 Supabase 專案
- 建立資料庫 Schema
- 實作基礎認證 API
- 設置開發環境
短期目標 (2週內)
- 完成所有 CRUD API
- 整合 Gemini API
- 實作 SM-2 算法
- 基礎測試覆蓋
中期目標 (4週內)
- 完成所有功能 API
- 效能優化
- 完整測試套件
- 準備部署
附錄
A. 技術參考資料
B. 相關規格文件
C. 前端實作參考
已實作頁面清單
- 首頁 - 登入前的 Landing Page
- 登入頁 - 用戶登入界面
- 註冊頁 - 用戶註冊界面
- 儀表板 - 用戶主頁與學習概覽
- AI 生成 - AI 詞卡生成功能
- 詞卡管理 - 詞卡與卡組管理
- 學習頁面 - 學習模式實作(翻卡、測驗等)
前端資料結構參考
從前端實作可以參考的重要資料結構和業務邏輯:
-
詞卡資料結構 (/app/flashcards/page.tsx)
- word, partOfSpeech, pronunciation
- definition, translation
- example, exampleTranslation, exampleImage
- synonyms[], difficulty (CEFR)
- nextReview, easeFactor
-
學習模式 (/app/learn/page.tsx)
- flip (翻卡), quiz (選擇題), fill (填空)
- listening (聽力), speaking (口說)
- 評分系統: 1-5 分對應不同的記憶強度
-
AI 生成參數 (/app/generate/page.tsx)
- mode: 'manual' | 'screenshot'
- extractionType: 'vocabulary' | 'smart'
- difficulty: A1-C2 (CEFR 等級)
- 用戶權限區分 (free/premium)
-
錯誤回報系統 (/app/learn/page.tsx)
- 每個測驗模式都有錯誤回報功能
- 包含 flashcard_id, test_mode, error_reason
-
智能檢測功能 (/app/flashcards/page.tsx)
- 單一詞彙檢測
- 批量錯誤檢測
- 自動修正建議