docs: 添加完整的项目文档和说明文件

This commit is contained in:
patdelphi
2025-08-18 09:20:15 +08:00
parent db343a096e
commit 5e87725cde
6 changed files with 2402 additions and 40 deletions

441
docs/API.md Normal file
View File

@@ -0,0 +1,441 @@
# API 文档
本文档描述了三算命平台的后端API接口所有API都基于Supabase Edge Functions实现。
## 基础信息
- **Base URL**: `https://your-project.supabase.co/functions/v1`
- **认证方式**: Bearer Token (Supabase JWT)
- **数据格式**: JSON
- **字符编码**: UTF-8
## 通用响应格式
### 成功响应
```json
{
"data": {
"record_id": "uuid",
"analysis": {
// 分析结果数据
}
}
}
```
### 错误响应
```json
{
"error": {
"code": "ERROR_CODE",
"message": "错误描述信息"
}
}
```
## 认证
所有API请求都需要在请求头中包含认证信息
```http
Authorization: Bearer <your-jwt-token>
Content-Type: application/json
```
## API 接口
### 1. 八字命理分析
**接口地址**: `POST /bazi-analyzer`
**请求参数**:
```json
{
"user_id": "string",
"birth_data": {
"name": "string",
"birth_date": "YYYY-MM-DD",
"birth_time": "HH:MM",
"gender": "male|female",
"birth_place": "string"
}
}
```
**响应示例**:
```json
{
"data": {
"record_id": "123e4567-e89b-12d3-a456-426614174000",
"analysis": {
"bazi": {
"year": "甲子",
"month": "丙寅",
"day": "戊辰",
"hour": "庚申"
},
"wuxing": {
"wood": 2,
"fire": 1,
"earth": 2,
"metal": 2,
"water": 1
},
"analysis": {
"character": "性格分析内容",
"career": "事业分析内容",
"wealth": "财运分析内容",
"health": "健康分析内容",
"relationships": "感情分析内容"
}
}
}
}
```
### 2. 紫微斗数分析
**接口地址**: `POST /ziwei-analyzer`
**请求参数**:
```json
{
"user_id": "string",
"birth_data": {
"name": "string",
"birth_date": "YYYY-MM-DD",
"birth_time": "HH:MM",
"gender": "male|female",
"birth_place": "string"
}
}
```
**响应示例**:
```json
{
"data": {
"record_id": "123e4567-e89b-12d3-a456-426614174000",
"analysis": {
"ziwei": {
"ming_gong": "子",
"ming_gong_xing": ["紫微", "天机"],
"shi_er_gong": {
"命宫": {
"branch": "子",
"main_stars": ["紫微", "天机"],
"interpretation": "命宫解读内容"
}
// ... 其他宫位
},
"si_hua": {
"hua_lu": {
"star": "廉贞",
"meaning": "财禄亨通,运势顺遂"
},
"hua_quan": {
"star": "破军",
"meaning": "权力地位,事业有成"
},
"hua_ke": {
"star": "武曲",
"meaning": "贵人相助,学业有成"
},
"hua_ji": {
"star": "太阳",
"meaning": "需要谨慎,防范风险"
}
}
},
"analysis": {
"character": {
"overview": "性格概述",
"personality_traits": "性格特质"
},
"career": {
"suitable_industries": ["行业1", "行业2"],
"career_advice": "事业建议"
},
"wealth": {
"wealth_pattern": "财富模式"
},
"health": {
"constitution": "体质分析",
"wellness_advice": "健康建议"
},
"relationships": {
"marriage_fortune": "婚姻运势",
"spouse_characteristics": "伴侣特质"
}
}
}
}
}
```
### 3. 易经占卜分析
**接口地址**: `POST /yijing-analyzer`
**请求参数**:
```json
{
"user_id": "string",
"divination_data": {
"question": "string",
"method": "梅花易数时间起卦法",
"divination_time": "YYYY-MM-DDTHH:MM:SSZ"
}
}
```
**响应示例**:
```json
{
"data": {
"record_id": "123e4567-e89b-12d3-a456-426614174000",
"analysis": {
"basic_info": {
"divination_data": {
"question": "占卜问题",
"method": "梅花易数时间起卦法",
"divination_time": "2024-01-01T12:00:00Z"
},
"hexagram_info": {
"main_hexagram": "乾为天",
"hexagram_description": "卦辞内容",
"upper_trigram": "乾",
"lower_trigram": "乾",
"detailed_interpretation": "详细解释"
}
},
"detailed_analysis": {
"hexagram_analysis": {
"primary_meaning": "主要含义",
"judgment": "吉凶断语",
"image": "象辞解释"
},
"changing_lines_analysis": {
"changing_line_position": "六二",
"line_meaning": "爻辞含义"
},
"changing_hexagram": {
"name": "变卦名称",
"meaning": "变卦含义",
"transformation_insight": "变化启示"
}
},
"life_guidance": {
"overall_fortune": "整体运势",
"career_guidance": "事业指导",
"relationship_guidance": "情感指导",
"wealth_guidance": "财运指导"
},
"divination_wisdom": {
"key_message": "核心信息",
"action_advice": "行动建议",
"philosophical_insight": "哲学启示"
}
}
}
}
```
### 4. 五行分析
**接口地址**: `POST /bazi-wuxing-analysis`
**请求参数**:
```json
{
"user_id": "string",
"birth_data": {
"name": "string",
"birth_date": "YYYY-MM-DD",
"birth_time": "HH:MM",
"gender": "male|female"
}
}
```
**响应示例**:
```json
{
"data": {
"record_id": "123e4567-e89b-12d3-a456-426614174000",
"analysis": {
"wuxing_distribution": {
"wood": 2,
"fire": 1,
"earth": 2,
"metal": 2,
"water": 1
},
"balance_analysis": {
"dominant_element": "wood",
"lacking_element": "fire",
"balance_score": 75
},
"recommendations": {
"colors": ["红色", "橙色"],
"directions": ["南方"],
"career_fields": ["文化教育", "艺术创作"],
"lifestyle_advice": "生活建议内容"
}
}
}
}
```
### 5. 八字详细分析
**接口地址**: `POST /bazi-details`
**请求参数**:
```json
{
"user_id": "string",
"birth_data": {
"name": "string",
"birth_date": "YYYY-MM-DD",
"birth_time": "HH:MM",
"gender": "male|female",
"birth_place": "string"
}
}
```
**响应示例**:
```json
{
"data": {
"record_id": "123e4567-e89b-12d3-a456-426614174000",
"analysis": {
"basic_info": {
"bazi": {
"year": "甲子",
"month": "丙寅",
"day": "戊辰",
"hour": "庚申"
},
"solar_terms": "立春后",
"lunar_info": {
"lunar_date": "农历日期",
"lunar_month": "农历月份"
}
},
"detailed_analysis": {
"daymaster_analysis": "日主分析",
"pattern_analysis": "格局分析",
"useful_god": "用神分析",
"taboo_god": "忌神分析"
},
"life_stages": {
"childhood": "童年运势",
"youth": "青年运势",
"middle_age": "中年运势",
"old_age": "晚年运势"
},
"annual_fortune": [
{
"year": 2024,
"fortune": "年运分析",
"advice": "建议事项"
}
]
}
}
}
```
## 错误代码
| 错误代码 | 描述 | HTTP状态码 |
|---------|------|----------|
| INVALID_JSON | 请求JSON格式错误 | 400 |
| MISSING_PARAMETERS | 缺少必需参数 | 400 |
| INVALID_DATE_FORMAT | 日期格式错误 | 400 |
| INVALID_TIME_FORMAT | 时间格式错误 | 400 |
| UNAUTHORIZED | 未授权访问 | 401 |
| FORBIDDEN | 禁止访问 | 403 |
| ANALYSIS_ERROR | 分析过程错误 | 500 |
| DATABASE_ERROR | 数据库操作错误 | 500 |
| INTERNAL_ERROR | 内部服务器错误 | 500 |
## 使用示例
### JavaScript/TypeScript
```typescript
import { createClient } from '@supabase/supabase-js'
const supabase = createClient(
'https://your-project.supabase.co',
'your-anon-key'
)
// 八字分析示例
async function analyzeBazi(birthData: any) {
const { data, error } = await supabase.functions.invoke('bazi-analyzer', {
body: {
user_id: 'user-uuid',
birth_data: birthData
}
})
if (error) {
console.error('分析失败:', error)
return null
}
return data
}
// 使用示例
const result = await analyzeBazi({
name: '张三',
birth_date: '1990-01-01',
birth_time: '12:00',
gender: 'male',
birth_place: '北京市'
})
```
### cURL
```bash
# 八字分析
curl -X POST 'https://your-project.supabase.co/functions/v1/bazi-analyzer' \
-H 'Authorization: Bearer YOUR_JWT_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"user_id": "user-uuid",
"birth_data": {
"name": "张三",
"birth_date": "1990-01-01",
"birth_time": "12:00",
"gender": "male",
"birth_place": "北京市"
}
}'
```
## 注意事项
1. **请求频率限制**: 每个用户每分钟最多50次请求
2. **数据格式**: 所有日期使用ISO 8601格式 (YYYY-MM-DD)
3. **时间格式**: 使用24小时制 (HH:MM)
4. **字符编码**: 所有文本数据使用UTF-8编码
5. **数据安全**: 敏感信息会被加密存储
6. **缓存策略**: 相同参数的分析结果会被缓存24小时
## 更新日志
### v1.0.0 (2024-01-01)
- 初始版本发布
- 支持八字命理、紫微斗数、易经占卜三大分析功能
- 完整的用户认证和数据存储功能
---
如有疑问或需要技术支持请通过GitHub Issues联系我们。

521
docs/DEPLOYMENT.md Normal file
View File

@@ -0,0 +1,521 @@
# 部署指南
本文档详细说明如何将三算命平台部署到各种环境中。
## 目录
- [环境要求](#环境要求)
- [Supabase 配置](#supabase-配置)
- [前端部署](#前端部署)
- [Vercel 部署](#vercel-部署)
- [Netlify 部署](#netlify-部署)
- [GitHub Pages 部署](#github-pages-部署)
- [自托管部署](#自托管部署)
- [Edge Functions 部署](#edge-functions-部署)
- [环境变量配置](#环境变量配置)
- [域名配置](#域名配置)
- [SSL 证书](#ssl-证书)
- [监控和日志](#监控和日志)
- [故障排除](#故障排除)
## 环境要求
### 开发环境
- Node.js >= 18.0.0
- pnpm >= 8.0.0 (推荐) 或 npm >= 9.0.0
- Git >= 2.0.0
### 生产环境
- 支持静态文件托管的服务器或CDN
- Supabase 项目 (后端服务)
- 域名 (可选)
- SSL 证书 (推荐)
## Supabase 配置
### 1. 创建 Supabase 项目
1. 访问 [Supabase](https://supabase.com) 并创建账户
2. 创建新项目
3. 等待项目初始化完成
4. 记录项目URL和API密钥
### 2. 数据库设置
在 Supabase SQL 编辑器中执行以下SQL创建必要的表
```sql
-- 创建用户资料表
CREATE TABLE IF NOT EXISTS user_profiles (
id UUID REFERENCES auth.users(id) PRIMARY KEY,
username TEXT UNIQUE,
full_name TEXT,
avatar_url TEXT,
birth_date DATE,
birth_time TIME,
birth_place TEXT,
gender TEXT CHECK (gender IN ('male', 'female')),
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- 创建命理分析记录表
CREATE TABLE IF NOT EXISTS numerology_readings (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
user_id UUID REFERENCES auth.users(id) NOT NULL,
reading_type TEXT NOT NULL CHECK (reading_type IN ('bazi', 'ziwei', 'yijing', 'wuxing')),
name TEXT,
birth_date DATE,
birth_time TIME,
gender TEXT CHECK (gender IN ('male', 'female')),
birth_place TEXT,
input_data JSONB,
results JSONB,
analysis JSONB,
status TEXT DEFAULT 'pending' CHECK (status IN ('pending', 'processing', 'completed', 'failed')),
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- 创建索引
CREATE INDEX IF NOT EXISTS idx_numerology_readings_user_id ON numerology_readings(user_id);
CREATE INDEX IF NOT EXISTS idx_numerology_readings_type ON numerology_readings(reading_type);
CREATE INDEX IF NOT EXISTS idx_numerology_readings_created_at ON numerology_readings(created_at DESC);
-- 启用行级安全策略
ALTER TABLE user_profiles ENABLE ROW LEVEL SECURITY;
ALTER TABLE numerology_readings ENABLE ROW LEVEL SECURITY;
-- 用户资料访问策略
CREATE POLICY "Users can view own profile" ON user_profiles
FOR SELECT USING (auth.uid() = id);
CREATE POLICY "Users can update own profile" ON user_profiles
FOR UPDATE USING (auth.uid() = id);
CREATE POLICY "Users can insert own profile" ON user_profiles
FOR INSERT WITH CHECK (auth.uid() = id);
-- 命理分析记录访问策略
CREATE POLICY "Users can view own readings" ON numerology_readings
FOR SELECT USING (auth.uid() = user_id);
CREATE POLICY "Users can insert own readings" ON numerology_readings
FOR INSERT WITH CHECK (auth.uid() = user_id);
CREATE POLICY "Users can update own readings" ON numerology_readings
FOR UPDATE USING (auth.uid() = user_id);
```
### 3. 认证设置
1. 在 Supabase 控制台中,转到 "Authentication" > "Settings"
2. 配置站点URL为你的域名
3. 启用邮箱确认 (可选)
4. 配置第三方登录提供商 (可选)
## 前端部署
### Vercel 部署
Vercel 是推荐的部署平台,提供优秀的性能和开发体验。
#### 自动部署 (推荐)
1. 将代码推送到 GitHub 仓库
2. 访问 [Vercel](https://vercel.com) 并登录
3. 点击 "New Project"
4. 导入你的 GitHub 仓库
5. 配置环境变量:
```
VITE_SUPABASE_URL=your_supabase_project_url
VITE_SUPABASE_ANON_KEY=your_supabase_anon_key
```
6. 点击 "Deploy"
#### 手动部署
```bash
# 安装 Vercel CLI
npm i -g vercel
# 登录 Vercel
vercel login
# 构建项目
npm run build
# 部署
vercel --prod
```
### Netlify 部署
#### 自动部署
1. 将代码推送到 GitHub 仓库
2. 访问 [Netlify](https://netlify.com) 并登录
3. 点击 "New site from Git"
4. 选择你的 GitHub 仓库
5. 配置构建设置:
- Build command: `npm run build`
- Publish directory: `dist`
6. 配置环境变量
7. 点击 "Deploy site"
#### 手动部署
```bash
# 安装 Netlify CLI
npm install -g netlify-cli
# 构建项目
npm run build
# 部署
netlify deploy --prod --dir=dist
```
### GitHub Pages 部署
1. 在项目根目录创建 `.github/workflows/deploy.yml`
```yaml
name: Deploy to GitHub Pages
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build
run: npm run build
env:
VITE_SUPABASE_URL: ${{ secrets.VITE_SUPABASE_URL }}
VITE_SUPABASE_ANON_KEY: ${{ secrets.VITE_SUPABASE_ANON_KEY }}
- name: Deploy to GitHub Pages
uses: peaceiris/actions-gh-pages@v3
if: github.ref == 'refs/heads/main'
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./dist
```
2. 在 GitHub 仓库设置中配置 Secrets
3. 启用 GitHub Pages
### 自托管部署
#### 使用 Nginx
1. 构建项目:
```bash
npm run build
```
2. 将 `dist` 目录上传到服务器
3. 配置 Nginx
```nginx
server {
listen 80;
server_name your-domain.com;
root /path/to/your/dist;
index index.html;
# 处理 SPA 路由
location / {
try_files $uri $uri/ /index.html;
}
# 静态资源缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# 安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
}
```
#### 使用 Apache
1. 在 `dist` 目录创建 `.htaccess` 文件:
```apache
RewriteEngine On
RewriteBase /
# 处理 SPA 路由
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
# 静态资源缓存
<FilesMatch "\.(js|css|png|jpg|jpeg|gif|ico|svg)$">
ExpiresActive On
ExpiresDefault "access plus 1 year"
</FilesMatch>
```
## Edge Functions 部署
### 1. 准备 Edge Functions
在 Supabase 项目中创建以下 Edge Functions
- `bazi-analyzer` - 八字命理分析
- `ziwei-analyzer` - 紫微斗数分析
- `yijing-analyzer` - 易经占卜分析
- `bazi-wuxing-analysis` - 五行分析
- `bazi-details` - 八字详细分析
### 2. 部署 Edge Functions
```bash
# 安装 Supabase CLI
npm install -g supabase
# 登录 Supabase
supabase login
# 链接到你的项目
supabase link --project-ref your-project-ref
# 部署所有函数
supabase functions deploy
# 或部署单个函数
supabase functions deploy bazi-analyzer
```
### 3. 设置环境变量
```bash
# 为 Edge Functions 设置环境变量
supabase secrets set SUPABASE_URL=your_supabase_url
supabase secrets set SUPABASE_SERVICE_ROLE_KEY=your_service_role_key
```
## 环境变量配置
### 开发环境 (.env.local)
```env
VITE_SUPABASE_URL=https://your-project.supabase.co
VITE_SUPABASE_ANON_KEY=your_anon_key
```
### 生产环境
根据部署平台配置相应的环境变量:
- **Vercel**: 在项目设置中添加环境变量
- **Netlify**: 在站点设置中添加环境变量
- **GitHub Actions**: 在仓库 Secrets 中添加
- **自托管**: 在构建脚本中设置
## 域名配置
### 1. DNS 设置
根据部署平台配置 DNS 记录:
- **Vercel**: 添加 CNAME 记录指向 `cname.vercel-dns.com`
- **Netlify**: 添加 CNAME 记录指向 Netlify 提供的域名
- **自托管**: 添加 A 记录指向服务器 IP
### 2. 自定义域名
在部署平台的控制台中添加自定义域名,并等待 DNS 传播完成。
## SSL 证书
大多数现代部署平台都会自动提供 SSL 证书:
- **Vercel**: 自动提供 Let's Encrypt 证书
- **Netlify**: 自动提供 Let's Encrypt 证书
- **GitHub Pages**: 支持自定义域名的 HTTPS
对于自托管,可以使用 Certbot 获取免费的 Let's Encrypt 证书:
```bash
# 安装 Certbot
sudo apt install certbot python3-certbot-nginx
# 获取证书
sudo certbot --nginx -d your-domain.com
# 设置自动续期
sudo crontab -e
# 添加以下行:
0 12 * * * /usr/bin/certbot renew --quiet
```
## 监控和日志
### 1. 应用监控
推荐使用以下监控服务:
- **Vercel Analytics**: Vercel 内置分析
- **Google Analytics**: 网站流量分析
- **Sentry**: 错误监控和性能监控
### 2. Supabase 监控
在 Supabase 控制台中可以查看:
- API 使用情况
- 数据库性能
- Edge Functions 日志
- 认证统计
### 3. 日志配置
在生产环境中启用适当的日志级别:
```typescript
// 生产环境日志配置
if (import.meta.env.PROD) {
console.log = () => {} // 禁用 console.log
console.warn = () => {} // 禁用 console.warn
// 保留 console.error 用于错误报告
}
```
## 故障排除
### 常见问题
#### 1. 构建失败
**问题**: 构建过程中出现错误
**解决方案**:
- 检查 Node.js 版本是否符合要求
- 清除缓存:`rm -rf node_modules package-lock.json && npm install`
- 检查环境变量是否正确配置
#### 2. 路由不工作
**问题**: SPA 路由在生产环境中不工作
**解决方案**:
- 确保服务器配置了正确的回退规则
- 检查 `vite.config.ts` 中的 base 配置
#### 3. API 调用失败
**问题**: 无法连接到 Supabase
**解决方案**:
- 检查环境变量是否正确
- 验证 Supabase URL 和 API 密钥
- 检查网络连接和 CORS 设置
#### 4. 认证问题
**问题**: 用户无法登录或注册
**解决方案**:
- 检查 Supabase 认证设置
- 验证站点 URL 配置
- 检查邮箱确认设置
### 性能优化
#### 1. 代码分割
```typescript
// 使用动态导入进行代码分割
const AnalysisPage = lazy(() => import('./pages/AnalysisPage'))
const HistoryPage = lazy(() => import('./pages/HistoryPage'))
```
#### 2. 图片优化
- 使用 WebP 格式
- 实现懒加载
- 使用 CDN 加速
#### 3. 缓存策略
```nginx
# Nginx 缓存配置
location ~* \.(js|css)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
location ~* \.(png|jpg|jpeg|gif|ico|svg)$ {
expires 6M;
add_header Cache-Control "public";
}
```
## 安全检查清单
- [ ] 启用 HTTPS
- [ ] 配置安全头
- [ ] 启用 Supabase RLS
- [ ] 验证环境变量安全
- [ ] 定期更新依赖
- [ ] 配置 CSP 策略
- [ ] 启用错误监控
- [ ] 设置备份策略
## 维护和更新
### 1. 定期更新
```bash
# 检查过时的依赖
npm outdated
# 更新依赖
npm update
# 安全审计
npm audit
npm audit fix
```
### 2. 数据库维护
- 定期备份数据库
- 监控数据库性能
- 清理过期数据
- 优化查询性能
### 3. 监控和告警
设置适当的监控和告警机制:
- 应用错误率
- 响应时间
- 数据库连接
- 磁盘空间使用
---
如需更多帮助,请查看我们的 [FAQ](FAQ.md) 或在 GitHub Issues 中提问。

1070
docs/DEVELOPMENT.md Normal file

File diff suppressed because it is too large Load Diff