初始化项目结构和基础模块
完成内容: - 创建前后端项目目录结构 - 初始化 Node.js + TypeScript 后端项目 (Fastify) - 初始化 Vue 3 + TypeScript 前端项目 (Vite) - 配置 Prisma ORM 和 MySQL 数据库 - 创建数据库 Schema 和种子数据 - 实现后端基础模块 (配置、日志、错误处理、验证) - 创建基础服务类 (BaseService) - 配置 Git 仓库和忽略文件 技术栈: - 后端:Fastify + Prisma + MySQL + Winston - 前端:Vue 3 + TypeScript + Element Plus + Pinia Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
commit
830a17bf46
53 files changed
+16893
No files matched your search
+29
@@ -0,0 +1,29 @@
|
|||||||
|
# 依赖
|
||||||
|
node_modules/
|
||||||
|
|
||||||
|
# 构建产物
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
|
||||||
|
# 环境变量
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
|
||||||
|
# 日志
|
||||||
|
*.log
|
||||||
|
logs/
|
||||||
|
|
||||||
|
# 编辑器
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
|
||||||
|
# 系统文件
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# PM2
|
||||||
|
.pm2/
|
||||||
|
.claude/
|
||||||
|
nul
|
||||||
@@ -0,0 +1,430 @@
|
|||||||
|
# News Aggregator - 项目总览
|
||||||
|
|
||||||
|
基于配置的资讯聚合系统,自动收集、整理、推送每日报告。
|
||||||
|
|
||||||
|
## 项目状态
|
||||||
|
|
||||||
|
**当前阶段**:设计完成,准备开始实施
|
||||||
|
|
||||||
|
**已完成**:
|
||||||
|
- ✅ 产品需求分析
|
||||||
|
- ✅ 产品逻辑架构设计
|
||||||
|
- ✅ 技术架构设计
|
||||||
|
- ✅ 数据库设计
|
||||||
|
- ✅ 任务拆分(任务 01-09)
|
||||||
|
|
||||||
|
**进行中**:
|
||||||
|
- 🔄 后端开发(任务 01-09)
|
||||||
|
|
||||||
|
**待开始**:
|
||||||
|
- ⏳ 前端开发(任务 10-14)
|
||||||
|
- ⏳ AI Agent 开发(任务 15)
|
||||||
|
- ⏳ 部署配置(任务 16)
|
||||||
|
|
||||||
|
## 快速导航
|
||||||
|
|
||||||
|
### 📋 文档
|
||||||
|
- [产品需求文档](./docs/requirements/product-requirements.md)
|
||||||
|
- [产品逻辑架构](./docs/designs/product-architecture.md)
|
||||||
|
- [技术架构](./docs/designs/technical-architecture.md)
|
||||||
|
- [数据库设计](./docs/designs/database-design.md)
|
||||||
|
|
||||||
|
### 📝 任务清单
|
||||||
|
- [任务总览](./docs/tasks/README.md)
|
||||||
|
- [任务 01:项目初始化](./docs/tasks/01-project-setup.md)
|
||||||
|
- [任务 02:数据库搭建](./docs/tasks/02-database-setup.md)
|
||||||
|
- [任务 03:后端核心框架](./docs/tasks/03-backend-core.md)
|
||||||
|
- [任务 04:采集器实现](./docs/tasks/04-collectors.md)
|
||||||
|
- [任务 05:内容处理](./docs/tasks/05-processor.md)
|
||||||
|
- [任务 06:报告生成](./docs/tasks/06-report-generator.md)
|
||||||
|
- [任务 07:分发器实现](./docs/tasks/07-distributors.md)
|
||||||
|
- [任务 08:定时任务调度](./docs/tasks/08-scheduler.md)
|
||||||
|
- [任务 09:Web API 实现](./docs/tasks/09-web-api.md)
|
||||||
|
|
||||||
|
## 核心功能
|
||||||
|
|
||||||
|
### 🔍 多数据源采集
|
||||||
|
- API 采集器:支持通用 REST API
|
||||||
|
- Playwright 采集器:支持网页爬取
|
||||||
|
- RSS 采集器:支持 RSS/Atom 订阅
|
||||||
|
- 可配置采集频率
|
||||||
|
|
||||||
|
### 🤖 AI 内容处理
|
||||||
|
- 简单聚合:列出标题和链接
|
||||||
|
- AI 摘要:为每条资讯生成摘要
|
||||||
|
- AI 深度整理:分析、去重、归纳要点
|
||||||
|
|
||||||
|
### 📊 报告生成
|
||||||
|
- 按主题独立生成报告
|
||||||
|
- 支持定时自动生成
|
||||||
|
- 支持手动触发生成
|
||||||
|
- 灵活的时间范围配置
|
||||||
|
|
||||||
|
### 📤 多渠道推送
|
||||||
|
- 邮件推送
|
||||||
|
- 钉钉机器人
|
||||||
|
- 企业微信机器人
|
||||||
|
- Slack 推送
|
||||||
|
|
||||||
|
### 💬 AI Agent 深入探索
|
||||||
|
- 基于报告/资讯的对话
|
||||||
|
- 自动获取更多信息
|
||||||
|
- 联网搜索补充内容
|
||||||
|
|
||||||
|
### 🎛️ Web 管理界面
|
||||||
|
- 配置管理(LLM、数据源、渠道、主题)
|
||||||
|
- 报告查看和浏览
|
||||||
|
- 资讯浏览和筛选
|
||||||
|
- 采集监控和日志
|
||||||
|
|
||||||
|
## 技术栈
|
||||||
|
|
||||||
|
### 后端
|
||||||
|
- **运行时**:Node.js 20+
|
||||||
|
- **语言**:TypeScript 5.x
|
||||||
|
- **Web 框架**:Fastify
|
||||||
|
- **ORM**:Prisma
|
||||||
|
- **数据库**:MySQL 5.6
|
||||||
|
- **定时任务**:node-cron
|
||||||
|
- **网页爬取**:Playwright
|
||||||
|
- **LLM**:OpenAI SDK
|
||||||
|
|
||||||
|
### 前端
|
||||||
|
- **框架**:Vue 3
|
||||||
|
- **语言**:TypeScript 5.x
|
||||||
|
- **构建工具**:Vite
|
||||||
|
- **UI 组件**:Element Plus
|
||||||
|
- **状态管理**:Pinia
|
||||||
|
- **HTTP 客户端**:Axios
|
||||||
|
|
||||||
|
### 部署
|
||||||
|
- **进程管理**:PM2
|
||||||
|
- **容器化**:Docker(可选)
|
||||||
|
|
||||||
|
## 项目结构
|
||||||
|
|
||||||
|
```
|
||||||
|
news-aggregator/
|
||||||
|
├── backend/ # 后端代码
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── app.ts # 应用入口
|
||||||
|
│ │ ├── config/ # 配置
|
||||||
|
│ │ ├── web/ # Web 层(路由、中间件)
|
||||||
|
│ │ ├── services/ # 业务服务
|
||||||
|
│ │ ├── collectors/ # 采集器
|
||||||
|
│ │ ├── distributors/ # 分发器
|
||||||
|
│ │ ├── utils/ # 工具函数
|
||||||
|
│ │ └── types/ # 类型定义
|
||||||
|
│ ├── prisma/ # 数据库模型
|
||||||
|
│ └── package.json
|
||||||
|
├── frontend/ # 前端代码
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── main.ts # 应用入口
|
||||||
|
│ │ ├── router/ # 路由
|
||||||
|
│ │ ├── stores/ # 状态管理
|
||||||
|
│ │ ├── views/ # 页面组件
|
||||||
|
│ │ ├── components/ # 公共组件
|
||||||
|
│ │ ├── api/ # API 请求
|
||||||
|
│ │ └── types/ # 类型定义
|
||||||
|
│ └── package.json
|
||||||
|
├── docs/ # 文档
|
||||||
|
│ ├── requirements/ # 需求文档
|
||||||
|
│ ├── designs/ # 设计文档
|
||||||
|
│ └── tasks/ # 任务文档
|
||||||
|
└── README.md
|
||||||
|
```
|
||||||
|
|
||||||
|
## 开始开发
|
||||||
|
|
||||||
|
### 环境要求
|
||||||
|
- Node.js 20+
|
||||||
|
- MySQL 5.6+
|
||||||
|
- PM2(生产环境)
|
||||||
|
|
||||||
|
### 安装依赖
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 后端
|
||||||
|
cd backend
|
||||||
|
npm install
|
||||||
|
|
||||||
|
# 前端
|
||||||
|
cd frontend
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
### 配置环境变量
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
cp .env.example .env
|
||||||
|
# 编辑 .env 文件,配置数据库连接等
|
||||||
|
```
|
||||||
|
|
||||||
|
### 初始化数据库
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
npm run prisma:migrate
|
||||||
|
npm run prisma:seed
|
||||||
|
```
|
||||||
|
|
||||||
|
### 启动开发服务
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 后端
|
||||||
|
cd backend
|
||||||
|
npm run dev
|
||||||
|
|
||||||
|
# 前端(新终端)
|
||||||
|
cd frontend
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
### 访问应用
|
||||||
|
|
||||||
|
- 后端 API:http://localhost:3000
|
||||||
|
- 前端界面:http://localhost:5173
|
||||||
|
- Prisma Studio:`npm run prisma:studio`
|
||||||
|
|
||||||
|
## 开发指南
|
||||||
|
|
||||||
|
### 开发流程
|
||||||
|
1. 阅读相关文档(需求、设计、任务)
|
||||||
|
2. 按任务文档步骤实现功能
|
||||||
|
3. 运行验证步骤测试功能
|
||||||
|
4. 提交代码并继续下一个任务
|
||||||
|
|
||||||
|
### 代码规范
|
||||||
|
- 使用 TypeScript 严格模式
|
||||||
|
- 遵循 ESLint 规则
|
||||||
|
- 编写清晰的注释
|
||||||
|
- 保持代码简洁
|
||||||
|
|
||||||
|
### 提交规范
|
||||||
|
```
|
||||||
|
<type>: <subject>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
|
||||||
|
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
|
||||||
|
```
|
||||||
|
|
||||||
|
类型:
|
||||||
|
- feat: 新功能
|
||||||
|
- fix: 修复
|
||||||
|
- docs: 文档
|
||||||
|
- style: 格式
|
||||||
|
- refactor: 重构
|
||||||
|
- test: 测试
|
||||||
|
- chore: 构建/工具
|
||||||
|
|
||||||
|
## 常用命令
|
||||||
|
|
||||||
|
### 后端
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 开发
|
||||||
|
npm run dev # 启动开发服务器
|
||||||
|
npm run build # 构建生产版本
|
||||||
|
npm run start # 启动生产服务器
|
||||||
|
|
||||||
|
# 数据库
|
||||||
|
npm run prisma:generate # 生成 Prisma Client
|
||||||
|
npm run prisma:migrate # 执行数据库迁移
|
||||||
|
npm run prisma:studio # 打开 Prisma Studio
|
||||||
|
npm run prisma:seed # 执行种子数据
|
||||||
|
|
||||||
|
# 调度器
|
||||||
|
npm run scheduler:start # 启动调度器
|
||||||
|
npm run scheduler:status # 查看调度任务状态
|
||||||
|
```
|
||||||
|
|
||||||
|
### 前端
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 开发
|
||||||
|
npm run dev # 启动开发服务器
|
||||||
|
npm run build # 构建生产版本
|
||||||
|
npm run preview # 预览生产构建
|
||||||
|
```
|
||||||
|
|
||||||
|
## 部署
|
||||||
|
|
||||||
|
### 使用 PM2
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 构建
|
||||||
|
cd backend
|
||||||
|
npm run build
|
||||||
|
|
||||||
|
# 启动
|
||||||
|
pm2 start ecosystem.config.js
|
||||||
|
|
||||||
|
# 管理
|
||||||
|
pm2 status # 查看状态
|
||||||
|
pm2 logs news-aggregator # 查看日志
|
||||||
|
pm2 restart news-aggregator # 重启
|
||||||
|
pm2 stop news-aggregator # 停止
|
||||||
|
```
|
||||||
|
|
||||||
|
### 使用 Docker
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 构建镜像
|
||||||
|
docker-compose build
|
||||||
|
|
||||||
|
# 启动服务
|
||||||
|
docker-compose up -d
|
||||||
|
|
||||||
|
# 查看日志
|
||||||
|
docker-compose logs -f
|
||||||
|
|
||||||
|
# 停止服务
|
||||||
|
docker-compose down
|
||||||
|
```
|
||||||
|
|
||||||
|
## 功能演示
|
||||||
|
|
||||||
|
### 1. 配置数据源
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 使用 API 创建数据源
|
||||||
|
curl -X POST http://localhost:3000/api/sources \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{
|
||||||
|
"name": "Hacker News",
|
||||||
|
"type": "api",
|
||||||
|
"config": {...},
|
||||||
|
"cronExpression": "0 */6 * * *",
|
||||||
|
"enabled": true
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 配置主题
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 创建主题并关联数据源
|
||||||
|
curl -X POST http://localhost:3000/api/topics \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{
|
||||||
|
"name": "科技资讯",
|
||||||
|
"processMode": "summary",
|
||||||
|
"scheduleConfig": {...},
|
||||||
|
"sourceIds": [1],
|
||||||
|
"channelIds": [1]
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 生成报告
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 手动触发报告生成
|
||||||
|
curl -X POST http://localhost:3000/api/topics/1/generate-report
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 查看报告
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 获取报告列表
|
||||||
|
curl http://localhost:3000/api/reports
|
||||||
|
|
||||||
|
# 获取报告详情
|
||||||
|
curl http://localhost:3000/api/reports/1
|
||||||
|
```
|
||||||
|
|
||||||
|
## 监控和日志
|
||||||
|
|
||||||
|
### 查看日志
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 应用日志
|
||||||
|
tail -f logs/out.log
|
||||||
|
|
||||||
|
# 错误日志
|
||||||
|
tail -f logs/error.log
|
||||||
|
|
||||||
|
# PM2 日志
|
||||||
|
pm2 logs news-aggregator
|
||||||
|
```
|
||||||
|
|
||||||
|
### 监控指标
|
||||||
|
|
||||||
|
- 数据源采集成功率
|
||||||
|
- 报告生成成功率
|
||||||
|
- 推送成功率
|
||||||
|
- API 响应时间
|
||||||
|
|
||||||
|
## 故障排查
|
||||||
|
|
||||||
|
### 常见问题
|
||||||
|
|
||||||
|
#### 1. 数据库连接失败
|
||||||
|
- 检查 MySQL 服务是否运行
|
||||||
|
- 检查 `.env` 中的数据库配置
|
||||||
|
- 检查数据库用户权限
|
||||||
|
|
||||||
|
#### 2. 采集失败
|
||||||
|
- 查看采集日志
|
||||||
|
- 检查数据源配置
|
||||||
|
- 检查网络连接
|
||||||
|
|
||||||
|
#### 3. 报告生成失败
|
||||||
|
- 检查 LLM 配置
|
||||||
|
- 查看错误日志
|
||||||
|
- 确认有足够的资讯数据
|
||||||
|
|
||||||
|
#### 4. 推送失败
|
||||||
|
- 检查推送渠道配置
|
||||||
|
- 验证 webhook 地址
|
||||||
|
- 查看推送日志
|
||||||
|
|
||||||
|
## 贡献指南
|
||||||
|
|
||||||
|
### 提交 Issue
|
||||||
|
- 使用清晰的标题
|
||||||
|
- 提供详细的描述
|
||||||
|
- 附上错误日志
|
||||||
|
- 说明复现步骤
|
||||||
|
|
||||||
|
### 提交 Pull Request
|
||||||
|
- Fork 项目
|
||||||
|
- 创建功能分支
|
||||||
|
- 编写清晰的提交信息
|
||||||
|
- 确保测试通过
|
||||||
|
- 提交 PR
|
||||||
|
|
||||||
|
## 路线图
|
||||||
|
|
||||||
|
### v1.0(MVP)
|
||||||
|
- [x] 核心采集功能
|
||||||
|
- [x] 报告生成
|
||||||
|
- [x] 多渠道推送
|
||||||
|
- [x] Web API
|
||||||
|
- [ ] Web 管理界面
|
||||||
|
|
||||||
|
### v2.0
|
||||||
|
- [ ] AI Agent 深入探索
|
||||||
|
- [ ] 更多数据源类型
|
||||||
|
- [ ] 更多推送渠道
|
||||||
|
- [ ] 报告模板自定义
|
||||||
|
|
||||||
|
### v3.0
|
||||||
|
- [ ] 多用户支持
|
||||||
|
- [ ] 权限管理
|
||||||
|
- [ ] 数据分析和统计
|
||||||
|
- [ ] 移动端应用
|
||||||
|
|
||||||
|
## 许可证
|
||||||
|
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
## 联系方式
|
||||||
|
|
||||||
|
- 项目地址:[GitHub Repository]
|
||||||
|
- 问题反馈:[GitHub Issues]
|
||||||
|
- 文档:[Documentation]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**注意**:本项目目前处于开发阶段,功能和文档会持续更新。
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# 应用配置
|
||||||
|
NODE_ENV=development
|
||||||
|
PORT=3000
|
||||||
|
|
||||||
|
# 数据库配置
|
||||||
|
DATABASE_URL="mysql://root:password@localhost:3306/news_aggregator"
|
||||||
|
|
||||||
|
# 其他配置
|
||||||
|
LOG_LEVEL=info
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
.env
|
||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
Generated
+2280
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,37 @@
|
|||||||
|
{
|
||||||
|
"name": "backend",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "",
|
||||||
|
"main": "index.js",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "tsx watch src/app.ts",
|
||||||
|
"build": "tsc",
|
||||||
|
"start": "node dist/app.js",
|
||||||
|
"prisma:generate": "prisma generate",
|
||||||
|
"prisma:migrate": "prisma migrate dev",
|
||||||
|
"prisma:studio": "prisma studio"
|
||||||
|
},
|
||||||
|
"keywords": [],
|
||||||
|
"author": "",
|
||||||
|
"license": "ISC",
|
||||||
|
"type": "commonjs",
|
||||||
|
"dependencies": {
|
||||||
|
"@fastify/cors": "^11.2.0",
|
||||||
|
"@fastify/static": "^9.0.0",
|
||||||
|
"@prisma/client": "^5.22.0",
|
||||||
|
"dotenv": "^17.2.3",
|
||||||
|
"fastify": "^5.7.4",
|
||||||
|
"node-cron": "^4.2.1",
|
||||||
|
"openai": "^6.17.0",
|
||||||
|
"playwright": "^1.58.1",
|
||||||
|
"prisma": "^5.22.0",
|
||||||
|
"winston": "^3.19.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^25.2.0",
|
||||||
|
"@types/node-cron": "^3.0.11",
|
||||||
|
"nodemon": "^3.1.11",
|
||||||
|
"tsx": "^4.21.0",
|
||||||
|
"typescript": "^5.9.3"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
generator client {
|
||||||
|
provider = "prisma-client-js"
|
||||||
|
}
|
||||||
|
|
||||||
|
datasource db {
|
||||||
|
provider = "mysql"
|
||||||
|
url = env("DATABASE_URL")
|
||||||
|
}
|
||||||
|
|
||||||
|
// LLM 配置表
|
||||||
|
model LlmConfig {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
name String @db.VarChar(100)
|
||||||
|
baseUrl String @map("base_url") @db.VarChar(500)
|
||||||
|
model String @db.VarChar(100)
|
||||||
|
apiKey String @map("api_key") @db.VarChar(500)
|
||||||
|
enabled Boolean @default(true) @db.TinyInt
|
||||||
|
userId Int? @map("user_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
topics Topic[]
|
||||||
|
|
||||||
|
@@index([userId, enabled], map: "idx_user_enabled")
|
||||||
|
@@map("llm_configs")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 数据源表
|
||||||
|
model Source {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
name String @db.VarChar(100)
|
||||||
|
type String @db.VarChar(50) // api/playwright/rss
|
||||||
|
config Json
|
||||||
|
cronExpression String @map("cron_expression") @db.VarChar(100)
|
||||||
|
enabled Boolean @default(true) @db.TinyInt
|
||||||
|
lastCollectedAt DateTime? @map("last_collected_at")
|
||||||
|
userId Int? @map("user_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
articles Article[]
|
||||||
|
topicSources TopicSource[]
|
||||||
|
collectionLogs CollectionLog[]
|
||||||
|
|
||||||
|
@@index([userId, enabled], map: "idx_user_enabled")
|
||||||
|
@@index([type], map: "idx_type")
|
||||||
|
@@map("sources")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 推送渠道表
|
||||||
|
model Channel {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
name String @db.VarChar(100)
|
||||||
|
type String @db.VarChar(50) // email/dingtalk/wechat/slack
|
||||||
|
config Json
|
||||||
|
enabled Boolean @default(true) @db.TinyInt
|
||||||
|
userId Int? @map("user_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
topicChannels TopicChannel[]
|
||||||
|
pushLogs PushLog[]
|
||||||
|
|
||||||
|
@@index([userId, enabled], map: "idx_user_enabled")
|
||||||
|
@@index([type], map: "idx_type")
|
||||||
|
@@map("channels")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 主题表
|
||||||
|
model Topic {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
name String @db.VarChar(100)
|
||||||
|
description String? @db.Text
|
||||||
|
processMode String @map("process_mode") @db.VarChar(50) // aggregate/summary/deep_analysis
|
||||||
|
llmConfigId Int? @map("llm_config_id")
|
||||||
|
scheduleConfig Json @map("schedule_config")
|
||||||
|
enabled Boolean @default(true) @db.TinyInt
|
||||||
|
userId Int? @map("user_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
llmConfig LlmConfig? @relation(fields: [llmConfigId], references: [id])
|
||||||
|
topicSources TopicSource[]
|
||||||
|
topicChannels TopicChannel[]
|
||||||
|
reports Report[]
|
||||||
|
conversations Conversation[]
|
||||||
|
|
||||||
|
@@index([userId, enabled], map: "idx_user_enabled")
|
||||||
|
@@map("topics")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 主题-数据源关联表
|
||||||
|
model TopicSource {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
topicId Int @map("topic_id")
|
||||||
|
sourceId Int @map("source_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
topic Topic @relation(fields: [topicId], references: [id], onDelete: Cascade)
|
||||||
|
source Source @relation(fields: [sourceId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@unique([topicId, sourceId], map: "uk_topic_source")
|
||||||
|
@@index([topicId], map: "idx_topic")
|
||||||
|
@@index([sourceId], map: "idx_source")
|
||||||
|
@@map("topic_sources")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 主题-推送渠道关联表
|
||||||
|
model TopicChannel {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
topicId Int @map("topic_id")
|
||||||
|
channelId Int @map("channel_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
topic Topic @relation(fields: [topicId], references: [id], onDelete: Cascade)
|
||||||
|
channel Channel @relation(fields: [channelId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@unique([topicId, channelId], map: "uk_topic_channel")
|
||||||
|
@@index([topicId], map: "idx_topic")
|
||||||
|
@@index([channelId], map: "idx_channel")
|
||||||
|
@@map("topic_channels")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 资讯表
|
||||||
|
model Article {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
sourceId Int @map("source_id")
|
||||||
|
title String @db.VarChar(500)
|
||||||
|
content String? @db.Text
|
||||||
|
summary String? @db.Text
|
||||||
|
url String? @db.VarChar(1000)
|
||||||
|
publishedAt DateTime? @map("published_at")
|
||||||
|
collectedAt DateTime @map("collected_at")
|
||||||
|
rawData Json? @map("raw_data")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
source Source @relation(fields: [sourceId], references: [id])
|
||||||
|
conversations Conversation[]
|
||||||
|
|
||||||
|
@@index([sourceId], map: "idx_source")
|
||||||
|
@@index([publishedAt], map: "idx_published")
|
||||||
|
@@index([collectedAt], map: "idx_collected")
|
||||||
|
@@index([url(length: 255)], map: "idx_url")
|
||||||
|
@@map("articles")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 报告表
|
||||||
|
model Report {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
topicId Int @map("topic_id")
|
||||||
|
title String @db.VarChar(500)
|
||||||
|
content String @db.LongText
|
||||||
|
periodStart DateTime @map("period_start")
|
||||||
|
periodEnd DateTime @map("period_end")
|
||||||
|
status String @db.VarChar(50) // pending/generating/completed/failed
|
||||||
|
errorMessage String? @map("error_message") @db.Text
|
||||||
|
articleCount Int @default(0) @map("article_count")
|
||||||
|
userId Int? @map("user_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
topic Topic @relation(fields: [topicId], references: [id])
|
||||||
|
pushLogs PushLog[]
|
||||||
|
conversations Conversation[]
|
||||||
|
|
||||||
|
@@index([topicId], map: "idx_topic")
|
||||||
|
@@index([status], map: "idx_status")
|
||||||
|
@@index([periodStart, periodEnd], map: "idx_period")
|
||||||
|
@@index([userId, createdAt], map: "idx_user_created")
|
||||||
|
@@map("reports")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 采集日志表
|
||||||
|
model CollectionLog {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
sourceId Int @map("source_id")
|
||||||
|
status String @db.VarChar(50) // success/failed
|
||||||
|
errorMessage String? @map("error_message") @db.Text
|
||||||
|
articlesCount Int @default(0) @map("articles_count")
|
||||||
|
startedAt DateTime @map("started_at")
|
||||||
|
finishedAt DateTime? @map("finished_at")
|
||||||
|
durationMs Int? @map("duration_ms")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
source Source @relation(fields: [sourceId], references: [id])
|
||||||
|
|
||||||
|
@@index([sourceId], map: "idx_source")
|
||||||
|
@@index([status], map: "idx_status")
|
||||||
|
@@index([startedAt], map: "idx_started")
|
||||||
|
@@map("collection_logs")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 推送日志表
|
||||||
|
model PushLog {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
reportId Int @map("report_id")
|
||||||
|
channelId Int @map("channel_id")
|
||||||
|
status String @db.VarChar(50) // success/failed
|
||||||
|
errorMessage String? @map("error_message") @db.Text
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
report Report @relation(fields: [reportId], references: [id])
|
||||||
|
channel Channel @relation(fields: [channelId], references: [id])
|
||||||
|
|
||||||
|
@@index([reportId], map: "idx_report")
|
||||||
|
@@index([channelId], map: "idx_channel")
|
||||||
|
@@index([status], map: "idx_status")
|
||||||
|
@@map("push_logs")
|
||||||
|
}
|
||||||
|
|
||||||
|
// AI对话记录表
|
||||||
|
model Conversation {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
reportId Int? @map("report_id")
|
||||||
|
articleId Int? @map("article_id")
|
||||||
|
topicId Int @map("topic_id")
|
||||||
|
messages Json
|
||||||
|
userId Int? @map("user_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
report Report? @relation(fields: [reportId], references: [id])
|
||||||
|
article Article? @relation(fields: [articleId], references: [id])
|
||||||
|
topic Topic @relation(fields: [topicId], references: [id])
|
||||||
|
|
||||||
|
@@index([reportId], map: "idx_report")
|
||||||
|
@@index([articleId], map: "idx_article")
|
||||||
|
@@index([topicId], map: "idx_topic")
|
||||||
|
@@index([userId], map: "idx_user")
|
||||||
|
@@map("conversations")
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
console.log('开始填充种子数据...');
|
||||||
|
|
||||||
|
// 创建默认 LLM 配置
|
||||||
|
const defaultLlmConfig = await prisma.llmConfig.create({
|
||||||
|
data: {
|
||||||
|
name: '默认配置',
|
||||||
|
baseUrl: 'https://api.openai.com/v1',
|
||||||
|
model: 'gpt-4o-mini',
|
||||||
|
apiKey: 'your-api-key-here',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
console.log('✅ 创建默认 LLM 配置:', defaultLlmConfig.id);
|
||||||
|
|
||||||
|
// 创建示例数据源
|
||||||
|
const sampleSource = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '示例新闻源',
|
||||||
|
type: 'api',
|
||||||
|
config: JSON.stringify({
|
||||||
|
url: 'https://api.example.com/news',
|
||||||
|
method: 'GET',
|
||||||
|
headers: {},
|
||||||
|
}),
|
||||||
|
cronExpression: '0 */6 * * *',
|
||||||
|
enabled: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
console.log('✅ 创建示例数据源:', sampleSource.id);
|
||||||
|
|
||||||
|
// 创建示例推送渠道
|
||||||
|
const sampleChannel = await prisma.channel.create({
|
||||||
|
data: {
|
||||||
|
name: '示例邮箱',
|
||||||
|
type: 'email',
|
||||||
|
config: JSON.stringify({
|
||||||
|
smtpHost: 'smtp.example.com',
|
||||||
|
smtpPort: 587,
|
||||||
|
username: 'user@example.com',
|
||||||
|
password: 'password',
|
||||||
|
to: 'recipient@example.com',
|
||||||
|
}),
|
||||||
|
enabled: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
console.log('✅ 创建示例推送渠道:', sampleChannel.id);
|
||||||
|
|
||||||
|
// 创建示例主题
|
||||||
|
const sampleTopic = await prisma.topic.create({
|
||||||
|
data: {
|
||||||
|
name: '示例主题',
|
||||||
|
description: '这是一个示例主题,用于演示功能',
|
||||||
|
processMode: 'summary',
|
||||||
|
llmConfigId: defaultLlmConfig.id,
|
||||||
|
scheduleConfig: JSON.stringify({
|
||||||
|
cron: '0 9 * * *',
|
||||||
|
timezone: 'Asia/Shanghai',
|
||||||
|
}),
|
||||||
|
enabled: false,
|
||||||
|
topicSources: {
|
||||||
|
create: {
|
||||||
|
sourceId: sampleSource.id,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
topicChannels: {
|
||||||
|
create: {
|
||||||
|
channelId: sampleChannel.id,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
console.log('✅ 创建示例主题:', sampleTopic.id);
|
||||||
|
|
||||||
|
console.log('\n✨ 种子数据填充完成!');
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
.catch((e) => {
|
||||||
|
console.error('❌ 种子数据填充失败:', e);
|
||||||
|
process.exit(1);
|
||||||
|
})
|
||||||
|
.finally(async () => {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
});
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import Fastify from 'fastify';
|
||||||
|
import cors from '@fastify/cors';
|
||||||
|
import { config, validateConfig } from './config';
|
||||||
|
import logger from './utils/logger';
|
||||||
|
|
||||||
|
// 验证配置
|
||||||
|
try {
|
||||||
|
validateConfig();
|
||||||
|
logger.info('配置验证通过');
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('配置验证失败:', error);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建 Fastify 实例
|
||||||
|
const app = Fastify({
|
||||||
|
logger: false, // 使用 winston 替代
|
||||||
|
});
|
||||||
|
|
||||||
|
// 注册插件
|
||||||
|
async function registerPlugins(): Promise<void> {
|
||||||
|
// CORS
|
||||||
|
await app.register(cors, {
|
||||||
|
origin: true,
|
||||||
|
credentials: true,
|
||||||
|
});
|
||||||
|
logger.info('CORS 插件已注册');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 注册路由
|
||||||
|
async function registerRoutes(): Promise<void> {
|
||||||
|
// 健康检查
|
||||||
|
app.get('/api/v1/health', async () => {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
status: 'ok',
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
version: '1.0.0',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info('路由已注册');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 错误处理
|
||||||
|
app.setErrorHandler((error, request, reply) => {
|
||||||
|
logger.error('请求处理错误:', {
|
||||||
|
error: error.message,
|
||||||
|
stack: error.stack,
|
||||||
|
url: request.url,
|
||||||
|
method: request.method,
|
||||||
|
});
|
||||||
|
|
||||||
|
reply.status(error.statusCode || 500).send({
|
||||||
|
success: false,
|
||||||
|
error: error.message || '服务器内部错误',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 启动服务器
|
||||||
|
async function start(): Promise<void> {
|
||||||
|
try {
|
||||||
|
await registerPlugins();
|
||||||
|
await registerRoutes();
|
||||||
|
|
||||||
|
await app.listen({
|
||||||
|
port: config.port,
|
||||||
|
host: '0.0.0.0',
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info(`🚀 服务器启动成功,监听端口 ${config.port}`);
|
||||||
|
logger.info(`📚 API 文档: http://localhost:${config.port}/api/v1/health`);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('服务器启动失败:', error);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理未捕获的异常
|
||||||
|
process.on('uncaughtException', (error) => {
|
||||||
|
logger.error('未捕获的异常:', error);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
process.on('unhandledRejection', (reason, promise) => {
|
||||||
|
logger.error('未处理的 Promise 拒绝:', { reason, promise });
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 优雅关闭
|
||||||
|
process.on('SIGTERM', async () => {
|
||||||
|
logger.info('SIGTERM 信号收到,正在关闭服务器...');
|
||||||
|
await app.close();
|
||||||
|
process.exit(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
process.on('SIGINT', async () => {
|
||||||
|
logger.info('SIGINT 信号收到,正在关闭服务器...');
|
||||||
|
await app.close();
|
||||||
|
process.exit(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 启动
|
||||||
|
start();
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
import { config } from '.';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
// 创建 Prisma 客户端实例
|
||||||
|
const prisma = new PrismaClient({
|
||||||
|
log: [
|
||||||
|
{ emit: 'event', level: 'query' },
|
||||||
|
{ emit: 'stdout', level: 'error' },
|
||||||
|
{ emit: 'stdout', level: 'info' },
|
||||||
|
{ emit: 'stdout', level: 'warn' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 查询日志
|
||||||
|
prisma.$on('query', (e: any) => {
|
||||||
|
logger.debug(`Query: ${e.query}`);
|
||||||
|
logger.debug(`Duration: ${e.duration}ms`);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 连接数据库
|
||||||
|
export async function connectDatabase(): Promise<void> {
|
||||||
|
try {
|
||||||
|
await prisma.$connect();
|
||||||
|
logger.info('✅ 数据库连接成功');
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('❌ 数据库连接失败:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 断开数据库连接
|
||||||
|
export async function disconnectDatabase(): Promise<void> {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
logger.info('数据库连接已关闭');
|
||||||
|
}
|
||||||
|
|
||||||
|
export default prisma;
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import dotenv from 'dotenv';
|
||||||
|
import path from 'path';
|
||||||
|
|
||||||
|
// 加载环境变量
|
||||||
|
dotenv.config({ path: path.resolve(__dirname, '../../.env') });
|
||||||
|
|
||||||
|
export interface Config {
|
||||||
|
// 应用配置
|
||||||
|
nodeEnv: string;
|
||||||
|
port: number;
|
||||||
|
logLevel: string;
|
||||||
|
|
||||||
|
// 数据库配置
|
||||||
|
databaseUrl: string;
|
||||||
|
|
||||||
|
// 安全配置
|
||||||
|
jwtSecret?: string;
|
||||||
|
apiKey?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getEnvVar(key: string, defaultValue?: string): string {
|
||||||
|
const value = process.env[key] || defaultValue;
|
||||||
|
if (value === undefined) {
|
||||||
|
throw new Error(`环境变量 ${key} 未设置`);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getEnvVarAsInt(key: string, defaultValue?: number): number {
|
||||||
|
const value = process.env[key];
|
||||||
|
if (value === undefined) {
|
||||||
|
if (defaultValue !== undefined) {
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
throw new Error(`环境变量 ${key} 未设置`);
|
||||||
|
}
|
||||||
|
const parsed = parseInt(value, 10);
|
||||||
|
if (isNaN(parsed)) {
|
||||||
|
throw new Error(`环境变量 ${key} 不是有效的整数`);
|
||||||
|
}
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const config: Config = {
|
||||||
|
nodeEnv: getEnvVar('NODE_ENV', 'development'),
|
||||||
|
port: getEnvVarAsInt('PORT', 3000),
|
||||||
|
logLevel: getEnvVar('LOG_LEVEL', 'info'),
|
||||||
|
databaseUrl: getEnvVar('DATABASE_URL'),
|
||||||
|
jwtSecret: process.env.JWT_SECRET,
|
||||||
|
apiKey: process.env.API_KEY,
|
||||||
|
};
|
||||||
|
|
||||||
|
// 验证必需配置
|
||||||
|
export function validateConfig(): void {
|
||||||
|
if (!config.databaseUrl) {
|
||||||
|
throw new Error('DATABASE_URL 是必需的配置项');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default config;
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import prisma from '../config/database';
|
||||||
|
import { NotFoundError, ConflictError } from '../utils/errors';
|
||||||
|
|
||||||
|
export abstract class BaseService<T, CreateInput, UpdateInput> {
|
||||||
|
protected model: any;
|
||||||
|
|
||||||
|
constructor(model: any) {
|
||||||
|
this.model = model;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取所有记录
|
||||||
|
async findAll(options: {
|
||||||
|
skip?: number;
|
||||||
|
take?: number;
|
||||||
|
where?: any;
|
||||||
|
orderBy?: any;
|
||||||
|
include?: any;
|
||||||
|
} = {}): Promise<T[]> {
|
||||||
|
return this.model.findMany({
|
||||||
|
skip: options.skip,
|
||||||
|
take: options.take,
|
||||||
|
where: options.where,
|
||||||
|
orderBy: options.orderBy || { createdAt: 'desc' },
|
||||||
|
include: options.include,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 根据 ID 查找
|
||||||
|
async findById(id: number, include?: any): Promise<T | null> {
|
||||||
|
return this.model.findUnique({
|
||||||
|
where: { id },
|
||||||
|
include,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 根据 ID 查找(不存在则抛出错误)
|
||||||
|
async findByIdOrThrow(id: number, include?: any): Promise<T> {
|
||||||
|
const record = await this.findById(id, include);
|
||||||
|
if (!record) {
|
||||||
|
throw new NotFoundError(`${this.model.name} ID ${id} 不存在`);
|
||||||
|
}
|
||||||
|
return record;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建记录
|
||||||
|
async create(data: CreateInput, uniqueFields?: string[]): Promise<T> {
|
||||||
|
// 检查唯一约束
|
||||||
|
if (uniqueFields && uniqueFields.length > 0) {
|
||||||
|
for (const field of uniqueFields) {
|
||||||
|
const value = (data as any)[field];
|
||||||
|
if (value !== undefined) {
|
||||||
|
const existing = await this.model.findFirst({
|
||||||
|
where: { [field]: value },
|
||||||
|
});
|
||||||
|
if (existing) {
|
||||||
|
throw new ConflictError(`${field} 已存在: ${value}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.model.create({ data });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新记录
|
||||||
|
async update(id: number, data: UpdateInput): Promise<T> {
|
||||||
|
await this.findByIdOrThrow(id);
|
||||||
|
return this.model.update({
|
||||||
|
where: { id },
|
||||||
|
data,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 删除记录
|
||||||
|
async delete(id: number): Promise<T> {
|
||||||
|
await this.findByIdOrThrow(id);
|
||||||
|
return this.model.delete({ where: { id } });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计数
|
||||||
|
async count(where?: any): Promise<number> {
|
||||||
|
return this.model.count({ where });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 分页查询
|
||||||
|
async paginate(
|
||||||
|
page: number = 1,
|
||||||
|
limit: number = 20,
|
||||||
|
where?: any,
|
||||||
|
include?: any,
|
||||||
|
orderBy?: any
|
||||||
|
): Promise<{ data: T[]; total: number; totalPages: number }> {
|
||||||
|
const skip = (page - 1) * limit;
|
||||||
|
|
||||||
|
const [data, total] = await Promise.all([
|
||||||
|
this.model.findMany({
|
||||||
|
skip,
|
||||||
|
take: limit,
|
||||||
|
where,
|
||||||
|
include,
|
||||||
|
orderBy: orderBy || { createdAt: 'desc' },
|
||||||
|
}),
|
||||||
|
this.model.count({ where }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const totalPages = Math.ceil(total / limit);
|
||||||
|
|
||||||
|
return { data, total, totalPages };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default BaseService;
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
// 通用类型定义
|
||||||
|
|
||||||
|
export interface ApiResponse<T = any> {
|
||||||
|
success: boolean;
|
||||||
|
data?: T;
|
||||||
|
error?: string;
|
||||||
|
message?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PaginationParams {
|
||||||
|
page: number;
|
||||||
|
limit: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PaginatedResponse<T> extends ApiResponse<T[]> {
|
||||||
|
pagination: {
|
||||||
|
page: number;
|
||||||
|
limit: number;
|
||||||
|
total: number;
|
||||||
|
totalPages: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 采集器类型
|
||||||
|
export interface CollectorConfig {
|
||||||
|
url: string;
|
||||||
|
method?: 'GET' | 'POST';
|
||||||
|
headers?: Record<string, string>;
|
||||||
|
body?: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RawArticle {
|
||||||
|
title: string;
|
||||||
|
content?: string;
|
||||||
|
url?: string;
|
||||||
|
publishedAt?: Date;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理器类型
|
||||||
|
export type ProcessMode = 'aggregate' | 'summary' | 'deep_analysis';
|
||||||
|
|
||||||
|
export interface ProcessingResult {
|
||||||
|
title: string;
|
||||||
|
content: string;
|
||||||
|
articleCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 推送器类型
|
||||||
|
export interface PushConfig {
|
||||||
|
type: 'email' | 'dingtalk' | 'wechat' | 'slack';
|
||||||
|
config: Record<string, any>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 日志类型
|
||||||
|
export interface LogMetadata {
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
// 自定义错误类
|
||||||
|
|
||||||
|
export class AppError extends Error {
|
||||||
|
public readonly statusCode: number;
|
||||||
|
public readonly isOperational: boolean;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
message: string,
|
||||||
|
statusCode: number = 500,
|
||||||
|
isOperational: boolean = true
|
||||||
|
) {
|
||||||
|
super(message);
|
||||||
|
this.statusCode = statusCode;
|
||||||
|
this.isOperational = isOperational;
|
||||||
|
|
||||||
|
Error.captureStackTrace(this, this.constructor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 400 - 错误请求
|
||||||
|
export class BadRequestError extends AppError {
|
||||||
|
constructor(message: string = '错误的请求') {
|
||||||
|
super(message, 400);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 401 - 未授权
|
||||||
|
export class UnauthorizedError extends AppError {
|
||||||
|
constructor(message: string = '未授权访问') {
|
||||||
|
super(message, 401);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 403 - 禁止访问
|
||||||
|
export class ForbiddenError extends AppError {
|
||||||
|
constructor(message: string = '禁止访问') {
|
||||||
|
super(message, 403);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 404 - 未找到
|
||||||
|
export class NotFoundError extends AppError {
|
||||||
|
constructor(message: string = '资源未找到') {
|
||||||
|
super(message, 404);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 409 - 冲突
|
||||||
|
export class ConflictError extends AppError {
|
||||||
|
constructor(message: string = '资源冲突') {
|
||||||
|
super(message, 409);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 422 - 无法处理的实体
|
||||||
|
export class ValidationError extends AppError {
|
||||||
|
public readonly errors: Record<string, string>;
|
||||||
|
|
||||||
|
constructor(errors: Record<string, string>) {
|
||||||
|
super('请求参数验证失败', 422);
|
||||||
|
this.errors = errors;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 500 - 服务器内部错误
|
||||||
|
export class InternalError extends AppError {
|
||||||
|
constructor(message: string = '服务器内部错误') {
|
||||||
|
super(message, 500, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 503 - 服务不可用
|
||||||
|
export class ServiceUnavailableError extends AppError {
|
||||||
|
constructor(message: string = '服务暂时不可用') {
|
||||||
|
super(message, 503);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import winston from 'winston';
|
||||||
|
import path from 'path';
|
||||||
|
import { config } from '../config';
|
||||||
|
|
||||||
|
// 定义日志级别颜色
|
||||||
|
const colors = {
|
||||||
|
error: 'red',
|
||||||
|
warn: 'yellow',
|
||||||
|
info: 'green',
|
||||||
|
http: 'magenta',
|
||||||
|
debug: 'white',
|
||||||
|
};
|
||||||
|
|
||||||
|
winston.addColors(colors);
|
||||||
|
|
||||||
|
// 定义日志格式
|
||||||
|
const consoleFormat = winston.format.combine(
|
||||||
|
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
|
||||||
|
winston.format.colorize({ all: true }),
|
||||||
|
winston.format.printf(
|
||||||
|
(info) => `${info.timestamp} [${info.level}]: ${info.message}`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
const fileFormat = winston.format.combine(
|
||||||
|
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
|
||||||
|
winston.format.json()
|
||||||
|
);
|
||||||
|
|
||||||
|
// 创建日志目录
|
||||||
|
const logDir = path.resolve(__dirname, '../../logs');
|
||||||
|
|
||||||
|
// 创建 logger 实例
|
||||||
|
const logger = winston.createLogger({
|
||||||
|
level: config.logLevel,
|
||||||
|
defaultMeta: { service: 'news-aggregator' },
|
||||||
|
transports: [
|
||||||
|
// 控制台输出
|
||||||
|
new winston.transports.Console({
|
||||||
|
format: consoleFormat,
|
||||||
|
}),
|
||||||
|
// 错误日志文件
|
||||||
|
new winston.transports.File({
|
||||||
|
filename: path.join(logDir, 'error.log'),
|
||||||
|
level: 'error',
|
||||||
|
format: fileFormat,
|
||||||
|
}),
|
||||||
|
// 所有日志文件
|
||||||
|
new winston.transports.File({
|
||||||
|
filename: path.join(logDir, 'combined.log'),
|
||||||
|
format: fileFormat,
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
// 未捕获的异常处理
|
||||||
|
exceptionHandlers: [
|
||||||
|
new winston.transports.File({
|
||||||
|
filename: path.join(logDir, 'exceptions.log'),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
// 未处理的 Promise 拒绝
|
||||||
|
rejectionHandlers: [
|
||||||
|
new winston.transports.File({
|
||||||
|
filename: path.join(logDir, 'rejections.log'),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 开发环境下简化日志输出
|
||||||
|
if (config.nodeEnv === 'development') {
|
||||||
|
logger.clear();
|
||||||
|
logger.add(
|
||||||
|
new winston.transports.Console({
|
||||||
|
format: consoleFormat,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 流接口用于 HTTP 请求日志
|
||||||
|
export const stream = {
|
||||||
|
write: (message: string): void => {
|
||||||
|
logger.http(message.trim());
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default logger;
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { FastifyReply } from 'fastify';
|
||||||
|
import { ApiResponse, PaginatedResponse } from '../types';
|
||||||
|
|
||||||
|
export function successResponse<T>(
|
||||||
|
reply: FastifyReply,
|
||||||
|
data: T,
|
||||||
|
message?: string,
|
||||||
|
statusCode: number = 200
|
||||||
|
): void {
|
||||||
|
const response: ApiResponse<T> = {
|
||||||
|
success: true,
|
||||||
|
data,
|
||||||
|
message,
|
||||||
|
};
|
||||||
|
reply.status(statusCode).send(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function paginatedResponse<T>(
|
||||||
|
reply: FastifyReply,
|
||||||
|
data: T[],
|
||||||
|
total: number,
|
||||||
|
page: number,
|
||||||
|
limit: number
|
||||||
|
): void {
|
||||||
|
const totalPages = Math.ceil(total / limit);
|
||||||
|
const response: PaginatedResponse<T> = {
|
||||||
|
success: true,
|
||||||
|
data,
|
||||||
|
pagination: {
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
total,
|
||||||
|
totalPages,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
reply.status(200).send(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function errorResponse(
|
||||||
|
reply: FastifyReply,
|
||||||
|
error: string,
|
||||||
|
statusCode: number = 500
|
||||||
|
): void {
|
||||||
|
const response: ApiResponse = {
|
||||||
|
success: false,
|
||||||
|
error,
|
||||||
|
};
|
||||||
|
reply.status(statusCode).send(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createdResponse<T>(
|
||||||
|
reply: FastifyReply,
|
||||||
|
data: T,
|
||||||
|
message: string = '创建成功'
|
||||||
|
): void {
|
||||||
|
successResponse(reply, data, message, 201);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function noContentResponse(reply: FastifyReply): void {
|
||||||
|
reply.status(204).send();
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { BadRequestError, ValidationError } from './errors';
|
||||||
|
|
||||||
|
export function validateRequired(
|
||||||
|
data: Record<string, any>,
|
||||||
|
fields: string[]
|
||||||
|
): void {
|
||||||
|
const missing: string[] = [];
|
||||||
|
|
||||||
|
for (const field of fields) {
|
||||||
|
if (data[field] === undefined || data[field] === null || data[field] === '') {
|
||||||
|
missing.push(field);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (missing.length > 0) {
|
||||||
|
throw new BadRequestError(`缺少必需字段: ${missing.join(', ')}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateEmail(email: string): void {
|
||||||
|
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||||
|
if (!emailRegex.test(email)) {
|
||||||
|
throw new BadRequestError('邮箱格式不正确');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateUrl(url: string): void {
|
||||||
|
try {
|
||||||
|
new URL(url);
|
||||||
|
} catch {
|
||||||
|
throw new BadRequestError('URL 格式不正确');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateCronExpression(cron: string): void {
|
||||||
|
const cronRegex = /^((\*|\?|\d+([\/\-]\d+)?)(,\d+([\/\-]\d+)?)*\s+){4}(\*|\?|\d+([\/\-]\d+)?)(,\d+([\/\-]\d+)?)*$/;
|
||||||
|
if (!cronRegex.test(cron)) {
|
||||||
|
throw new BadRequestError('Cron 表达式格式不正确');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateJson(jsonString: string): any {
|
||||||
|
try {
|
||||||
|
return JSON.parse(jsonString);
|
||||||
|
} catch {
|
||||||
|
throw new BadRequestError('JSON 格式不正确');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sanitizeString(input: string, maxLength: number = 255): string {
|
||||||
|
if (typeof input !== 'string') {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
return input.trim().slice(0, maxLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validatePagination(
|
||||||
|
page: any,
|
||||||
|
limit: any,
|
||||||
|
maxLimit: number = 100
|
||||||
|
): { page: number; limit: number } {
|
||||||
|
const parsedPage = parseInt(page, 10) || 1;
|
||||||
|
const parsedLimit = Math.min(parseInt(limit, 10) || 20, maxLimit);
|
||||||
|
|
||||||
|
return {
|
||||||
|
page: Math.max(1, parsedPage),
|
||||||
|
limit: Math.max(1, parsedLimit),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "commonjs",
|
||||||
|
"lib": ["ES2022"],
|
||||||
|
"outDir": "./dist",
|
||||||
|
"rootDir": "./src",
|
||||||
|
"strict": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"moduleResolution": "node",
|
||||||
|
"types": ["node"]
|
||||||
|
},
|
||||||
|
"include": ["src/**/*"],
|
||||||
|
"exclude": ["node_modules", "dist"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,697 @@
|
|||||||
|
# 开发指南
|
||||||
|
|
||||||
|
本文档提供 News Aggregator 项目的开发指南和最佳实践。
|
||||||
|
|
||||||
|
## 目录
|
||||||
|
|
||||||
|
- [快速开始](#快速开始)
|
||||||
|
- [开发流程](#开发流程)
|
||||||
|
- [代码规范](#代码规范)
|
||||||
|
- [测试指南](#测试指南)
|
||||||
|
- [调试技巧](#调试技巧)
|
||||||
|
- [常见问题](#常见问题)
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
### 环境准备
|
||||||
|
|
||||||
|
1. **安装 Node.js**
|
||||||
|
- 版本:20.x 或更高
|
||||||
|
- 下载:https://nodejs.org/
|
||||||
|
|
||||||
|
2. **安装 MySQL**
|
||||||
|
- 版本:5.6 或更高
|
||||||
|
- 创建数据库:`news_aggregator`
|
||||||
|
|
||||||
|
3. **安装 PM2**(生产环境)
|
||||||
|
```bash
|
||||||
|
npm install -g pm2
|
||||||
|
```
|
||||||
|
|
||||||
|
### 项目初始化
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 克隆项目
|
||||||
|
git clone <repository-url>
|
||||||
|
cd news-aggregator
|
||||||
|
|
||||||
|
# 2. 安装后端依赖
|
||||||
|
cd backend
|
||||||
|
npm install
|
||||||
|
|
||||||
|
# 3. 配置环境变量
|
||||||
|
cp .env.example .env
|
||||||
|
# 编辑 .env 文件,配置数据库连接等
|
||||||
|
|
||||||
|
# 4. 初始化数据库
|
||||||
|
npm run prisma:migrate
|
||||||
|
npm run prisma:seed
|
||||||
|
|
||||||
|
# 5. 启动后端开发服务
|
||||||
|
npm run dev
|
||||||
|
|
||||||
|
# 6. 安装前端依赖(新终端)
|
||||||
|
cd ../frontend
|
||||||
|
npm install
|
||||||
|
|
||||||
|
# 7. 启动前端开发服务
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
### 访问应用
|
||||||
|
|
||||||
|
- 后端 API:http://localhost:3000
|
||||||
|
- 前端界面:http://localhost:5173
|
||||||
|
- API 文档:http://localhost:3000/api/health
|
||||||
|
- Prisma Studio:`npm run prisma:studio`
|
||||||
|
|
||||||
|
## 开发流程
|
||||||
|
|
||||||
|
### 1. 任务开发流程
|
||||||
|
|
||||||
|
```
|
||||||
|
选择任务 → 阅读文档 → 实现功能 → 测试验证 → 提交代码
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 步骤详解
|
||||||
|
|
||||||
|
1. **选择任务**
|
||||||
|
- 查看 [任务清单](./tasks/README.md)
|
||||||
|
- 选择下一个待完成的任务
|
||||||
|
- 确认前置任务已完成
|
||||||
|
|
||||||
|
2. **阅读文档**
|
||||||
|
- 阅读任务文档
|
||||||
|
- 理解任务目标和要求
|
||||||
|
- 查看相关设计文档
|
||||||
|
|
||||||
|
3. **实现功能**
|
||||||
|
- 按任务文档步骤实现
|
||||||
|
- 遵循代码规范
|
||||||
|
- 编写清晰的注释
|
||||||
|
|
||||||
|
4. **测试验证**
|
||||||
|
- 运行任务文档中的验证步骤
|
||||||
|
- 测试边界情况
|
||||||
|
- 确保功能正常
|
||||||
|
|
||||||
|
5. **提交代码**
|
||||||
|
- 编写清晰的提交信息
|
||||||
|
- 提交到 Git
|
||||||
|
- 更新任务状态
|
||||||
|
|
||||||
|
### 2. 分支管理
|
||||||
|
|
||||||
|
```
|
||||||
|
main (主分支)
|
||||||
|
├── develop (开发分支)
|
||||||
|
│ ├── feature/task-01 (功能分支)
|
||||||
|
│ ├── feature/task-02
|
||||||
|
│ └── ...
|
||||||
|
└── hotfix/xxx (热修复分支)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 分支命名规范
|
||||||
|
|
||||||
|
- `feature/task-xx`:功能开发
|
||||||
|
- `fix/bug-description`:Bug 修复
|
||||||
|
- `hotfix/critical-issue`:紧急修复
|
||||||
|
- `refactor/module-name`:重构
|
||||||
|
|
||||||
|
#### 工作流程
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 创建功能分支
|
||||||
|
git checkout -b feature/task-01
|
||||||
|
|
||||||
|
# 2. 开发功能
|
||||||
|
# ... 编写代码 ...
|
||||||
|
|
||||||
|
# 3. 提交代码
|
||||||
|
git add .
|
||||||
|
git commit -m "feat: implement task 01"
|
||||||
|
|
||||||
|
# 4. 推送到远程
|
||||||
|
git push origin feature/task-01
|
||||||
|
|
||||||
|
# 5. 创建 Pull Request
|
||||||
|
# 在 GitHub/GitLab 上创建 PR
|
||||||
|
|
||||||
|
# 6. 代码审查通过后合并
|
||||||
|
git checkout develop
|
||||||
|
git merge feature/task-01
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 提交规范
|
||||||
|
|
||||||
|
#### 提交信息格式
|
||||||
|
|
||||||
|
```
|
||||||
|
<type>(<scope>): <subject>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<footer>
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Type 类型
|
||||||
|
|
||||||
|
- `feat`: 新功能
|
||||||
|
- `fix`: Bug 修复
|
||||||
|
- `docs`: 文档更新
|
||||||
|
- `style`: 代码格式(不影响功能)
|
||||||
|
- `refactor`: 重构
|
||||||
|
- `test`: 测试相关
|
||||||
|
- `chore`: 构建/工具相关
|
||||||
|
|
||||||
|
#### 示例
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 新功能
|
||||||
|
git commit -m "feat(collector): add API collector"
|
||||||
|
|
||||||
|
# Bug 修复
|
||||||
|
git commit -m "fix(report): fix date format issue"
|
||||||
|
|
||||||
|
# 文档更新
|
||||||
|
git commit -m "docs: update API documentation"
|
||||||
|
|
||||||
|
# 重构
|
||||||
|
git commit -m "refactor(service): simplify report generation logic"
|
||||||
|
```
|
||||||
|
|
||||||
|
## 代码规范
|
||||||
|
|
||||||
|
### TypeScript 规范
|
||||||
|
|
||||||
|
#### 1. 类型定义
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ✅ 好的做法
|
||||||
|
interface User {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
email: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function getUser(id: number): Promise<User> {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
|
||||||
|
// ❌ 避免使用 any
|
||||||
|
function getUser(id: any): any {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2. 命名规范
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// 变量/函数:camelCase
|
||||||
|
const userName = 'John'
|
||||||
|
function getUserName() {}
|
||||||
|
|
||||||
|
// 类/接口:PascalCase
|
||||||
|
class UserService {}
|
||||||
|
interface UserConfig {}
|
||||||
|
|
||||||
|
// 常量:UPPER_SNAKE_CASE
|
||||||
|
const API_BASE_URL = 'http://localhost:3000'
|
||||||
|
|
||||||
|
// 私有成员:前缀下划线
|
||||||
|
class User {
|
||||||
|
private _password: string
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3. 函数规范
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ✅ 好的做法:清晰的函数签名
|
||||||
|
async function createUser(
|
||||||
|
name: string,
|
||||||
|
email: string,
|
||||||
|
options?: { sendEmail?: boolean }
|
||||||
|
): Promise<User> {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
|
||||||
|
// ✅ 好的做法:使用解构
|
||||||
|
function processUser({ id, name, email }: User) {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
|
||||||
|
// ❌ 避免:参数过多
|
||||||
|
function createUser(name, email, age, phone, address, city, country) {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 4. 异步处理
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ✅ 好的做法:使用 async/await
|
||||||
|
async function fetchData() {
|
||||||
|
try {
|
||||||
|
const data = await api.get('/data')
|
||||||
|
return data
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to fetch data', error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ❌ 避免:回调地狱
|
||||||
|
function fetchData(callback) {
|
||||||
|
api.get('/data', (err, data) => {
|
||||||
|
if (err) {
|
||||||
|
callback(err)
|
||||||
|
} else {
|
||||||
|
processData(data, (err, result) => {
|
||||||
|
// ...
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Vue 规范
|
||||||
|
|
||||||
|
#### 1. 组件命名
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ✅ 好的做法:PascalCase
|
||||||
|
<template>
|
||||||
|
<UserProfile />
|
||||||
|
<ArticleList />
|
||||||
|
</template>
|
||||||
|
|
||||||
|
// ❌ 避免:kebab-case(在 script 中)
|
||||||
|
<template>
|
||||||
|
<user-profile />
|
||||||
|
</template>
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2. Props 定义
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ✅ 好的做法:完整的类型定义
|
||||||
|
interface Props {
|
||||||
|
userId: number
|
||||||
|
userName: string
|
||||||
|
isActive?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const props = defineProps<Props>()
|
||||||
|
|
||||||
|
// ❌ 避免:无类型定义
|
||||||
|
const props = defineProps(['userId', 'userName'])
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3. 组件结构
|
||||||
|
|
||||||
|
```vue
|
||||||
|
<template>
|
||||||
|
<!-- 模板 -->
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
// 1. 导入
|
||||||
|
import { ref, computed, onMounted } from 'vue'
|
||||||
|
|
||||||
|
// 2. Props/Emits
|
||||||
|
interface Props {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
const props = defineProps<Props>()
|
||||||
|
const emit = defineEmits<{
|
||||||
|
update: [value: string]
|
||||||
|
}>()
|
||||||
|
|
||||||
|
// 3. 响应式数据
|
||||||
|
const count = ref(0)
|
||||||
|
|
||||||
|
// 4. 计算属性
|
||||||
|
const doubleCount = computed(() => count.value * 2)
|
||||||
|
|
||||||
|
// 5. 方法
|
||||||
|
function increment() {
|
||||||
|
count.value++
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. 生命周期
|
||||||
|
onMounted(() => {
|
||||||
|
// ...
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
/* 样式 */
|
||||||
|
</style>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 代码注释
|
||||||
|
|
||||||
|
#### 1. 文件头注释
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
/**
|
||||||
|
* 用户服务
|
||||||
|
*
|
||||||
|
* 提供用户相关的业务逻辑
|
||||||
|
*
|
||||||
|
* @module services/user
|
||||||
|
*/
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2. 函数注释
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
/**
|
||||||
|
* 创建用户
|
||||||
|
*
|
||||||
|
* @param name - 用户名
|
||||||
|
* @param email - 邮箱
|
||||||
|
* @returns 创建的用户对象
|
||||||
|
* @throws {ValidationError} 参数验证失败
|
||||||
|
*/
|
||||||
|
async function createUser(name: string, email: string): Promise<User> {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3. 复杂逻辑注释
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// 计算用户的活跃度分数
|
||||||
|
// 规则:
|
||||||
|
// 1. 基础分 = 登录天数 * 10
|
||||||
|
// 2. 发帖加分 = 发帖数 * 5
|
||||||
|
// 3. 评论加分 = 评论数 * 2
|
||||||
|
const activityScore =
|
||||||
|
loginDays * 10 +
|
||||||
|
postCount * 5 +
|
||||||
|
commentCount * 2
|
||||||
|
```
|
||||||
|
|
||||||
|
## 测试指南
|
||||||
|
|
||||||
|
### 单元测试
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// 示例:测试工具函数
|
||||||
|
import { describe, it, expect } from 'vitest'
|
||||||
|
import { formatDate } from '@/utils/date'
|
||||||
|
|
||||||
|
describe('formatDate', () => {
|
||||||
|
it('should format date correctly', () => {
|
||||||
|
const date = new Date('2024-01-01')
|
||||||
|
expect(formatDate(date)).toBe('2024-01-01')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should handle null', () => {
|
||||||
|
expect(formatDate(null)).toBe('')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### API 测试
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 使用 curl 测试
|
||||||
|
curl http://localhost:3000/api/health
|
||||||
|
|
||||||
|
# 使用 REST Client(VS Code 插件)
|
||||||
|
# 在 .http 文件中编写请求
|
||||||
|
GET http://localhost:3000/api/health
|
||||||
|
```
|
||||||
|
|
||||||
|
### 端到端测试
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// 使用 Playwright 进行 E2E 测试
|
||||||
|
import { test, expect } from '@playwright/test'
|
||||||
|
|
||||||
|
test('should display dashboard', async ({ page }) => {
|
||||||
|
await page.goto('http://localhost:5173')
|
||||||
|
await expect(page.locator('h1')).toContainText('仪表盘')
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## 调试技巧
|
||||||
|
|
||||||
|
### 后端调试
|
||||||
|
|
||||||
|
#### 1. 使用日志
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { logger } from './utils/logger'
|
||||||
|
|
||||||
|
// 不同级别的日志
|
||||||
|
logger.debug('Debug message', { data })
|
||||||
|
logger.info('Info message')
|
||||||
|
logger.warn('Warning message')
|
||||||
|
logger.error('Error message', error)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2. 使用断点
|
||||||
|
|
||||||
|
在 VS Code 中配置 `.vscode/launch.json`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": "0.2.0",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"type": "node",
|
||||||
|
"request": "launch",
|
||||||
|
"name": "Debug Backend",
|
||||||
|
"runtimeExecutable": "npm",
|
||||||
|
"runtimeArgs": ["run", "dev"],
|
||||||
|
"cwd": "${workspaceFolder}/backend",
|
||||||
|
"console": "integratedTerminal"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3. 查看数据库
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 使用 Prisma Studio
|
||||||
|
cd backend
|
||||||
|
npm run prisma:studio
|
||||||
|
```
|
||||||
|
|
||||||
|
### 前端调试
|
||||||
|
|
||||||
|
#### 1. Vue DevTools
|
||||||
|
|
||||||
|
安装 Vue DevTools 浏览器插件,可以:
|
||||||
|
- 查看组件树
|
||||||
|
- 检查组件状态
|
||||||
|
- 查看 Pinia store
|
||||||
|
- 追踪事件
|
||||||
|
|
||||||
|
#### 2. 网络请求
|
||||||
|
|
||||||
|
在浏览器开发者工具的 Network 标签中:
|
||||||
|
- 查看 API 请求
|
||||||
|
- 检查请求参数
|
||||||
|
- 查看响应数据
|
||||||
|
- 分析请求时间
|
||||||
|
|
||||||
|
#### 3. 控制台调试
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// 在代码中添加 console.log
|
||||||
|
console.log('User data:', userData)
|
||||||
|
|
||||||
|
// 使用 debugger 语句
|
||||||
|
function processData(data) {
|
||||||
|
debugger // 浏览器会在此处暂停
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
### 后端问题
|
||||||
|
|
||||||
|
#### Q1: 数据库连接失败
|
||||||
|
**A**: 检查以下几点:
|
||||||
|
1. MySQL 服务是否运行
|
||||||
|
2. `.env` 中的数据库配置是否正确
|
||||||
|
3. 数据库是否已创建
|
||||||
|
4. 用户权限是否足够
|
||||||
|
|
||||||
|
#### Q2: Prisma 迁移失败
|
||||||
|
**A**: 尝试以下方法:
|
||||||
|
```bash
|
||||||
|
# 重置数据库
|
||||||
|
npm run prisma:migrate reset
|
||||||
|
|
||||||
|
# 重新生成 Prisma Client
|
||||||
|
npm run prisma:generate
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Q3: 采集器不工作
|
||||||
|
**A**: 检查:
|
||||||
|
1. 数据源配置是否正确
|
||||||
|
2. 网络连接是否正常
|
||||||
|
3. 查看采集日志
|
||||||
|
4. 检查 cron 表达式
|
||||||
|
|
||||||
|
### 前端问题
|
||||||
|
|
||||||
|
#### Q1: API 请求 CORS 错误
|
||||||
|
**A**: 确保后端已配置 CORS:
|
||||||
|
```typescript
|
||||||
|
// backend/src/app.ts
|
||||||
|
await app.register(cors, {
|
||||||
|
origin: 'http://localhost:5173',
|
||||||
|
credentials: true,
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Q2: 路由 404
|
||||||
|
**A**: 检查:
|
||||||
|
1. 路由配置是否正确
|
||||||
|
2. 组件路径是否存在
|
||||||
|
3. 是否使用了懒加载
|
||||||
|
|
||||||
|
#### Q3: 组件样式不生效
|
||||||
|
**A**: 检查:
|
||||||
|
1. 是否使用了 `scoped`
|
||||||
|
2. CSS 选择器是否正确
|
||||||
|
3. 是否有样式冲突
|
||||||
|
|
||||||
|
## 性能优化
|
||||||
|
|
||||||
|
### 后端优化
|
||||||
|
|
||||||
|
1. **数据库查询优化**
|
||||||
|
```typescript
|
||||||
|
// ✅ 使用索引
|
||||||
|
// ✅ 避免 N+1 查询
|
||||||
|
// ✅ 使用分页
|
||||||
|
const users = await prisma.user.findMany({
|
||||||
|
where: { active: true },
|
||||||
|
include: { posts: true },
|
||||||
|
skip: (page - 1) * limit,
|
||||||
|
take: limit,
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **缓存策略**
|
||||||
|
```typescript
|
||||||
|
// 缓存常用数据
|
||||||
|
const cache = new Map()
|
||||||
|
|
||||||
|
async function getConfig(key: string) {
|
||||||
|
if (cache.has(key)) {
|
||||||
|
return cache.get(key)
|
||||||
|
}
|
||||||
|
const value = await fetchConfig(key)
|
||||||
|
cache.set(key, value)
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 前端优化
|
||||||
|
|
||||||
|
1. **路由懒加载**
|
||||||
|
```typescript
|
||||||
|
const routes = [
|
||||||
|
{
|
||||||
|
path: '/reports',
|
||||||
|
component: () => import('@/views/reports/ReportList.vue'),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **组件按需加载**
|
||||||
|
```typescript
|
||||||
|
// 只导入需要的组件
|
||||||
|
import { ElButton, ElTable } from 'element-plus'
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **列表虚拟滚动**
|
||||||
|
```vue
|
||||||
|
<template>
|
||||||
|
<el-table-v2
|
||||||
|
:columns="columns"
|
||||||
|
:data="data"
|
||||||
|
:width="700"
|
||||||
|
:height="400"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
```
|
||||||
|
|
||||||
|
## 安全最佳实践
|
||||||
|
|
||||||
|
### 1. 输入验证
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ✅ 验证用户输入
|
||||||
|
function createUser(data: any) {
|
||||||
|
if (!data.email || !isValidEmail(data.email)) {
|
||||||
|
throw new ValidationError('Invalid email')
|
||||||
|
}
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. SQL 注入防护
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ✅ 使用 Prisma(自动防护)
|
||||||
|
await prisma.user.findMany({
|
||||||
|
where: { email: userInput },
|
||||||
|
})
|
||||||
|
|
||||||
|
// ❌ 避免拼接 SQL
|
||||||
|
const sql = `SELECT * FROM users WHERE email = '${userInput}'`
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. XSS 防护
|
||||||
|
|
||||||
|
```vue
|
||||||
|
<!-- ✅ Vue 自动转义 -->
|
||||||
|
<div>{{ userInput }}</div>
|
||||||
|
|
||||||
|
<!-- ❌ 避免使用 v-html(除非必要) -->
|
||||||
|
<div v-html="userInput"></div>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 敏感信息保护
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ✅ 使用环境变量
|
||||||
|
const apiKey = process.env.API_KEY
|
||||||
|
|
||||||
|
// ❌ 避免硬编码
|
||||||
|
const apiKey = 'sk-1234567890'
|
||||||
|
```
|
||||||
|
|
||||||
|
## 参考资源
|
||||||
|
|
||||||
|
### 官方文档
|
||||||
|
- [TypeScript](https://www.typescriptlang.org/docs/)
|
||||||
|
- [Vue 3](https://vuejs.org/)
|
||||||
|
- [Fastify](https://www.fastify.io/)
|
||||||
|
- [Prisma](https://www.prisma.io/docs)
|
||||||
|
- [Element Plus](https://element-plus.org/)
|
||||||
|
|
||||||
|
### 工具
|
||||||
|
- [VS Code](https://code.visualstudio.com/)
|
||||||
|
- [Postman](https://www.postman.com/)
|
||||||
|
- [Prisma Studio](https://www.prisma.io/studio)
|
||||||
|
|
||||||
|
### 社区
|
||||||
|
- [Stack Overflow](https://stackoverflow.com/)
|
||||||
|
- [GitHub Discussions](https://github.com/)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**持续更新中...**
|
||||||
+389
@@ -0,0 +1,389 @@
|
|||||||
|
# News Aggregator - 完整设计文档总结
|
||||||
|
|
||||||
|
## 文档概览
|
||||||
|
|
||||||
|
本项目已完成完整的产品设计和技术设计,所有文档已保存在 `docs/` 目录下。
|
||||||
|
|
||||||
|
### 📁 文档结构
|
||||||
|
|
||||||
|
```
|
||||||
|
docs/
|
||||||
|
├── requirements/ # 需求文档
|
||||||
|
│ └── product-requirements.md # 产品需求文档
|
||||||
|
├── designs/ # 设计文档
|
||||||
|
│ ├── product-architecture.md # 产品逻辑架构
|
||||||
|
│ ├── technical-architecture.md # 技术架构
|
||||||
|
│ └── database-design.md # 数据库设计
|
||||||
|
├── tasks/ # 任务文档
|
||||||
|
│ ├── README.md # 任务清单
|
||||||
|
│ ├── 01-project-setup.md # 项目初始化
|
||||||
|
│ ├── 02-database-setup.md # 数据库搭建
|
||||||
|
│ ├── 03-backend-core.md # 后端核心框架
|
||||||
|
│ ├── 04-collectors.md # 采集器实现
|
||||||
|
│ ├── 05-processor.md # 内容处理
|
||||||
|
│ ├── 06-report-generator.md # 报告生成
|
||||||
|
│ ├── 07-distributors.md # 分发器实现
|
||||||
|
│ ├── 08-scheduler.md # 定时任务调度
|
||||||
|
│ ├── 09-web-api.md # Web API 实现
|
||||||
|
│ ├── 10-frontend-setup.md # 前端初始化
|
||||||
|
│ └── 11-16-summary.md # 任务 11-16 简要说明
|
||||||
|
└── DEVELOPMENT.md # 开发指南
|
||||||
|
```
|
||||||
|
|
||||||
|
## 项目概述
|
||||||
|
|
||||||
|
### 产品定位
|
||||||
|
基于配置的资讯聚合系统,自动收集指定主题的资讯,通过 AI 整理后生成每日报告,并推送到指定渠道。
|
||||||
|
|
||||||
|
### 核心功能
|
||||||
|
1. **多数据源采集**:API、Playwright 网页爬取、RSS
|
||||||
|
2. **AI 内容处理**:简单聚合、AI 摘要、AI 深度整理
|
||||||
|
3. **报告生成**:按主题独立生成,支持定时和手动触发
|
||||||
|
4. **多渠道推送**:邮件、钉钉、企业微信、Slack
|
||||||
|
5. **Web 管理界面**:配置管理、报告查看、资讯浏览、采集监控
|
||||||
|
6. **AI Agent**:基于报告/资讯的深入探索
|
||||||
|
|
||||||
|
### 技术栈
|
||||||
|
- **后端**:Node.js + TypeScript + Fastify + Prisma + MySQL
|
||||||
|
- **前端**:Vue 3 + TypeScript + Vite + Element Plus
|
||||||
|
- **其他**:Playwright、OpenAI SDK、node-cron、PM2
|
||||||
|
|
||||||
|
## 设计文档说明
|
||||||
|
|
||||||
|
### 1. 产品需求文档
|
||||||
|
**文件**:`docs/requirements/product-requirements.md`
|
||||||
|
|
||||||
|
**内容**:
|
||||||
|
- 产品概述和核心价值
|
||||||
|
- 详细功能需求
|
||||||
|
- 非功能需求
|
||||||
|
- 数据流设计
|
||||||
|
- 用户使用流程
|
||||||
|
- 版本规划
|
||||||
|
|
||||||
|
**关键点**:
|
||||||
|
- 主题是配置的核心单元
|
||||||
|
- 数据源独立管理,可被多个主题复用
|
||||||
|
- 资讯归属所有关联该数据源的主题
|
||||||
|
- 报告按主题独立生成和推送
|
||||||
|
|
||||||
|
### 2. 产品逻辑架构
|
||||||
|
**文件**:`docs/designs/product-architecture.md`
|
||||||
|
|
||||||
|
**内容**:
|
||||||
|
- 核心概念模型(实体关系)
|
||||||
|
- 数据流设计(采集流、报告生成流、推送流、消费流)
|
||||||
|
- Web 端功能模块
|
||||||
|
- 业务流程
|
||||||
|
- 关键设计决策
|
||||||
|
|
||||||
|
**核心实体**:
|
||||||
|
- LLM 配置
|
||||||
|
- 数据源
|
||||||
|
- 推送渠道
|
||||||
|
- 主题(核心)
|
||||||
|
- 资讯
|
||||||
|
- 报告
|
||||||
|
|
||||||
|
### 3. 技术架构
|
||||||
|
**文件**:`docs/designs/technical-architecture.md`
|
||||||
|
|
||||||
|
**内容**:
|
||||||
|
- 技术选型
|
||||||
|
- 系统架构设计
|
||||||
|
- 目录结构
|
||||||
|
- 核心模块设计(采集器、分发器、服务层)
|
||||||
|
- 关键流程时序
|
||||||
|
- API 设计
|
||||||
|
- 安全设计
|
||||||
|
- 性能优化
|
||||||
|
- 部署架构
|
||||||
|
|
||||||
|
**架构特点**:
|
||||||
|
- 单体应用架构(适合初期)
|
||||||
|
- 插件式采集器和分发器
|
||||||
|
- 服务层封装业务逻辑
|
||||||
|
- RESTful API 设计
|
||||||
|
|
||||||
|
### 4. 数据库设计
|
||||||
|
**文件**:`docs/designs/database-design.md`
|
||||||
|
|
||||||
|
**内容**:
|
||||||
|
- 完整的表结构设计(11 张表)
|
||||||
|
- ER 图
|
||||||
|
- Prisma Schema
|
||||||
|
- 数据迁移策略
|
||||||
|
- 性能优化(索引、分区)
|
||||||
|
|
||||||
|
**核心表**:
|
||||||
|
- 配置表:llm_configs、sources、channels、topics
|
||||||
|
- 关联表:topic_sources、topic_channels
|
||||||
|
- 数据表:articles、reports
|
||||||
|
- 日志表:collection_logs、push_logs、conversations
|
||||||
|
|
||||||
|
## 任务文档说明
|
||||||
|
|
||||||
|
### 已完成详细文档的任务(01-10)
|
||||||
|
|
||||||
|
#### 任务 01:项目初始化
|
||||||
|
- 创建项目目录结构
|
||||||
|
- 初始化后端项目(Node.js + TypeScript + Fastify)
|
||||||
|
- 初始化前端项目(Vue 3 + TypeScript + Vite)
|
||||||
|
- 配置开发环境
|
||||||
|
|
||||||
|
#### 任务 02:数据库搭建
|
||||||
|
- 创建 Prisma Schema(11 张表)
|
||||||
|
- 执行数据库迁移
|
||||||
|
- 生成 Prisma Client
|
||||||
|
- 创建种子数据
|
||||||
|
|
||||||
|
#### 任务 03:后端核心框架
|
||||||
|
- 创建 Fastify 应用
|
||||||
|
- 配置管理
|
||||||
|
- 统一响应格式
|
||||||
|
- 错误处理中间件
|
||||||
|
- 日志系统
|
||||||
|
|
||||||
|
#### 任务 04:采集器实现
|
||||||
|
- 采集器基类
|
||||||
|
- API 采集器
|
||||||
|
- Playwright 采集器
|
||||||
|
- RSS 采集器
|
||||||
|
- 采集器工厂
|
||||||
|
- 采集服务
|
||||||
|
|
||||||
|
#### 任务 05:内容处理
|
||||||
|
- LLM 客户端封装
|
||||||
|
- 三种处理模式(聚合、摘要、深度整理)
|
||||||
|
- 去重逻辑
|
||||||
|
- 排序功能
|
||||||
|
|
||||||
|
#### 任务 06:报告生成
|
||||||
|
- 报告生成服务
|
||||||
|
- 按时间范围查询资讯
|
||||||
|
- 集成内容处理
|
||||||
|
- 报告保存和查询
|
||||||
|
|
||||||
|
#### 任务 07:分发器实现
|
||||||
|
- 分发器基类
|
||||||
|
- 邮件分发器
|
||||||
|
- 钉钉分发器
|
||||||
|
- 企业微信分发器
|
||||||
|
- Slack 分发器
|
||||||
|
- 分发服务
|
||||||
|
|
||||||
|
#### 任务 08:定时任务调度
|
||||||
|
- 调度服务
|
||||||
|
- 采集任务调度
|
||||||
|
- 报告生成任务调度
|
||||||
|
- 手动触发功能
|
||||||
|
- 优雅关闭
|
||||||
|
|
||||||
|
#### 任务 09:Web API 实现
|
||||||
|
- LLM 配置 API
|
||||||
|
- 数据源管理 API
|
||||||
|
- 推送渠道管理 API
|
||||||
|
- 主题管理 API
|
||||||
|
- 报告查询 API
|
||||||
|
- 资讯浏览 API
|
||||||
|
- 采集监控 API
|
||||||
|
|
||||||
|
#### 任务 10:前端初始化
|
||||||
|
- 配置 Vue Router
|
||||||
|
- 配置 Pinia 状态管理
|
||||||
|
- 配置 Element Plus
|
||||||
|
- 创建基础布局
|
||||||
|
- 配置 API 请求
|
||||||
|
- 实现仪表盘页面
|
||||||
|
|
||||||
|
### 简要说明的任务(11-16)
|
||||||
|
|
||||||
|
**文件**:`docs/tasks/11-16-summary.md`
|
||||||
|
|
||||||
|
- 任务 11:前端配置管理
|
||||||
|
- 任务 12:前端报告中心
|
||||||
|
- 任务 13:前端资讯浏览
|
||||||
|
- 任务 14:前端采集监控
|
||||||
|
- 任务 15:AI Agent 实现
|
||||||
|
- 任务 16:部署配置
|
||||||
|
|
||||||
|
## 开发指南
|
||||||
|
|
||||||
|
**文件**:`docs/DEVELOPMENT.md`
|
||||||
|
|
||||||
|
**内容**:
|
||||||
|
- 快速开始
|
||||||
|
- 开发流程
|
||||||
|
- 代码规范(TypeScript、Vue)
|
||||||
|
- 测试指南
|
||||||
|
- 调试技巧
|
||||||
|
- 常见问题
|
||||||
|
- 性能优化
|
||||||
|
- 安全最佳实践
|
||||||
|
|
||||||
|
## 项目特点
|
||||||
|
|
||||||
|
### 1. 完整的文档体系
|
||||||
|
- 从需求到设计到实施的完整文档
|
||||||
|
- 每个任务都有详细的步骤和验证方法
|
||||||
|
- 包含代码示例和配置示例
|
||||||
|
|
||||||
|
### 2. 模块化设计
|
||||||
|
- 插件式采集器和分发器
|
||||||
|
- 服务层封装业务逻辑
|
||||||
|
- 清晰的分层架构
|
||||||
|
|
||||||
|
### 3. 灵活的配置
|
||||||
|
- 支持多个 LLM 配置
|
||||||
|
- 支持多种数据源类型
|
||||||
|
- 支持多种推送渠道
|
||||||
|
- 主题可灵活组合配置
|
||||||
|
|
||||||
|
### 4. 可扩展性
|
||||||
|
- 易于添加新的采集器类型
|
||||||
|
- 易于添加新的分发器类型
|
||||||
|
- 预留多用户扩展
|
||||||
|
- 预留 AI Agent 功能
|
||||||
|
|
||||||
|
### 5. 开发友好
|
||||||
|
- TypeScript 类型安全
|
||||||
|
- Prisma ORM 简化数据库操作
|
||||||
|
- 详细的错误处理和日志
|
||||||
|
- 完善的开发工具配置
|
||||||
|
|
||||||
|
## 实施建议
|
||||||
|
|
||||||
|
### 阶段一:MVP(最小可行产品)
|
||||||
|
**目标**:实现核心功能,验证产品可行性
|
||||||
|
|
||||||
|
**任务**:01-09
|
||||||
|
- 后端核心功能
|
||||||
|
- API 接口
|
||||||
|
- 基础测试
|
||||||
|
|
||||||
|
**时间**:约 8-12 天
|
||||||
|
|
||||||
|
**验证**:
|
||||||
|
- 能够采集资讯
|
||||||
|
- 能够生成报告
|
||||||
|
- 能够推送报告
|
||||||
|
- API 可以正常调用
|
||||||
|
|
||||||
|
### 阶段二:Web 界面
|
||||||
|
**目标**:提供可视化管理界面
|
||||||
|
|
||||||
|
**任务**:10-14
|
||||||
|
- 前端基础设施
|
||||||
|
- 配置管理页面
|
||||||
|
- 报告查看页面
|
||||||
|
- 资讯浏览页面
|
||||||
|
- 采集监控页面
|
||||||
|
|
||||||
|
**时间**:约 6-9 天
|
||||||
|
|
||||||
|
**验证**:
|
||||||
|
- 可以通过 Web 界面完成所有配置
|
||||||
|
- 可以查看报告和资讯
|
||||||
|
- 可以监控采集状态
|
||||||
|
|
||||||
|
### 阶段三:AI 增强
|
||||||
|
**目标**:增加 AI 交互能力
|
||||||
|
|
||||||
|
**任务**:15
|
||||||
|
- AI Agent 实现
|
||||||
|
- 对话界面
|
||||||
|
- 流式响应
|
||||||
|
|
||||||
|
**时间**:约 2-3 天
|
||||||
|
|
||||||
|
**验证**:
|
||||||
|
- 可以与 AI 对话
|
||||||
|
- AI 能够理解上下文
|
||||||
|
- AI 能够获取额外信息
|
||||||
|
|
||||||
|
### 阶段四:生产部署
|
||||||
|
**目标**:部署到生产环境
|
||||||
|
|
||||||
|
**任务**:16
|
||||||
|
- 构建配置
|
||||||
|
- 部署脚本
|
||||||
|
- 监控和日志
|
||||||
|
- 备份策略
|
||||||
|
|
||||||
|
**时间**:约 1 天
|
||||||
|
|
||||||
|
**验证**:
|
||||||
|
- 应用在生产环境稳定运行
|
||||||
|
- 日志和监控正常
|
||||||
|
- 备份策略生效
|
||||||
|
|
||||||
|
## 总结
|
||||||
|
|
||||||
|
### 已完成的工作
|
||||||
|
✅ 完整的产品需求分析
|
||||||
|
✅ 详细的产品逻辑架构设计
|
||||||
|
✅ 完整的技术架构设计
|
||||||
|
✅ 详细的数据库设计
|
||||||
|
✅ 任务 01-10 的详细实施文档
|
||||||
|
✅ 任务 11-16 的简要说明
|
||||||
|
✅ 开发指南文档
|
||||||
|
✅ 项目 README
|
||||||
|
|
||||||
|
### 文档统计
|
||||||
|
- **总文档数**:17 个 Markdown 文件
|
||||||
|
- **总字数**:约 50,000+ 字
|
||||||
|
- **代码示例**:100+ 个
|
||||||
|
- **任务步骤**:200+ 个
|
||||||
|
|
||||||
|
### 下一步行动
|
||||||
|
|
||||||
|
1. **审查文档**
|
||||||
|
- 检查文档完整性
|
||||||
|
- 确认技术选型
|
||||||
|
- 验证设计合理性
|
||||||
|
|
||||||
|
2. **开始实施**
|
||||||
|
- 按任务顺序开始开发
|
||||||
|
- 每完成一个任务进行验证
|
||||||
|
- 及时更新文档
|
||||||
|
|
||||||
|
3. **持续迭代**
|
||||||
|
- 根据实际情况调整设计
|
||||||
|
- 补充遗漏的细节
|
||||||
|
- 优化实现方案
|
||||||
|
|
||||||
|
## 文档使用指南
|
||||||
|
|
||||||
|
### 对于开发者
|
||||||
|
1. 先阅读 `README.md` 了解项目概况
|
||||||
|
2. 阅读 `docs/requirements/product-requirements.md` 理解产品需求
|
||||||
|
3. 阅读 `docs/designs/` 下的设计文档理解架构
|
||||||
|
4. 按 `docs/tasks/` 下的任务文档逐步实施
|
||||||
|
5. 参考 `docs/DEVELOPMENT.md` 了解开发规范
|
||||||
|
|
||||||
|
### 对于项目管理者
|
||||||
|
1. 查看 `docs/tasks/README.md` 了解任务清单
|
||||||
|
2. 根据任务预估工作量和时间
|
||||||
|
3. 安排开发资源和进度
|
||||||
|
4. 跟踪任务完成情况
|
||||||
|
|
||||||
|
### 对于产品经理
|
||||||
|
1. 阅读 `docs/requirements/product-requirements.md` 了解功能需求
|
||||||
|
2. 阅读 `docs/designs/product-architecture.md` 了解产品逻辑
|
||||||
|
3. 根据实际需求调整功能优先级
|
||||||
|
4. 补充用户故事和验收标准
|
||||||
|
|
||||||
|
## 联系方式
|
||||||
|
|
||||||
|
如有问题或建议,请通过以下方式联系:
|
||||||
|
- 项目 Issues
|
||||||
|
- 邮件
|
||||||
|
- 其他沟通渠道
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**文档版本**:v1.0
|
||||||
|
**最后更新**:2024-01-01
|
||||||
|
**维护者**:开发团队
|
||||||
|
|
||||||
|
**注意**:本文档会随着项目进展持续更新。
|
||||||
@@ -0,0 +1,420 @@
|
|||||||
|
# News Aggregator - 数据库设计
|
||||||
|
|
||||||
|
## 1. 数据库概述
|
||||||
|
|
||||||
|
### 1.1 数据库信息
|
||||||
|
- **数据库类型**:MySQL 5.6
|
||||||
|
- **字符集**:utf8mb4
|
||||||
|
- **排序规则**:utf8mb4_unicode_ci
|
||||||
|
- **ORM**:Prisma
|
||||||
|
|
||||||
|
### 1.2 设计原则
|
||||||
|
- 遵循第三范式
|
||||||
|
- 预留 user_id 字段支持多用户扩展
|
||||||
|
- 使用软删除(部分表)
|
||||||
|
- 时间字段统一使用 DATETIME 类型
|
||||||
|
- JSON 字段存储灵活配置
|
||||||
|
|
||||||
|
## 2. 表结构设计
|
||||||
|
|
||||||
|
### 2.1 配置相关表
|
||||||
|
|
||||||
|
#### llm_configs (LLM配置表)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 约束 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | INT | PK, AUTO_INCREMENT | 主键 |
|
||||||
|
| name | VARCHAR(100) | NOT NULL | 配置名称 |
|
||||||
|
| base_url | VARCHAR(500) | NOT NULL | API 基础地址 |
|
||||||
|
| model | VARCHAR(100) | NOT NULL | 模型名称 |
|
||||||
|
| api_key | VARCHAR(500) | NOT NULL | API 密钥(加密存储) |
|
||||||
|
| enabled | TINYINT(1) | NOT NULL, DEFAULT 1 | 是否启用 |
|
||||||
|
| user_id | INT | NULL | 用户ID(预留) |
|
||||||
|
| created_at | DATETIME | NOT NULL | 创建时间 |
|
||||||
|
| updated_at | DATETIME | NOT NULL | 更新时间 |
|
||||||
|
|
||||||
|
**索引**:
|
||||||
|
- PRIMARY KEY (id)
|
||||||
|
- INDEX idx_user_enabled (user_id, enabled)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### sources (数据源表)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 约束 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | INT | PK, AUTO_INCREMENT | 主键 |
|
||||||
|
| name | VARCHAR(100) | NOT NULL | 数据源名称 |
|
||||||
|
| type | VARCHAR(50) | NOT NULL | 类型:api/playwright/rss |
|
||||||
|
| config | JSON | NOT NULL | 采集配置(API地址、选择器等) |
|
||||||
|
| cron_expression | VARCHAR(100) | NOT NULL | 采集频率(cron表达式) |
|
||||||
|
| enabled | TINYINT(1) | NOT NULL, DEFAULT 1 | 是否启用 |
|
||||||
|
| last_collected_at | DATETIME | NULL | 最后采集时间 |
|
||||||
|
| user_id | INT | NULL | 用户ID(预留) |
|
||||||
|
| created_at | DATETIME | NOT NULL | 创建时间 |
|
||||||
|
| updated_at | DATETIME | NOT NULL | 更新时间 |
|
||||||
|
|
||||||
|
**索引**:
|
||||||
|
- PRIMARY KEY (id)
|
||||||
|
- INDEX idx_user_enabled (user_id, enabled)
|
||||||
|
- INDEX idx_type (type)
|
||||||
|
|
||||||
|
**config 字段示例**:
|
||||||
|
```json
|
||||||
|
// API 类型
|
||||||
|
{
|
||||||
|
"url": "https://api.example.com/news",
|
||||||
|
"method": "GET",
|
||||||
|
"headers": {},
|
||||||
|
"params": {},
|
||||||
|
"dataPath": "data.items",
|
||||||
|
"mapping": {
|
||||||
|
"title": "title",
|
||||||
|
"content": "description",
|
||||||
|
"url": "link",
|
||||||
|
"publishedAt": "pubDate"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Playwright 类型
|
||||||
|
{
|
||||||
|
"url": "https://example.com/news",
|
||||||
|
"selectors": {
|
||||||
|
"items": ".news-item",
|
||||||
|
"title": ".title",
|
||||||
|
"content": ".content",
|
||||||
|
"url": "a",
|
||||||
|
"publishedAt": ".date"
|
||||||
|
},
|
||||||
|
"waitFor": ".news-item",
|
||||||
|
"script": "// 可选的自定义脚本"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### channels (推送渠道表)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 约束 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | INT | PK, AUTO_INCREMENT | 主键 |
|
||||||
|
| name | VARCHAR(100) | NOT NULL | 渠道名称 |
|
||||||
|
| type | VARCHAR(50) | NOT NULL | 类型:email/dingtalk/wechat/slack |
|
||||||
|
| config | JSON | NOT NULL | 渠道配置 |
|
||||||
|
| enabled | TINYINT(1) | NOT NULL, DEFAULT 1 | 是否启用 |
|
||||||
|
| user_id | INT | NULL | 用户ID(预留) |
|
||||||
|
| created_at | DATETIME | NOT NULL | 创建时间 |
|
||||||
|
| updated_at | DATETIME | NOT NULL | 更新时间 |
|
||||||
|
|
||||||
|
**索引**:
|
||||||
|
- PRIMARY KEY (id)
|
||||||
|
- INDEX idx_user_enabled (user_id, enabled)
|
||||||
|
- INDEX idx_type (type)
|
||||||
|
|
||||||
|
**config 字段示例**:
|
||||||
|
```json
|
||||||
|
// Email 类型
|
||||||
|
{
|
||||||
|
"smtp": {
|
||||||
|
"host": "smtp.example.com",
|
||||||
|
"port": 465,
|
||||||
|
"secure": true,
|
||||||
|
"auth": {
|
||||||
|
"user": "user@example.com",
|
||||||
|
"pass": "password"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"from": "News Aggregator <noreply@example.com>",
|
||||||
|
"to": ["user@example.com"]
|
||||||
|
}
|
||||||
|
|
||||||
|
// 钉钉类型
|
||||||
|
{
|
||||||
|
"webhook": "https://oapi.dingtalk.com/robot/send?access_token=xxx",
|
||||||
|
"secret": "SECxxx"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### topics (主题表)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 约束 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | INT | PK, AUTO_INCREMENT | 主键 |
|
||||||
|
| name | VARCHAR(100) | NOT NULL | 主题名称 |
|
||||||
|
| description | TEXT | NULL | 主题描述 |
|
||||||
|
| process_mode | VARCHAR(50) | NOT NULL | 处理模式:aggregate/summary/deep_analysis |
|
||||||
|
| llm_config_id | INT | NULL | 关联的LLM配置ID |
|
||||||
|
| schedule_config | JSON | NOT NULL | 推送时间配置 |
|
||||||
|
| enabled | TINYINT(1) | NOT NULL, DEFAULT 1 | 是否启用 |
|
||||||
|
| user_id | INT | NULL | 用户ID(预留) |
|
||||||
|
| created_at | DATETIME | NOT NULL | 创建时间 |
|
||||||
|
| updated_at | DATETIME | NOT NULL | 更新时间 |
|
||||||
|
|
||||||
|
**索引**:
|
||||||
|
- PRIMARY KEY (id)
|
||||||
|
- INDEX idx_user_enabled (user_id, enabled)
|
||||||
|
- FOREIGN KEY (llm_config_id) REFERENCES llm_configs(id)
|
||||||
|
|
||||||
|
**schedule_config 字段示例**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cron": "0 9 * * *", // 每天9点
|
||||||
|
"timezone": "Asia/Shanghai",
|
||||||
|
"period": "daily", // daily/weekly/monthly
|
||||||
|
"lookback": 24 // 回溯小时数
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### topic_sources (主题-数据源关联表)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 约束 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | INT | PK, AUTO_INCREMENT | 主键 |
|
||||||
|
| topic_id | INT | NOT NULL | 主题ID |
|
||||||
|
| source_id | INT | NOT NULL | 数据源ID |
|
||||||
|
| created_at | DATETIME | NOT NULL | 创建时间 |
|
||||||
|
|
||||||
|
**索引**:
|
||||||
|
- PRIMARY KEY (id)
|
||||||
|
- UNIQUE KEY uk_topic_source (topic_id, source_id)
|
||||||
|
- INDEX idx_topic (topic_id)
|
||||||
|
- INDEX idx_source (source_id)
|
||||||
|
- FOREIGN KEY (topic_id) REFERENCES topics(id) ON DELETE CASCADE
|
||||||
|
- FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### topic_channels (主题-推送渠道关联表)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 约束 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | INT | PK, AUTO_INCREMENT | 主键 |
|
||||||
|
| topic_id | INT | NOT NULL | 主题ID |
|
||||||
|
| channel_id | INT | NOT NULL | 渠道ID |
|
||||||
|
| created_at | DATETIME | NOT NULL | 创建时间 |
|
||||||
|
|
||||||
|
**索引**:
|
||||||
|
- PRIMARY KEY (id)
|
||||||
|
- UNIQUE KEY uk_topic_channel (topic_id, channel_id)
|
||||||
|
- INDEX idx_topic (topic_id)
|
||||||
|
- INDEX idx_channel (channel_id)
|
||||||
|
- FOREIGN KEY (topic_id) REFERENCES topics(id) ON DELETE CASCADE
|
||||||
|
- FOREIGN KEY (channel_id) REFERENCES channels(id) ON DELETE CASCADE
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.2 数据相关表
|
||||||
|
|
||||||
|
#### articles (资讯表)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 约束 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | INT | PK, AUTO_INCREMENT | 主键 |
|
||||||
|
| source_id | INT | NOT NULL | 数据源ID |
|
||||||
|
| title | VARCHAR(500) | NOT NULL | 标题 |
|
||||||
|
| content | TEXT | NULL | 内容 |
|
||||||
|
| summary | TEXT | NULL | 摘要 |
|
||||||
|
| url | VARCHAR(1000) | NULL | 原文链接 |
|
||||||
|
| published_at | DATETIME | NULL | 发布时间 |
|
||||||
|
| collected_at | DATETIME | NOT NULL | 采集时间 |
|
||||||
|
| raw_data | JSON | NULL | 原始采集数据 |
|
||||||
|
| created_at | DATETIME | NOT NULL | 创建时间 |
|
||||||
|
|
||||||
|
**索引**:
|
||||||
|
- PRIMARY KEY (id)
|
||||||
|
- INDEX idx_source (source_id)
|
||||||
|
- INDEX idx_published (published_at)
|
||||||
|
- INDEX idx_collected (collected_at)
|
||||||
|
- INDEX idx_url (url(255))
|
||||||
|
- FOREIGN KEY (source_id) REFERENCES sources(id)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### reports (报告表)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 约束 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | INT | PK, AUTO_INCREMENT | 主键 |
|
||||||
|
| topic_id | INT | NOT NULL | 主题ID |
|
||||||
|
| title | VARCHAR(500) | NOT NULL | 报告标题 |
|
||||||
|
| content | LONGTEXT | NOT NULL | 报告内容 |
|
||||||
|
| period_start | DATETIME | NOT NULL | 时间范围开始 |
|
||||||
|
| period_end | DATETIME | NOT NULL | 时间范围结束 |
|
||||||
|
| status | VARCHAR(50) | NOT NULL | 状态:pending/generating/completed/failed |
|
||||||
|
| error_message | TEXT | NULL | 错误信息 |
|
||||||
|
| article_count | INT | NOT NULL, DEFAULT 0 | 资讯数量 |
|
||||||
|
| user_id | INT | NULL | 用户ID(预留) |
|
||||||
|
| created_at | DATETIME | NOT NULL | 创建时间 |
|
||||||
|
| updated_at | DATETIME | NOT NULL | 更新时间 |
|
||||||
|
|
||||||
|
**索引**:
|
||||||
|
- PRIMARY KEY (id)
|
||||||
|
- INDEX idx_topic (topic_id)
|
||||||
|
- INDEX idx_status (status)
|
||||||
|
- INDEX idx_period (period_start, period_end)
|
||||||
|
- INDEX idx_user_created (user_id, created_at)
|
||||||
|
- FOREIGN KEY (topic_id) REFERENCES topics(id)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.3 运行相关表
|
||||||
|
|
||||||
|
#### collection_logs (采集日志表)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 约束 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | INT | PK, AUTO_INCREMENT | 主键 |
|
||||||
|
| source_id | INT | NOT NULL | 数据源ID |
|
||||||
|
| status | VARCHAR(50) | NOT NULL | 状态:success/failed |
|
||||||
|
| error_message | TEXT | NULL | 错误信息 |
|
||||||
|
| articles_count | INT | NOT NULL, DEFAULT 0 | 采集到的资讯数量 |
|
||||||
|
| started_at | DATETIME | NOT NULL | 开始时间 |
|
||||||
|
| finished_at | DATETIME | NULL | 结束时间 |
|
||||||
|
| duration_ms | INT | NULL | 耗时(毫秒) |
|
||||||
|
| created_at | DATETIME | NOT NULL | 创建时间 |
|
||||||
|
|
||||||
|
**索引**:
|
||||||
|
- PRIMARY KEY (id)
|
||||||
|
- INDEX idx_source (source_id)
|
||||||
|
- INDEX idx_status (status)
|
||||||
|
- INDEX idx_started (started_at)
|
||||||
|
- FOREIGN KEY (source_id) REFERENCES sources(id)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### push_logs (推送日志表)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 约束 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | INT | PK, AUTO_INCREMENT | 主键 |
|
||||||
|
| report_id | INT | NOT NULL | 报告ID |
|
||||||
|
| channel_id | INT | NOT NULL | 渠道ID |
|
||||||
|
| status | VARCHAR(50) | NOT NULL | 状态:success/failed |
|
||||||
|
| error_message | TEXT | NULL | 错误信息 |
|
||||||
|
| created_at | DATETIME | NOT NULL | 创建时间 |
|
||||||
|
|
||||||
|
**索引**:
|
||||||
|
- PRIMARY KEY (id)
|
||||||
|
- INDEX idx_report (report_id)
|
||||||
|
- INDEX idx_channel (channel_id)
|
||||||
|
- INDEX idx_status (status)
|
||||||
|
- FOREIGN KEY (report_id) REFERENCES reports(id)
|
||||||
|
- FOREIGN KEY (channel_id) REFERENCES channels(id)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### conversations (AI对话记录表) - 可选
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 约束 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | INT | PK, AUTO_INCREMENT | 主键 |
|
||||||
|
| report_id | INT | NULL | 报告ID |
|
||||||
|
| article_id | INT | NULL | 资讯ID |
|
||||||
|
| topic_id | INT | NOT NULL | 主题ID |
|
||||||
|
| messages | JSON | NOT NULL | 对话历史 |
|
||||||
|
| user_id | INT | NULL | 用户ID(预留) |
|
||||||
|
| created_at | DATETIME | NOT NULL | 创建时间 |
|
||||||
|
| updated_at | DATETIME | NOT NULL | 更新时间 |
|
||||||
|
|
||||||
|
**索引**:
|
||||||
|
- PRIMARY KEY (id)
|
||||||
|
- INDEX idx_report (report_id)
|
||||||
|
- INDEX idx_article (article_id)
|
||||||
|
- INDEX idx_topic (topic_id)
|
||||||
|
- INDEX idx_user (user_id)
|
||||||
|
- FOREIGN KEY (report_id) REFERENCES reports(id)
|
||||||
|
- FOREIGN KEY (article_id) REFERENCES articles(id)
|
||||||
|
- FOREIGN KEY (topic_id) REFERENCES topics(id)
|
||||||
|
|
||||||
|
**messages 字段示例**:
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": "这个功能具体怎么用?",
|
||||||
|
"timestamp": "2024-01-01T10:00:00Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "assistant",
|
||||||
|
"content": "根据资讯内容...",
|
||||||
|
"timestamp": "2024-01-01T10:00:05Z"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. ER 图
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
|
||||||
|
│ llm_configs │ │ channels │ │ sources │
|
||||||
|
└─────────────┘ └─────────────┘ └─────────────┘
|
||||||
|
│ │ │
|
||||||
|
│ │ │
|
||||||
|
└───────────┬───────────┴───────────┬───────────┘
|
||||||
|
│ │
|
||||||
|
▼ ▼
|
||||||
|
┌─────────────┐ ┌──────────────┐
|
||||||
|
│ topics │◄────────┤topic_sources │
|
||||||
|
└─────────────┘ └──────────────┘
|
||||||
|
│ │
|
||||||
|
│ │
|
||||||
|
┌──────┴──────┐ │
|
||||||
|
│ │ │
|
||||||
|
▼ ▼ ▼
|
||||||
|
┌──────────────┐ ┌─────────────┐ ┌─────────────┐
|
||||||
|
│topic_channels│ │ reports │ │ articles │
|
||||||
|
└──────────────┘ └─────────────┘ └─────────────┘
|
||||||
|
│ │ │
|
||||||
|
│ │ │
|
||||||
|
▼ ▼ ▼
|
||||||
|
┌─────────────┐ ┌─────────────┐ ┌──────────────┐
|
||||||
|
│ channels │ │ push_logs │ │collection_logs│
|
||||||
|
└─────────────┘ └─────────────┘ └──────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
## 4. Prisma Schema
|
||||||
|
|
||||||
|
完整的 Prisma Schema 将在项目初始化时创建,包含所有表定义和关系。
|
||||||
|
|
||||||
|
## 5. 数据迁移策略
|
||||||
|
|
||||||
|
### 5.1 初始化
|
||||||
|
- 使用 Prisma Migrate 创建初始数据库结构
|
||||||
|
- 提供种子数据脚本
|
||||||
|
|
||||||
|
### 5.2 版本升级
|
||||||
|
- 使用 Prisma Migrate 管理数据库变更
|
||||||
|
- 每次变更创建迁移文件
|
||||||
|
- 提供回滚方案
|
||||||
|
|
||||||
|
## 6. 数据备份策略
|
||||||
|
|
||||||
|
### 6.1 定期备份
|
||||||
|
- 每日自动备份数据库
|
||||||
|
- 保留最近 7 天的备份
|
||||||
|
|
||||||
|
### 6.2 重要操作前备份
|
||||||
|
- 数据库结构变更前备份
|
||||||
|
- 批量数据操作前备份
|
||||||
|
|
||||||
|
## 7. 性能优化
|
||||||
|
|
||||||
|
### 7.1 索引优化
|
||||||
|
- 为常用查询字段添加索引
|
||||||
|
- 为外键添加索引
|
||||||
|
- 定期分析慢查询
|
||||||
|
|
||||||
|
### 7.2 分区策略(可选)
|
||||||
|
- articles 表按时间分区(数据量大时)
|
||||||
|
- collection_logs 表按时间分区
|
||||||
|
|
||||||
|
### 7.3 归档策略
|
||||||
|
- 定期归档历史数据
|
||||||
|
- articles 表保留最近 3 个月数据
|
||||||
|
- logs 表保留最近 1 个月数据
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
# News Aggregator - 产品逻辑架构
|
||||||
|
|
||||||
|
## 1. 核心概念模型
|
||||||
|
|
||||||
|
### 1.1 实体关系图
|
||||||
|
|
||||||
|
```
|
||||||
|
┌──────────┐ ┌──────────┐ ┌──────────┐
|
||||||
|
│ LLM 配置 │ │ 推送渠道 │ │ 数据源 │
|
||||||
|
│ │ │ │ │ │
|
||||||
|
│ -baseUrl │ │ -类型 │ │ -名称 │
|
||||||
|
│ -model │ │ -配置 │ │ -类型 │
|
||||||
|
│ -token │ │ (邮件/ │ │ (API/ │
|
||||||
|
│ │ │ 钉钉等) │ │ 爬虫) │
|
||||||
|
└──────────┘ └──────────┘ │ -采集频率 │
|
||||||
|
│ │ │ -采集规则 │
|
||||||
|
│ │ └──────────┘
|
||||||
|
│ │ │
|
||||||
|
└────────────┬───────┴────────────┬──────┘
|
||||||
|
▼ ▼
|
||||||
|
┌──────────────────────────────┐
|
||||||
|
│ 主题 │
|
||||||
|
│ │
|
||||||
|
│ - 名称、描述 │
|
||||||
|
│ - 关联的数据源(多个) │
|
||||||
|
│ - 关联的推送渠道(多个) │
|
||||||
|
│ - 推送时间配置 │
|
||||||
|
│ - 内容处理方式 │
|
||||||
|
│ - 使用的 LLM │
|
||||||
|
└──────────────────────────────┘
|
||||||
|
│
|
||||||
|
┌──────────────┴──────────────┐
|
||||||
|
▼ ▼
|
||||||
|
┌──────────┐ ┌──────────┐
|
||||||
|
│ 资讯 │ │ 报告 │
|
||||||
|
│ │ │ │
|
||||||
|
│ -标题 │ ──(汇总生成)──→ │ -主题 │
|
||||||
|
│ -内容 │ │ -时间范围 │
|
||||||
|
│ -来源 │ │ -内容 │
|
||||||
|
│ -时间 │ │ -状态 │
|
||||||
|
└──────────┘ └──────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.2 核心实体说明
|
||||||
|
|
||||||
|
#### LLM 配置
|
||||||
|
- 支持配置多个 LLM 实例
|
||||||
|
- 兼容 OpenAI API 格式(baseUrl/model/token 可配置)
|
||||||
|
- 可用于不同主题或任务
|
||||||
|
|
||||||
|
#### 数据源
|
||||||
|
- 独立管理,可被多个主题复用
|
||||||
|
- 三种类型:API、Playwright 爬取、RSS
|
||||||
|
- 每个数据源有独立的采集频率配置
|
||||||
|
|
||||||
|
#### 推送渠道
|
||||||
|
- 独立管理,可被多个主题复用
|
||||||
|
- 支持多种类型:邮件、钉钉、企业微信、Slack 等
|
||||||
|
|
||||||
|
#### 主题
|
||||||
|
- 配置的核心单元
|
||||||
|
- 关联数据源、推送渠道、LLM
|
||||||
|
- 配置推送时间和内容处理方式
|
||||||
|
|
||||||
|
#### 资讯
|
||||||
|
- 通过数据源采集
|
||||||
|
- 归属于关联该数据源的所有主题
|
||||||
|
- 保留原始数据完整性
|
||||||
|
|
||||||
|
#### 报告
|
||||||
|
- 按主题独立生成
|
||||||
|
- 基于时间范围内的资讯汇总
|
||||||
|
- 通过配置的渠道推送
|
||||||
|
|
||||||
|
## 2. 数据流设计
|
||||||
|
|
||||||
|
### 2.1 采集流
|
||||||
|
|
||||||
|
```
|
||||||
|
数据源A ──(定时采集)──┐
|
||||||
|
数据源B ──(定时采集)──┼──→ 资讯表 ←──(关联)── 数据源-主题映射
|
||||||
|
数据源C ──(定时采集)──┘
|
||||||
|
```
|
||||||
|
|
||||||
|
**说明**:
|
||||||
|
- 每个数据源按自己的频率独立采集
|
||||||
|
- 采集到的资讯存入资讯表
|
||||||
|
- 通过数据源-主题映射关系,资讯自动归属到相关主题
|
||||||
|
|
||||||
|
### 2.2 报告生成流
|
||||||
|
|
||||||
|
```
|
||||||
|
主题配置 ──→ 查询时间范围内的资讯 ──→ 内容处理(AI) ──→ 报告
|
||||||
|
│ │ │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ ┌────┴────┐ ┌─────┴─────┐ │
|
||||||
|
│ │按数据源 │ │简单聚合 │ │
|
||||||
|
│ │过滤资讯 │ │AI摘要 │ │
|
||||||
|
│ └─────────┘ │AI深度整理│ │
|
||||||
|
│ └──────────┘ │
|
||||||
|
│ │
|
||||||
|
└──→ 推送渠道配置 ←────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────┐
|
||||||
|
│ 邮件: 摘要 + Web链接 │
|
||||||
|
│ 钉钉: 摘要 + Web链接 │
|
||||||
|
│ 微信: 摘要 + Web链接 │
|
||||||
|
└─────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
**说明**:
|
||||||
|
- 按主题配置的时间触发报告生成
|
||||||
|
- 查询该主题关联的数据源在时间范围内的资讯
|
||||||
|
- 根据主题配置的处理方式进行内容处理
|
||||||
|
- 生成报告后通过配置的渠道推送
|
||||||
|
|
||||||
|
### 2.3 消费流
|
||||||
|
|
||||||
|
```
|
||||||
|
用户 ──→ 点击推送链接 ──→ Web报告详情 ──→ AI Agent对话
|
||||||
|
│ │
|
||||||
|
│ ▼
|
||||||
|
│ ┌──────────────┐
|
||||||
|
│ │ 读取资讯上下文│
|
||||||
|
│ │ 调用数据源 │
|
||||||
|
│ │ 联网搜索 │
|
||||||
|
│ └──────────────┘
|
||||||
|
│
|
||||||
|
└──→ 浏览原始资讯列表
|
||||||
|
```
|
||||||
|
|
||||||
|
**说明**:
|
||||||
|
- 用户收到推送后点击链接进入 Web 端
|
||||||
|
- 可查看完整报告或浏览原始资讯
|
||||||
|
- 可与 AI Agent 对话深入了解
|
||||||
|
|
||||||
|
## 3. Web 端功能模块
|
||||||
|
|
||||||
|
### 3.1 配置管理
|
||||||
|
|
||||||
|
#### LLM 配置管理
|
||||||
|
- 列表展示所有 LLM 配置
|
||||||
|
- 新增/编辑/删除 LLM 配置
|
||||||
|
- 配置项:名称、baseUrl、model、apiKey
|
||||||
|
|
||||||
|
#### 数据源管理
|
||||||
|
- 列表展示所有数据源
|
||||||
|
- 新增/编辑/删除数据源
|
||||||
|
- 配置项:名称、类型、采集规则、采集频率
|
||||||
|
- 启用/禁用数据源
|
||||||
|
|
||||||
|
#### 推送渠道管理
|
||||||
|
- 列表展示所有推送渠道
|
||||||
|
- 新增/编辑/删除推送渠道
|
||||||
|
- 配置项:名称、类型、渠道配置(webhook、邮箱等)
|
||||||
|
- 启用/禁用渠道
|
||||||
|
|
||||||
|
#### 主题管理
|
||||||
|
- 列表展示所有主题
|
||||||
|
- 新增/编辑/删除主题
|
||||||
|
- 配置项:
|
||||||
|
- 基本信息:名称、描述
|
||||||
|
- 关联数据源(多选)
|
||||||
|
- 关联推送渠道(多选)
|
||||||
|
- 推送时间配置
|
||||||
|
- 内容处理方式
|
||||||
|
- 使用的 LLM
|
||||||
|
- 启用/禁用主题
|
||||||
|
|
||||||
|
### 3.2 报告中心
|
||||||
|
|
||||||
|
#### 报告列表
|
||||||
|
- 展示所有历史报告
|
||||||
|
- 按主题筛选
|
||||||
|
- 按时间范围筛选
|
||||||
|
- 显示报告状态(生成中/已完成/失败)
|
||||||
|
|
||||||
|
#### 报告详情
|
||||||
|
- 展示完整报告内容
|
||||||
|
- 显示报告元信息(主题、时间范围、生成时间)
|
||||||
|
- 列出报告中的资讯条目
|
||||||
|
- 提供 AI Agent 对话入口
|
||||||
|
|
||||||
|
#### AI Agent 对话
|
||||||
|
- 针对当前报告/资讯进行对话
|
||||||
|
- Agent 能力:
|
||||||
|
- 读取当前上下文
|
||||||
|
- 调用数据源获取更多信息
|
||||||
|
- 联网搜索
|
||||||
|
- 对比分析
|
||||||
|
|
||||||
|
### 3.3 资讯浏览
|
||||||
|
|
||||||
|
#### 资讯列表
|
||||||
|
- 展示所有采集到的资讯
|
||||||
|
- 按数据源筛选
|
||||||
|
- 按主题筛选
|
||||||
|
- 按时间范围筛选
|
||||||
|
- 显示资讯基本信息(标题、来源、时间)
|
||||||
|
|
||||||
|
#### 资讯详情
|
||||||
|
- 展示资讯完整内容
|
||||||
|
- 显示原文链接
|
||||||
|
- 显示所属主题
|
||||||
|
- 提供 AI Agent 对话入口
|
||||||
|
|
||||||
|
### 3.4 采集监控
|
||||||
|
|
||||||
|
#### 数据源状态
|
||||||
|
- 展示所有数据源的运行状态
|
||||||
|
- 显示最近采集时间
|
||||||
|
- 显示采集成功/失败次数
|
||||||
|
- 手动触发采集按钮
|
||||||
|
|
||||||
|
#### 采集日志
|
||||||
|
- 展示采集历史记录
|
||||||
|
- 按数据源筛选
|
||||||
|
- 按状态筛选(成功/失败)
|
||||||
|
- 显示错误信息
|
||||||
|
- 显示采集到的资讯数量
|
||||||
|
|
||||||
|
## 4. 业务流程
|
||||||
|
|
||||||
|
### 4.1 配置阶段
|
||||||
|
|
||||||
|
```
|
||||||
|
用户 ──→ 配置 LLM
|
||||||
|
──→ 配置数据源
|
||||||
|
──→ 配置推送渠道
|
||||||
|
──→ 创建主题(关联以上配置)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 自动运行阶段
|
||||||
|
|
||||||
|
```
|
||||||
|
定时调度器 ──→ 触发数据源采集 ──→ 保存资讯
|
||||||
|
──→ 触发报告生成 ──→ 处理资讯 ──→ 生成报告
|
||||||
|
──→ 触发报告推送 ──→ 发送到各渠道
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.3 消费阶段
|
||||||
|
|
||||||
|
```
|
||||||
|
用户 ──→ 收到推送通知
|
||||||
|
──→ 点击链接进入 Web 端
|
||||||
|
──→ 查看报告详情
|
||||||
|
──→ 与 AI Agent 对话(可选)
|
||||||
|
──→ 浏览原始资讯(可选)
|
||||||
|
```
|
||||||
|
|
||||||
|
## 5. 关键设计决策
|
||||||
|
|
||||||
|
### 5.1 数据源与主题的关系
|
||||||
|
- **决策**:数据源和主题多对多关系,数据源独立管理
|
||||||
|
- **理由**:同一个数据源可能为多个主题提供资讯,独立管理便于复用
|
||||||
|
|
||||||
|
### 5.2 资讯归属
|
||||||
|
- **决策**:资讯归属所有关联该数据源的主题
|
||||||
|
- **理由**:简化逻辑,避免复杂的过滤规则配置
|
||||||
|
|
||||||
|
### 5.3 去重策略
|
||||||
|
- **决策**:保留原始数据,去重在报告生成阶段处理
|
||||||
|
- **理由**:保持数据完整性,灵活处理不同主题的去重需求
|
||||||
|
|
||||||
|
### 5.4 推送形式
|
||||||
|
- **决策**:推送摘要 + Web链接,不推送完整内容
|
||||||
|
- **理由**:避免推送内容过长,引导用户到 Web 端获得更好体验
|
||||||
|
|
||||||
|
### 5.5 报告组织
|
||||||
|
- **决策**:每个主题独立生成报告,独立推送
|
||||||
|
- **理由**:不同主题可能有不同的推送时间和渠道,独立管理更灵活
|
||||||
|
|
||||||
|
### 5.6 采集频率
|
||||||
|
- **决策**:每个数据源独立配置采集频率
|
||||||
|
- **理由**:不同数据源的更新频率不同,独立配置更合理
|
||||||
@@ -0,0 +1,402 @@
|
|||||||
|
# News Aggregator - 技术架构
|
||||||
|
|
||||||
|
## 1. 技术选型
|
||||||
|
|
||||||
|
### 1.1 后端技术栈
|
||||||
|
|
||||||
|
| 技术 | 版本 | 用途 |
|
||||||
|
|------|------|------|
|
||||||
|
| Node.js | 20+ | 运行时环境 |
|
||||||
|
| TypeScript | 5.x | 开发语言 |
|
||||||
|
| Fastify | 最新 | Web 框架(轻量、高性能) |
|
||||||
|
| Prisma | 最新 | ORM(类型安全、迁移管理) |
|
||||||
|
| node-cron | 最新 | 定时任务调度 |
|
||||||
|
| Playwright | 最新 | 网页爬取 |
|
||||||
|
| OpenAI SDK | 最新 | LLM 调用(兼容 OpenAI API 格式) |
|
||||||
|
|
||||||
|
### 1.2 前端技术栈
|
||||||
|
|
||||||
|
| 技术 | 版本 | 用途 |
|
||||||
|
|------|------|------|
|
||||||
|
| Vue | 3.x | 前端框架 |
|
||||||
|
| TypeScript | 5.x | 开发语言 |
|
||||||
|
| Vite | 最新 | 构建工具 |
|
||||||
|
| Element Plus | 最新 | UI 组件库 |
|
||||||
|
| Pinia | 最新 | 状态管理 |
|
||||||
|
| Axios | 最新 | HTTP 请求 |
|
||||||
|
| Vue Router | 4.x | 路由管理 |
|
||||||
|
|
||||||
|
### 1.3 数据库
|
||||||
|
|
||||||
|
| 技术 | 版本 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| MySQL | 5.6 | 关系型数据库 |
|
||||||
|
|
||||||
|
### 1.4 部署运维
|
||||||
|
|
||||||
|
| 技术 | 用途 |
|
||||||
|
|------|------|
|
||||||
|
| PM2 | 进程管理 |
|
||||||
|
| Docker | 容器化(可选) |
|
||||||
|
|
||||||
|
## 2. 系统架构
|
||||||
|
|
||||||
|
### 2.1 整体架构图
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────┐
|
||||||
|
│ News Aggregator │
|
||||||
|
├─────────────────────────────────────────────────────────┤
|
||||||
|
│ Web Layer (Fastify) │
|
||||||
|
│ ├── 前端静态资源 (Vue 3) - 配置管理、报告查看 │
|
||||||
|
│ └── REST API - 配置CRUD、手动触发 │
|
||||||
|
├─────────────────────────────────────────────────────────┤
|
||||||
|
│ Core Services │
|
||||||
|
│ ├── ConfigService - 配置管理 │
|
||||||
|
│ ├── CollectorService - 数据采集调度 │
|
||||||
|
│ ├── ProcessorService - 内容处理 (AI) │
|
||||||
|
│ ├── ReportService - 报告生成 │
|
||||||
|
│ ├── DistributorService - 报告分发 │
|
||||||
|
│ ├── AgentService - AI Agent │
|
||||||
|
│ └── SchedulerService - 定时任务调度 │
|
||||||
|
├─────────────────────────────────────────────────────────┤
|
||||||
|
│ Collectors (插件式) │
|
||||||
|
│ ├── BaseCollector - 采集器基类/接口 │
|
||||||
|
│ ├── ApiCollector - 通用 API 采集器 │
|
||||||
|
│ ├── PlaywrightCollector - 网页爬取采集器 │
|
||||||
|
│ └── RssCollector - RSS 订阅采集器(可选) │
|
||||||
|
├─────────────────────────────────────────────────────────┤
|
||||||
|
│ Distributors (插件式) │
|
||||||
|
│ ├── BaseDistributor - 分发器基类/接口 │
|
||||||
|
│ ├── EmailDistributor - 邮件分发 │
|
||||||
|
│ ├── DingtalkDistributor - 钉钉分发 │
|
||||||
|
│ ├── WechatDistributor - 企业微信分发 │
|
||||||
|
│ └── SlackDistributor - Slack 分发 │
|
||||||
|
├─────────────────────────────────────────────────────────┤
|
||||||
|
│ Infrastructure │
|
||||||
|
│ ├── MySQL (Prisma) - 数据存储 │
|
||||||
|
│ ├── node-cron - 定时任务调度 │
|
||||||
|
│ └── OpenAI SDK - LLM 调用 │
|
||||||
|
└─────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 目录结构
|
||||||
|
|
||||||
|
```
|
||||||
|
news-aggregator/
|
||||||
|
├── backend/ # 后端代码
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── app.ts # 应用入口
|
||||||
|
│ │ ├── config/ # 配置文件
|
||||||
|
│ │ │ └── index.ts
|
||||||
|
│ │ ├── web/ # Web 层
|
||||||
|
│ │ │ ├── routes/ # API 路由
|
||||||
|
│ │ │ │ ├── llm-configs.ts
|
||||||
|
│ │ │ │ ├── sources.ts
|
||||||
|
│ │ │ │ ├── channels.ts
|
||||||
|
│ │ │ │ ├── topics.ts
|
||||||
|
│ │ │ │ ├── articles.ts
|
||||||
|
│ │ │ │ ├── reports.ts
|
||||||
|
│ │ │ │ └── agent.ts
|
||||||
|
│ │ │ └── middleware/ # 中间件
|
||||||
|
│ │ ├── services/ # 业务服务层
|
||||||
|
│ │ │ ├── config.service.ts
|
||||||
|
│ │ │ ├── collector.service.ts
|
||||||
|
│ │ │ ├── processor.service.ts
|
||||||
|
│ │ │ ├── report.service.ts
|
||||||
|
│ │ │ ├── distributor.service.ts
|
||||||
|
│ │ │ ├── agent.service.ts
|
||||||
|
│ │ │ └── scheduler.service.ts
|
||||||
|
│ │ ├── collectors/ # 采集器
|
||||||
|
│ │ │ ├── base.collector.ts
|
||||||
|
│ │ │ ├── api.collector.ts
|
||||||
|
│ │ │ ├── playwright.collector.ts
|
||||||
|
│ │ │ └── rss.collector.ts
|
||||||
|
│ │ ├── distributors/ # 分发器
|
||||||
|
│ │ │ ├── base.distributor.ts
|
||||||
|
│ │ │ ├── email.distributor.ts
|
||||||
|
│ │ │ ├── dingtalk.distributor.ts
|
||||||
|
│ │ │ ├── wechat.distributor.ts
|
||||||
|
│ │ │ └── slack.distributor.ts
|
||||||
|
│ │ ├── utils/ # 工具函数
|
||||||
|
│ │ └── types/ # 类型定义
|
||||||
|
│ ├── prisma/
|
||||||
|
│ │ └── schema.prisma # 数据库模型
|
||||||
|
│ ├── package.json
|
||||||
|
│ └── tsconfig.json
|
||||||
|
├── frontend/ # 前端代码
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── main.ts # 应用入口
|
||||||
|
│ │ ├── App.vue
|
||||||
|
│ │ ├── router/ # 路由配置
|
||||||
|
│ │ ├── stores/ # Pinia 状态管理
|
||||||
|
│ │ ├── views/ # 页面组件
|
||||||
|
│ │ │ ├── config/ # 配置管理页面
|
||||||
|
│ │ │ ├── reports/ # 报告中心页面
|
||||||
|
│ │ │ ├── articles/ # 资讯浏览页面
|
||||||
|
│ │ │ └── monitoring/ # 采集监控页面
|
||||||
|
│ │ ├── components/ # 公共组件
|
||||||
|
│ │ ├── api/ # API 请求
|
||||||
|
│ │ ├── types/ # 类型定义
|
||||||
|
│ │ └── utils/ # 工具函数
|
||||||
|
│ ├── package.json
|
||||||
|
│ └── tsconfig.json
|
||||||
|
├── docs/ # 文档
|
||||||
|
│ ├── requirements/
|
||||||
|
│ ├── designs/
|
||||||
|
│ └── tasks/
|
||||||
|
└── README.md
|
||||||
|
```
|
||||||
|
|
||||||
|
## 3. 核心模块设计
|
||||||
|
|
||||||
|
### 3.1 采集器设计(插件式)
|
||||||
|
|
||||||
|
#### 基类接口
|
||||||
|
```typescript
|
||||||
|
interface ICollector {
|
||||||
|
// 采集方法
|
||||||
|
collect(): Promise<Article[]>;
|
||||||
|
|
||||||
|
// 验证配置
|
||||||
|
validateConfig(config: any): boolean;
|
||||||
|
|
||||||
|
// 获取采集器类型
|
||||||
|
getType(): CollectorType;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 实现类
|
||||||
|
- **ApiCollector**:通用 API 采集器,支持配置 HTTP 请求参数
|
||||||
|
- **PlaywrightCollector**:网页爬取采集器,支持配置选择器和脚本
|
||||||
|
- **RssCollector**:RSS 订阅采集器
|
||||||
|
|
||||||
|
### 3.2 分发器设计(插件式)
|
||||||
|
|
||||||
|
#### 基类接口
|
||||||
|
```typescript
|
||||||
|
interface IDistributor {
|
||||||
|
// 分发方法
|
||||||
|
distribute(report: Report, summary: string): Promise<void>;
|
||||||
|
|
||||||
|
// 验证配置
|
||||||
|
validateConfig(config: any): boolean;
|
||||||
|
|
||||||
|
// 获取分发器类型
|
||||||
|
getType(): DistributorType;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 实现类
|
||||||
|
- **EmailDistributor**:邮件分发
|
||||||
|
- **DingtalkDistributor**:钉钉机器人分发
|
||||||
|
- **WechatDistributor**:企业微信机器人分发
|
||||||
|
- **SlackDistributor**:Slack 分发
|
||||||
|
|
||||||
|
### 3.3 服务层设计
|
||||||
|
|
||||||
|
#### CollectorService
|
||||||
|
- 管理所有采集器实例
|
||||||
|
- 根据数据源配置创建对应的采集器
|
||||||
|
- 执行采集任务
|
||||||
|
- 记录采集日志
|
||||||
|
|
||||||
|
#### ProcessorService
|
||||||
|
- 调用 LLM 进行内容处理
|
||||||
|
- 支持三种处理模式:聚合、摘要、深度整理
|
||||||
|
- 处理去重逻辑
|
||||||
|
|
||||||
|
#### ReportService
|
||||||
|
- 查询时间范围内的资讯
|
||||||
|
- 调用 ProcessorService 处理内容
|
||||||
|
- 生成报告
|
||||||
|
- 保存报告到数据库
|
||||||
|
|
||||||
|
#### DistributorService
|
||||||
|
- 管理所有分发器实例
|
||||||
|
- 根据推送渠道配置创建对应的分发器
|
||||||
|
- 执行分发任务
|
||||||
|
- 记录分发日志
|
||||||
|
|
||||||
|
#### AgentService
|
||||||
|
- 处理 AI Agent 对话
|
||||||
|
- 读取上下文(报告、资讯)
|
||||||
|
- 调用数据源获取更多信息
|
||||||
|
- 联网搜索
|
||||||
|
- 调用 LLM 生成回复
|
||||||
|
|
||||||
|
#### SchedulerService
|
||||||
|
- 管理所有定时任务
|
||||||
|
- 根据配置创建 cron 任务
|
||||||
|
- 触发采集、报告生成、推送
|
||||||
|
|
||||||
|
## 4. 关键流程时序
|
||||||
|
|
||||||
|
### 4.1 采集流程
|
||||||
|
|
||||||
|
```
|
||||||
|
Scheduler CollectorService Collector Database
|
||||||
|
│ │ │ │
|
||||||
|
│──(cron触发)──→ │ │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ 查询待采集数据源 │ │ │
|
||||||
|
│────────────────────────────────────────────────────────────────→│
|
||||||
|
│←───────────────────────────────────────────────────────────────│
|
||||||
|
│ │ │ │
|
||||||
|
│──(调用采集)──→ │ │ │
|
||||||
|
│ │──(创建采集器)──→ │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │──(执行采集)──→ │ │
|
||||||
|
│ │ │──(API/爬取)──→ 外部
|
||||||
|
│ │ │←────────────────
|
||||||
|
│ │←──(返回资讯)── │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │──(保存资讯)────────────────────────→│
|
||||||
|
│ │──(记录日志)────────────────────────→│
|
||||||
|
│←────────────────────────│ │ │
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 报告生成流程
|
||||||
|
|
||||||
|
```
|
||||||
|
Scheduler ReportService ProcessorService LLM API Database
|
||||||
|
│ │ │ │ │
|
||||||
|
│──(cron)──→ │ │ │ │
|
||||||
|
│ │ │ │ │
|
||||||
|
│ │──查询资讯────────────────────────────────────→│
|
||||||
|
│ │←─────────────────────────────────────────────│
|
||||||
|
│ │ │ │ │
|
||||||
|
│ │──(处理请求)──→ │ │ │
|
||||||
|
│ │ │──(调用LLM)──→│ │
|
||||||
|
│ │ │←─────────────│ │
|
||||||
|
│ │←──(处理结果)── │ │ │
|
||||||
|
│ │ │ │ │
|
||||||
|
│ │──保存报告────────────────────────────────────→│
|
||||||
|
│ │ │ │ │
|
||||||
|
│ │──(分发)──→ DistributorService │
|
||||||
|
│←──────────────│ │ │ │
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.3 AI Agent 对话流程
|
||||||
|
|
||||||
|
```
|
||||||
|
Frontend AgentService Database Collector LLM API
|
||||||
|
│ │ │ │ │
|
||||||
|
│──(用户提问)──→│ │ │ │
|
||||||
|
│ │ │ │ │
|
||||||
|
│ │──读取上下文──→│ │ │
|
||||||
|
│ │←──────────────│ │ │
|
||||||
|
│ │ │ │ │
|
||||||
|
│ │──(需要更多信息)──→ │ │
|
||||||
|
│ │ │ │──(采集)──→外部
|
||||||
|
│ │←────────────────────────── │ │
|
||||||
|
│ │ │ │ │
|
||||||
|
│ │──(构建prompt)────────────────────────────→│
|
||||||
|
│ │←─────────────────────────────────────────│
|
||||||
|
│ │ │ │ │
|
||||||
|
│←──(流式返回)──│ │ │ │
|
||||||
|
```
|
||||||
|
|
||||||
|
## 5. 数据库访问层
|
||||||
|
|
||||||
|
### 5.1 Prisma 使用
|
||||||
|
- 使用 Prisma Client 进行数据库操作
|
||||||
|
- 类型安全的查询
|
||||||
|
- 自动生成 TypeScript 类型
|
||||||
|
- 数据库迁移管理
|
||||||
|
|
||||||
|
### 5.2 事务处理
|
||||||
|
- 报告生成时使用事务确保数据一致性
|
||||||
|
- 采集失败时回滚相关操作
|
||||||
|
|
||||||
|
## 6. API 设计
|
||||||
|
|
||||||
|
### 6.1 RESTful API 规范
|
||||||
|
- 使用标准 HTTP 方法(GET、POST、PUT、DELETE)
|
||||||
|
- 统一的响应格式
|
||||||
|
- 统一的错误处理
|
||||||
|
|
||||||
|
### 6.2 响应格式
|
||||||
|
```typescript
|
||||||
|
{
|
||||||
|
success: boolean;
|
||||||
|
data?: any;
|
||||||
|
error?: {
|
||||||
|
code: string;
|
||||||
|
message: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.3 主要 API 端点
|
||||||
|
详见各任务文档中的 API 设计部分。
|
||||||
|
|
||||||
|
## 7. 安全设计
|
||||||
|
|
||||||
|
### 7.1 API 安全
|
||||||
|
- 预留认证中间件(初期可不启用)
|
||||||
|
- 敏感配置加密存储(如 API Key)
|
||||||
|
|
||||||
|
### 7.2 数据安全
|
||||||
|
- 数据库连接使用环境变量
|
||||||
|
- LLM API Key 加密存储
|
||||||
|
|
||||||
|
### 7.3 爬虫安全
|
||||||
|
- 遵守 robots.txt
|
||||||
|
- 设置合理的请求频率
|
||||||
|
- 使用 User-Agent
|
||||||
|
|
||||||
|
## 8. 性能优化
|
||||||
|
|
||||||
|
### 8.1 采集优化
|
||||||
|
- 并发采集多个数据源
|
||||||
|
- 使用连接池
|
||||||
|
- 缓存机制
|
||||||
|
|
||||||
|
### 8.2 报告生成优化
|
||||||
|
- 异步处理
|
||||||
|
- 批量查询数据库
|
||||||
|
- LLM 调用失败重试机制
|
||||||
|
|
||||||
|
### 8.3 前端优化
|
||||||
|
- 路由懒加载
|
||||||
|
- 组件按需加载
|
||||||
|
- 列表虚拟滚动(大数据量时)
|
||||||
|
|
||||||
|
## 9. 监控与日志
|
||||||
|
|
||||||
|
### 9.1 日志记录
|
||||||
|
- 采集日志:记录采集状态、错误信息
|
||||||
|
- 推送日志:记录推送状态、错误信息
|
||||||
|
- 应用日志:记录关键操作和错误
|
||||||
|
|
||||||
|
### 9.2 监控指标
|
||||||
|
- 数据源采集成功率
|
||||||
|
- 报告生成成功率
|
||||||
|
- 推送成功率
|
||||||
|
- API 响应时间
|
||||||
|
|
||||||
|
## 10. 部署架构
|
||||||
|
|
||||||
|
### 10.1 单机部署
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────┐
|
||||||
|
│ 服务器 │
|
||||||
|
│ ┌───────────────────────────┐ │
|
||||||
|
│ │ PM2 │ │
|
||||||
|
│ │ ├── Backend (Fastify) │ │
|
||||||
|
│ │ └── Frontend (静态文件) │ │
|
||||||
|
│ └───────────────────────────┘ │
|
||||||
|
│ ┌───────────────────────────┐ │
|
||||||
|
│ │ MySQL 5.6 │ │
|
||||||
|
│ └───────────────────────────┘ │
|
||||||
|
└─────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 10.2 Docker 部署(可选)
|
||||||
|
```
|
||||||
|
docker-compose.yml
|
||||||
|
├── backend (Node.js)
|
||||||
|
├── frontend (Nginx)
|
||||||
|
└── mysql (MySQL 5.6)
|
||||||
|
```
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
# News Aggregator - 产品需求文档
|
||||||
|
|
||||||
|
## 1. 产品概述
|
||||||
|
|
||||||
|
### 1.1 产品定位
|
||||||
|
基于配置的资讯聚合系统,自动收集指定主题的资讯,通过 AI 整理后生成每日报告,并推送到指定渠道。
|
||||||
|
|
||||||
|
### 1.2 核心价值
|
||||||
|
- 自动化资讯收集,节省手动浏览时间
|
||||||
|
- AI 智能整理,提取关键信息
|
||||||
|
- 多渠道推送,随时随地获取资讯
|
||||||
|
- AI Agent 深入探索,按需深入了解
|
||||||
|
|
||||||
|
### 1.3 目标用户
|
||||||
|
- 初期:个人使用
|
||||||
|
- 后期:预留多用户扩展能力
|
||||||
|
|
||||||
|
## 2. 功能需求
|
||||||
|
|
||||||
|
### 2.1 主题管理
|
||||||
|
- 用户可创建多个主题(如:AI工具、前端技术、科技商业)
|
||||||
|
- 每个主题独立配置:
|
||||||
|
- 关联的数据源(多个)
|
||||||
|
- 推送渠道(多个)
|
||||||
|
- 推送时间
|
||||||
|
- 内容处理方式(简单聚合 / AI摘要 / AI深度整理)
|
||||||
|
- 使用的 LLM
|
||||||
|
|
||||||
|
### 2.2 数据源管理
|
||||||
|
- 支持三种数据源类型:
|
||||||
|
- **社交媒体/平台 API**:Twitter/X、微博、知乎、Hacker News 等
|
||||||
|
- **第三方数据 API**:GitHub Trending、Product Hunt、NewsAPI 等
|
||||||
|
- **网页爬取**:基于 Playwright 实时从网站查询信息
|
||||||
|
- 数据源独立管理,可被多个主题复用
|
||||||
|
- 每个数据源可配置独立的采集频率
|
||||||
|
- 支持启用/禁用数据源
|
||||||
|
|
||||||
|
### 2.3 内容处理
|
||||||
|
- 三种处理模式(可按主题配置):
|
||||||
|
- **简单聚合**:按主题分类列出标题和链接
|
||||||
|
- **AI 摘要**:用 LLM 对每条资讯生成简短摘要
|
||||||
|
- **AI 深度整理**:用 LLM 分析、去重、归纳要点,生成结构化报告
|
||||||
|
- 去重逻辑在报告生成阶段处理,保留原始数据完整性
|
||||||
|
|
||||||
|
### 2.4 报告生成
|
||||||
|
- 按主题独立生成报告
|
||||||
|
- 支持两种生成方式:
|
||||||
|
- **定时自动生成**:按配置的时间周期自动生成
|
||||||
|
- **手动触发生成**:可指定任意时间范围生成即时报告
|
||||||
|
- 报告时间维度灵活:
|
||||||
|
- 支持配置定期报告(每日/每周/每月)
|
||||||
|
- 支持指定任意时间范围(如"最近3天"、"上周")
|
||||||
|
|
||||||
|
### 2.5 推送分发
|
||||||
|
- 支持多种推送渠道(可配置):
|
||||||
|
- 本地文件(Markdown/HTML)
|
||||||
|
- 邮件
|
||||||
|
- 钉钉
|
||||||
|
- 企业微信
|
||||||
|
- Slack
|
||||||
|
- 推送形式:摘要 + Web链接
|
||||||
|
- 每个主题可独立配置推送渠道和时间
|
||||||
|
|
||||||
|
### 2.6 Web 管理界面
|
||||||
|
功能模块:
|
||||||
|
|
||||||
|
#### 配置管理
|
||||||
|
- LLM 配置管理:增删改查 LLM 实例(baseUrl/model/token)
|
||||||
|
- 数据源管理:增删改查数据源,配置采集规则/频率
|
||||||
|
- 推送渠道管理:增删改查推送渠道
|
||||||
|
- 主题管理:增删改查主题,关联数据源/渠道/LLM
|
||||||
|
|
||||||
|
#### 报告中心
|
||||||
|
- 报告列表:按主题/时间筛选历史报告
|
||||||
|
- 报告详情:查看完整报告内容
|
||||||
|
- AI Agent 对话:针对报告/资讯进行深入探索
|
||||||
|
|
||||||
|
#### 资讯浏览
|
||||||
|
- 资讯列表:浏览所有采集到的原始资讯
|
||||||
|
- 按数据源筛选:查看特定数据源的资讯
|
||||||
|
- 按主题筛选:查看特定主题关联的资讯
|
||||||
|
|
||||||
|
#### 采集监控
|
||||||
|
- 数据源状态:各数据源的运行状态、最近采集时间
|
||||||
|
- 采集日志:成功/失败记录、错误信息
|
||||||
|
- 手动触发:立即执行某个数据源的采集
|
||||||
|
|
||||||
|
### 2.7 AI Agent 深入探索
|
||||||
|
- 用户在 Web 端查看报告时,可与 AI Agent 对话
|
||||||
|
- AI Agent 能力:
|
||||||
|
- 读取当前资讯/主题上下文
|
||||||
|
- 调用数据源获取更多信息
|
||||||
|
- 联网搜索补充最新内容
|
||||||
|
- 进行对比分析、深入解读
|
||||||
|
- 典型使用场景:
|
||||||
|
- "这个功能具体怎么用?"
|
||||||
|
- "和 XX 产品比有什么优势?"
|
||||||
|
- "这个技术的最新进展是什么?"
|
||||||
|
|
||||||
|
## 3. 非功能需求
|
||||||
|
|
||||||
|
### 3.1 性能要求
|
||||||
|
- 采集任务不影响 Web 服务响应
|
||||||
|
- 报告生成支持异步处理
|
||||||
|
|
||||||
|
### 3.2 可扩展性
|
||||||
|
- 采集器插件式设计,方便扩展新数据源类型
|
||||||
|
- 分发器插件式设计,方便扩展新推送渠道
|
||||||
|
- 预留多用户扩展能力
|
||||||
|
|
||||||
|
### 3.3 可靠性
|
||||||
|
- 采集失败有日志记录
|
||||||
|
- 推送失败有日志记录
|
||||||
|
- 支持手动重试
|
||||||
|
|
||||||
|
### 3.4 易用性
|
||||||
|
- Web 界面直观易用
|
||||||
|
- 配置项清晰明确
|
||||||
|
- 提供采集监控和日志查看
|
||||||
|
|
||||||
|
## 4. 数据流
|
||||||
|
|
||||||
|
### 4.1 采集流
|
||||||
|
```
|
||||||
|
数据源 → (定时采集) → 资讯表 ← (关联) ← 数据源-主题映射
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 报告生成流
|
||||||
|
```
|
||||||
|
主题配置 → 查询时间范围内的资讯 → 内容处理(AI) → 报告
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.3 推送流
|
||||||
|
```
|
||||||
|
报告 → 推送渠道配置 → 邮件/钉钉/微信等 (摘要 + Web链接)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.4 消费流
|
||||||
|
```
|
||||||
|
用户 → 点击推送链接 → Web报告详情 → AI Agent对话
|
||||||
|
↓
|
||||||
|
浏览原始资讯列表
|
||||||
|
```
|
||||||
|
|
||||||
|
## 5. 核心概念关系
|
||||||
|
|
||||||
|
```
|
||||||
|
LLM配置 ←─┐
|
||||||
|
推送渠道 ←─┼─→ 主题 ←─→ 数据源
|
||||||
|
│ ↓
|
||||||
|
│ 资讯
|
||||||
|
│ ↓
|
||||||
|
└─→ 报告
|
||||||
|
```
|
||||||
|
|
||||||
|
- 主题是配置的核心单元,关联其他所有配置
|
||||||
|
- 数据源、推送渠道、LLM 配置都是独立管理,可被多个主题复用
|
||||||
|
- 资讯通过数据源采集,归属于关联该数据源的所有主题
|
||||||
|
- 报告按主题独立生成
|
||||||
|
|
||||||
|
## 6. 用户使用流程
|
||||||
|
|
||||||
|
### 6.1 配置阶段(一次性)
|
||||||
|
1. 配置 LLM(baseUrl、model、token)
|
||||||
|
2. 配置数据源(API、网页爬取规则)
|
||||||
|
3. 配置推送渠道(邮件、钉钉等)
|
||||||
|
4. 创建主题,关联数据源、推送渠道、LLM,配置推送时间
|
||||||
|
|
||||||
|
### 6.2 自动运行阶段
|
||||||
|
1. 系统按配置的频率自动采集资讯
|
||||||
|
2. 系统按配置的时间自动生成报告
|
||||||
|
3. 系统通过配置的渠道推送报告摘要
|
||||||
|
|
||||||
|
### 6.3 消费阶段
|
||||||
|
1. 用户收到推送通知
|
||||||
|
2. 点击链接进入 Web 端查看完整报告
|
||||||
|
3. 对感兴趣的内容,与 AI Agent 对话深入了解
|
||||||
|
4. 或浏览原始资讯列表
|
||||||
|
|
||||||
|
## 7. 版本规划
|
||||||
|
|
||||||
|
### V1.0 (MVP)
|
||||||
|
- 核心采集、报告、推送流程
|
||||||
|
- 基础 Web 管理界面
|
||||||
|
- 支持 API 和 Playwright 采集器
|
||||||
|
- 支持邮件推送
|
||||||
|
|
||||||
|
### V2.0
|
||||||
|
- 完善 Web 界面
|
||||||
|
- AI Agent 深入探索
|
||||||
|
- 更多推送渠道
|
||||||
|
- 采集监控和日志
|
||||||
|
|
||||||
|
### V3.0
|
||||||
|
- 多用户支持
|
||||||
|
- 权限管理
|
||||||
|
- 更多数据源类型
|
||||||
@@ -0,0 +1,394 @@
|
|||||||
|
# 任务 01:项目初始化
|
||||||
|
|
||||||
|
## 任务概述
|
||||||
|
创建项目基础结构,初始化前后端项目,配置开发环境。
|
||||||
|
|
||||||
|
## 前置条件
|
||||||
|
- Node.js 20+ 已安装
|
||||||
|
- MySQL 5.6 已安装并运行
|
||||||
|
- PM2 已全局安装
|
||||||
|
|
||||||
|
## 任务目标
|
||||||
|
- 创建项目目录结构
|
||||||
|
- 初始化后端项目(Node.js + TypeScript + Fastify)
|
||||||
|
- 初始化前端项目(Vue 3 + TypeScript + Vite)
|
||||||
|
- 配置开发环境
|
||||||
|
|
||||||
|
## 详细步骤
|
||||||
|
|
||||||
|
### 1. 创建项目根目录结构
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir news-aggregator
|
||||||
|
cd news-aggregator
|
||||||
|
mkdir backend frontend docs
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 初始化后端项目
|
||||||
|
|
||||||
|
#### 2.1 创建 backend 目录并初始化
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
npm init -y
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2.2 安装后端依赖
|
||||||
|
|
||||||
|
**核心依赖**:
|
||||||
|
```bash
|
||||||
|
npm install fastify @fastify/cors @fastify/static
|
||||||
|
npm install @prisma/client
|
||||||
|
npm install openai
|
||||||
|
npm install playwright
|
||||||
|
npm install node-cron
|
||||||
|
npm install dotenv
|
||||||
|
```
|
||||||
|
|
||||||
|
**开发依赖**:
|
||||||
|
```bash
|
||||||
|
npm install -D typescript @types/node
|
||||||
|
npm install -D tsx nodemon
|
||||||
|
npm install -D prisma
|
||||||
|
npm install -D @types/node-cron
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2.3 配置 TypeScript
|
||||||
|
|
||||||
|
创建 `tsconfig.json`:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "commonjs",
|
||||||
|
"lib": ["ES2022"],
|
||||||
|
"outDir": "./dist",
|
||||||
|
"rootDir": "./src",
|
||||||
|
"strict": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"moduleResolution": "node",
|
||||||
|
"types": ["node"]
|
||||||
|
},
|
||||||
|
"include": ["src/**/*"],
|
||||||
|
"exclude": ["node_modules", "dist"]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2.4 配置 package.json scripts
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"scripts": {
|
||||||
|
"dev": "tsx watch src/app.ts",
|
||||||
|
"build": "tsc",
|
||||||
|
"start": "node dist/app.js",
|
||||||
|
"prisma:generate": "prisma generate",
|
||||||
|
"prisma:migrate": "prisma migrate dev",
|
||||||
|
"prisma:studio": "prisma studio"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2.5 创建基础目录结构
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir -p src/{config,web/{routes,middleware},services,collectors,distributors,utils,types}
|
||||||
|
mkdir prisma
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2.6 创建环境变量文件
|
||||||
|
|
||||||
|
创建 `.env.example`:
|
||||||
|
```env
|
||||||
|
# 应用配置
|
||||||
|
NODE_ENV=development
|
||||||
|
PORT=3000
|
||||||
|
|
||||||
|
# 数据库配置
|
||||||
|
DATABASE_URL="mysql://root:password@localhost:3306/news_aggregator"
|
||||||
|
|
||||||
|
# 其他配置
|
||||||
|
LOG_LEVEL=info
|
||||||
|
```
|
||||||
|
|
||||||
|
创建 `.env`(复制 .env.example 并修改)
|
||||||
|
|
||||||
|
#### 2.7 创建 .gitignore
|
||||||
|
|
||||||
|
```
|
||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
.env
|
||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 初始化前端项目
|
||||||
|
|
||||||
|
#### 3.1 使用 Vite 创建 Vue 3 项目
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ../frontend
|
||||||
|
npm create vite@latest . -- --template vue-ts
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3.2 安装前端依赖
|
||||||
|
|
||||||
|
**核心依赖**:
|
||||||
|
```bash
|
||||||
|
npm install vue-router@4 pinia
|
||||||
|
npm install axios
|
||||||
|
npm install element-plus
|
||||||
|
npm install @element-plus/icons-vue
|
||||||
|
```
|
||||||
|
|
||||||
|
**开发依赖**:
|
||||||
|
```bash
|
||||||
|
npm install -D @types/node
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3.3 配置 vite.config.ts
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import vue from '@vitejs/plugin-vue'
|
||||||
|
import path from 'path'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [vue()],
|
||||||
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
'@': path.resolve(__dirname, './src')
|
||||||
|
}
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
port: 5173,
|
||||||
|
proxy: {
|
||||||
|
'/api': {
|
||||||
|
target: 'http://localhost:3000',
|
||||||
|
changeOrigin: true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3.4 配置 tsconfig.json
|
||||||
|
|
||||||
|
更新 `tsconfig.json`:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2020",
|
||||||
|
"useDefineForClassFields": true,
|
||||||
|
"module": "ESNext",
|
||||||
|
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"jsx": "preserve",
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"baseUrl": ".",
|
||||||
|
"paths": {
|
||||||
|
"@/*": ["./src/*"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
|
||||||
|
"references": [{ "path": "./tsconfig.node.json" }]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3.5 创建基础目录结构
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir -p src/{router,stores,views/{config,reports,articles,monitoring},components,api,types,utils}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3.6 配置 Element Plus
|
||||||
|
|
||||||
|
创建 `src/plugins/element-plus.ts`:
|
||||||
|
```typescript
|
||||||
|
import ElementPlus from 'element-plus'
|
||||||
|
import 'element-plus/dist/index.css'
|
||||||
|
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
||||||
|
import type { App } from 'vue'
|
||||||
|
|
||||||
|
export function setupElementPlus(app: App) {
|
||||||
|
app.use(ElementPlus)
|
||||||
|
|
||||||
|
// 注册所有图标
|
||||||
|
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
||||||
|
app.component(key, component)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3.7 更新 main.ts
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { createApp } from 'vue'
|
||||||
|
import { createPinia } from 'pinia'
|
||||||
|
import App from './App.vue'
|
||||||
|
import router from './router'
|
||||||
|
import { setupElementPlus } from './plugins/element-plus'
|
||||||
|
|
||||||
|
const app = createApp(App)
|
||||||
|
const pinia = createPinia()
|
||||||
|
|
||||||
|
app.use(pinia)
|
||||||
|
app.use(router)
|
||||||
|
setupElementPlus(app)
|
||||||
|
|
||||||
|
app.mount('#app')
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 创建项目根目录文件
|
||||||
|
|
||||||
|
#### 4.1 创建 README.md
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
# News Aggregator
|
||||||
|
|
||||||
|
基于配置的资讯聚合系统,自动收集、整理、推送每日报告。
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
### 环境要求
|
||||||
|
- Node.js 20+
|
||||||
|
- MySQL 5.6
|
||||||
|
- PM2
|
||||||
|
|
||||||
|
### 安装依赖
|
||||||
|
|
||||||
|
后端:
|
||||||
|
\`\`\`bash
|
||||||
|
cd backend
|
||||||
|
npm install
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
前端:
|
||||||
|
\`\`\`bash
|
||||||
|
cd frontend
|
||||||
|
npm install
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### 配置环境变量
|
||||||
|
|
||||||
|
复制 `backend/.env.example` 到 `backend/.env` 并修改配置。
|
||||||
|
|
||||||
|
### 初始化数据库
|
||||||
|
|
||||||
|
\`\`\`bash
|
||||||
|
cd backend
|
||||||
|
npm run prisma:migrate
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### 启动开发服务
|
||||||
|
|
||||||
|
后端:
|
||||||
|
\`\`\`bash
|
||||||
|
cd backend
|
||||||
|
npm run dev
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
前端:
|
||||||
|
\`\`\`bash
|
||||||
|
cd frontend
|
||||||
|
npm run dev
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
## 文档
|
||||||
|
|
||||||
|
详细文档请查看 `docs/` 目录。
|
||||||
|
|
||||||
|
## 技术栈
|
||||||
|
|
||||||
|
- 后端:Node.js + TypeScript + Fastify + Prisma
|
||||||
|
- 前端:Vue 3 + TypeScript + Vite + Element Plus
|
||||||
|
- 数据库:MySQL 5.6
|
||||||
|
- 部署:PM2
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 4.2 创建 .gitignore(根目录)
|
||||||
|
|
||||||
|
```
|
||||||
|
# 依赖
|
||||||
|
node_modules/
|
||||||
|
|
||||||
|
# 构建产物
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
|
||||||
|
# 环境变量
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
|
||||||
|
# 日志
|
||||||
|
*.log
|
||||||
|
logs/
|
||||||
|
|
||||||
|
# 编辑器
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
|
||||||
|
# 系统文件
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# PM2
|
||||||
|
.pm2/
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 初始化 Git 仓库
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd .. # 回到项目根目录
|
||||||
|
git init
|
||||||
|
git add .
|
||||||
|
git commit -m "Initial commit: project setup"
|
||||||
|
```
|
||||||
|
|
||||||
|
## 验证步骤
|
||||||
|
|
||||||
|
### 1. 验证后端项目
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
应该能看到 TypeScript 编译成功(即使还没有代码)。
|
||||||
|
|
||||||
|
### 2. 验证前端项目
|
||||||
|
```bash
|
||||||
|
cd frontend
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
应该能在浏览器访问 http://localhost:5173 看到 Vue 默认页面。
|
||||||
|
|
||||||
|
### 3. 验证目录结构
|
||||||
|
```bash
|
||||||
|
tree -L 3 -I node_modules
|
||||||
|
```
|
||||||
|
应该看到完整的目录结构。
|
||||||
|
|
||||||
|
## 预期产物
|
||||||
|
|
||||||
|
- ✅ 项目根目录结构创建完成
|
||||||
|
- ✅ 后端项目初始化完成,依赖安装完成
|
||||||
|
- ✅ 前端项目初始化完成,依赖安装完成
|
||||||
|
- ✅ TypeScript 配置完成
|
||||||
|
- ✅ 开发环境配置完成
|
||||||
|
- ✅ Git 仓库初始化完成
|
||||||
|
|
||||||
|
## 下一步
|
||||||
|
|
||||||
|
完成本任务后,继续 [任务 02:数据库搭建](./02-database-setup.md)。
|
||||||
@@ -0,0 +1,523 @@
|
|||||||
|
# 任务 02:数据库搭建
|
||||||
|
|
||||||
|
## 任务概述
|
||||||
|
使用 Prisma 创建数据库模型,执行数据库迁移,初始化数据库结构。
|
||||||
|
|
||||||
|
## 前置条件
|
||||||
|
- 任务 01 已完成
|
||||||
|
- MySQL 5.6 已安装并运行
|
||||||
|
- 数据库连接信息已配置到 `.env` 文件
|
||||||
|
|
||||||
|
## 任务目标
|
||||||
|
- 创建 Prisma Schema
|
||||||
|
- 执行数据库迁移
|
||||||
|
- 生成 Prisma Client
|
||||||
|
- 创建种子数据脚本
|
||||||
|
|
||||||
|
## 详细步骤
|
||||||
|
|
||||||
|
### 1. 创建 Prisma Schema
|
||||||
|
|
||||||
|
创建 `backend/prisma/schema.prisma`:
|
||||||
|
|
||||||
|
```prisma
|
||||||
|
generator client {
|
||||||
|
provider = "prisma-client-js"
|
||||||
|
}
|
||||||
|
|
||||||
|
datasource db {
|
||||||
|
provider = "mysql"
|
||||||
|
url = env("DATABASE_URL")
|
||||||
|
}
|
||||||
|
|
||||||
|
// LLM 配置表
|
||||||
|
model LlmConfig {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
name String @db.VarChar(100)
|
||||||
|
baseUrl String @map("base_url") @db.VarChar(500)
|
||||||
|
model String @db.VarChar(100)
|
||||||
|
apiKey String @map("api_key") @db.VarChar(500)
|
||||||
|
enabled Boolean @default(true) @db.TinyInt
|
||||||
|
userId Int? @map("user_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
topics Topic[]
|
||||||
|
|
||||||
|
@@index([userId, enabled], map: "idx_user_enabled")
|
||||||
|
@@map("llm_configs")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 数据源表
|
||||||
|
model Source {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
name String @db.VarChar(100)
|
||||||
|
type String @db.VarChar(50) // api/playwright/rss
|
||||||
|
config Json
|
||||||
|
cronExpression String @map("cron_expression") @db.VarChar(100)
|
||||||
|
enabled Boolean @default(true) @db.TinyInt
|
||||||
|
lastCollectedAt DateTime? @map("last_collected_at")
|
||||||
|
userId Int? @map("user_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
articles Article[]
|
||||||
|
topicSources TopicSource[]
|
||||||
|
collectionLogs CollectionLog[]
|
||||||
|
|
||||||
|
@@index([userId, enabled], map: "idx_user_enabled")
|
||||||
|
@@index([type], map: "idx_type")
|
||||||
|
@@map("sources")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 推送渠道表
|
||||||
|
model Channel {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
name String @db.VarChar(100)
|
||||||
|
type String @db.VarChar(50) // email/dingtalk/wechat/slack
|
||||||
|
config Json
|
||||||
|
enabled Boolean @default(true) @db.TinyInt
|
||||||
|
userId Int? @map("user_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
topicChannels TopicChannel[]
|
||||||
|
pushLogs PushLog[]
|
||||||
|
|
||||||
|
@@index([userId, enabled], map: "idx_user_enabled")
|
||||||
|
@@index([type], map: "idx_type")
|
||||||
|
@@map("channels")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 主题表
|
||||||
|
model Topic {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
name String @db.VarChar(100)
|
||||||
|
description String? @db.Text
|
||||||
|
processMode String @map("process_mode") @db.VarChar(50) // aggregate/summary/deep_analysis
|
||||||
|
llmConfigId Int? @map("llm_config_id")
|
||||||
|
scheduleConfig Json @map("schedule_config")
|
||||||
|
enabled Boolean @default(true) @db.TinyInt
|
||||||
|
userId Int? @map("user_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
llmConfig LlmConfig? @relation(fields: [llmConfigId], references: [id])
|
||||||
|
topicSources TopicSource[]
|
||||||
|
topicChannels TopicChannel[]
|
||||||
|
reports Report[]
|
||||||
|
conversations Conversation[]
|
||||||
|
|
||||||
|
@@index([userId, enabled], map: "idx_user_enabled")
|
||||||
|
@@map("topics")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 主题-数据源关联表
|
||||||
|
model TopicSource {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
topicId Int @map("topic_id")
|
||||||
|
sourceId Int @map("source_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
topic Topic @relation(fields: [topicId], references: [id], onDelete: Cascade)
|
||||||
|
source Source @relation(fields: [sourceId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@unique([topicId, sourceId], map: "uk_topic_source")
|
||||||
|
@@index([topicId], map: "idx_topic")
|
||||||
|
@@index([sourceId], map: "idx_source")
|
||||||
|
@@map("topic_sources")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 主题-推送渠道关联表
|
||||||
|
model TopicChannel {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
topicId Int @map("topic_id")
|
||||||
|
channelId Int @map("channel_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
topic Topic @relation(fields: [topicId], references: [id], onDelete: Cascade)
|
||||||
|
channel Channel @relation(fields: [channelId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@unique([topicId, channelId], map: "uk_topic_channel")
|
||||||
|
@@index([topicId], map: "idx_topic")
|
||||||
|
@@index([channelId], map: "idx_channel")
|
||||||
|
@@map("topic_channels")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 资讯表
|
||||||
|
model Article {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
sourceId Int @map("source_id")
|
||||||
|
title String @db.VarChar(500)
|
||||||
|
content String? @db.Text
|
||||||
|
summary String? @db.Text
|
||||||
|
url String? @db.VarChar(1000)
|
||||||
|
publishedAt DateTime? @map("published_at")
|
||||||
|
collectedAt DateTime @map("collected_at")
|
||||||
|
rawData Json? @map("raw_data")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
source Source @relation(fields: [sourceId], references: [id])
|
||||||
|
conversations Conversation[]
|
||||||
|
|
||||||
|
@@index([sourceId], map: "idx_source")
|
||||||
|
@@index([publishedAt], map: "idx_published")
|
||||||
|
@@index([collectedAt], map: "idx_collected")
|
||||||
|
@@index([url(length: 255)], map: "idx_url")
|
||||||
|
@@map("articles")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 报告表
|
||||||
|
model Report {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
topicId Int @map("topic_id")
|
||||||
|
title String @db.VarChar(500)
|
||||||
|
content String @db.LongText
|
||||||
|
periodStart DateTime @map("period_start")
|
||||||
|
periodEnd DateTime @map("period_end")
|
||||||
|
status String @db.VarChar(50) // pending/generating/completed/failed
|
||||||
|
errorMessage String? @map("error_message") @db.Text
|
||||||
|
articleCount Int @default(0) @map("article_count")
|
||||||
|
userId Int? @map("user_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
topic Topic @relation(fields: [topicId], references: [id])
|
||||||
|
pushLogs PushLog[]
|
||||||
|
conversations Conversation[]
|
||||||
|
|
||||||
|
@@index([topicId], map: "idx_topic")
|
||||||
|
@@index([status], map: "idx_status")
|
||||||
|
@@index([periodStart, periodEnd], map: "idx_period")
|
||||||
|
@@index([userId, createdAt], map: "idx_user_created")
|
||||||
|
@@map("reports")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 采集日志表
|
||||||
|
model CollectionLog {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
sourceId Int @map("source_id")
|
||||||
|
status String @db.VarChar(50) // success/failed
|
||||||
|
errorMessage String? @map("error_message") @db.Text
|
||||||
|
articlesCount Int @default(0) @map("articles_count")
|
||||||
|
startedAt DateTime @map("started_at")
|
||||||
|
finishedAt DateTime? @map("finished_at")
|
||||||
|
durationMs Int? @map("duration_ms")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
source Source @relation(fields: [sourceId], references: [id])
|
||||||
|
|
||||||
|
@@index([sourceId], map: "idx_source")
|
||||||
|
@@index([status], map: "idx_status")
|
||||||
|
@@index([startedAt], map: "idx_started")
|
||||||
|
@@map("collection_logs")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 推送日志表
|
||||||
|
model PushLog {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
reportId Int @map("report_id")
|
||||||
|
channelId Int @map("channel_id")
|
||||||
|
status String @db.VarChar(50) // success/failed
|
||||||
|
errorMessage String? @map("error_message") @db.Text
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
report Report @relation(fields: [reportId], references: [id])
|
||||||
|
channel Channel @relation(fields: [channelId], references: [id])
|
||||||
|
|
||||||
|
@@index([reportId], map: "idx_report")
|
||||||
|
@@index([channelId], map: "idx_channel")
|
||||||
|
@@index([status], map: "idx_status")
|
||||||
|
@@map("push_logs")
|
||||||
|
}
|
||||||
|
|
||||||
|
// AI对话记录表
|
||||||
|
model Conversation {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
reportId Int? @map("report_id")
|
||||||
|
articleId Int? @map("article_id")
|
||||||
|
topicId Int @map("topic_id")
|
||||||
|
messages Json
|
||||||
|
userId Int? @map("user_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
report Report? @relation(fields: [reportId], references: [id])
|
||||||
|
article Article? @relation(fields: [articleId], references: [id])
|
||||||
|
topic Topic @relation(fields: [topicId], references: [id])
|
||||||
|
|
||||||
|
@@index([reportId], map: "idx_report")
|
||||||
|
@@index([articleId], map: "idx_article")
|
||||||
|
@@index([topicId], map: "idx_topic")
|
||||||
|
@@index([userId], map: "idx_user")
|
||||||
|
@@map("conversations")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 执行数据库迁移
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
|
||||||
|
# 创建迁移文件并执行
|
||||||
|
npx prisma migrate dev --name init
|
||||||
|
|
||||||
|
# 生成 Prisma Client
|
||||||
|
npx prisma generate
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 创建种子数据脚本
|
||||||
|
|
||||||
|
创建 `backend/prisma/seed.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { PrismaClient } from '@prisma/client'
|
||||||
|
|
||||||
|
const prisma = new PrismaClient()
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
console.log('开始创建种子数据...')
|
||||||
|
|
||||||
|
// 创建默认 LLM 配置
|
||||||
|
const llmConfig = await prisma.llmConfig.create({
|
||||||
|
data: {
|
||||||
|
name: '默认 OpenAI',
|
||||||
|
baseUrl: 'https://api.openai.com/v1',
|
||||||
|
model: 'gpt-4o-mini',
|
||||||
|
apiKey: 'your-api-key-here',
|
||||||
|
enabled: false, // 默认禁用,需要用户配置后启用
|
||||||
|
},
|
||||||
|
})
|
||||||
|
console.log('✓ 创建默认 LLM 配置')
|
||||||
|
|
||||||
|
// 创建示例数据源
|
||||||
|
const source = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: 'Hacker News',
|
||||||
|
type: 'api',
|
||||||
|
config: {
|
||||||
|
url: 'https://hacker-news.firebaseio.com/v0/topstories.json',
|
||||||
|
method: 'GET',
|
||||||
|
dataPath: '',
|
||||||
|
mapping: {
|
||||||
|
title: 'title',
|
||||||
|
url: 'url',
|
||||||
|
publishedAt: 'time',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
cronExpression: '0 */6 * * *', // 每6小时
|
||||||
|
enabled: false, // 默认禁用
|
||||||
|
},
|
||||||
|
})
|
||||||
|
console.log('✓ 创建示例数据源')
|
||||||
|
|
||||||
|
// 创建示例推送渠道
|
||||||
|
const channel = await prisma.channel.create({
|
||||||
|
data: {
|
||||||
|
name: '邮件通知',
|
||||||
|
type: 'email',
|
||||||
|
config: {
|
||||||
|
smtp: {
|
||||||
|
host: 'smtp.example.com',
|
||||||
|
port: 465,
|
||||||
|
secure: true,
|
||||||
|
auth: {
|
||||||
|
user: 'user@example.com',
|
||||||
|
pass: 'password',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
from: 'News Aggregator <noreply@example.com>',
|
||||||
|
to: ['user@example.com'],
|
||||||
|
},
|
||||||
|
enabled: false, // 默认禁用
|
||||||
|
},
|
||||||
|
})
|
||||||
|
console.log('✓ 创建示例推送渠道')
|
||||||
|
|
||||||
|
// 创建示例主题
|
||||||
|
const topic = await prisma.topic.create({
|
||||||
|
data: {
|
||||||
|
name: '科技资讯',
|
||||||
|
description: '关注最新的科技动态和产品发布',
|
||||||
|
processMode: 'summary',
|
||||||
|
llmConfigId: llmConfig.id,
|
||||||
|
scheduleConfig: {
|
||||||
|
cron: '0 9 * * *',
|
||||||
|
timezone: 'Asia/Shanghai',
|
||||||
|
period: 'daily',
|
||||||
|
lookback: 24,
|
||||||
|
},
|
||||||
|
enabled: false, // 默认禁用
|
||||||
|
},
|
||||||
|
})
|
||||||
|
console.log('✓ 创建示例主题')
|
||||||
|
|
||||||
|
// 关联主题和数据源
|
||||||
|
await prisma.topicSource.create({
|
||||||
|
data: {
|
||||||
|
topicId: topic.id,
|
||||||
|
sourceId: source.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
console.log('✓ 关联主题和数据源')
|
||||||
|
|
||||||
|
// 关联主题和推送渠道
|
||||||
|
await prisma.topicChannel.create({
|
||||||
|
data: {
|
||||||
|
topicId: topic.id,
|
||||||
|
channelId: channel.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
console.log('✓ 关联主题和推送渠道')
|
||||||
|
|
||||||
|
console.log('种子数据创建完成!')
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
.catch((e) => {
|
||||||
|
console.error('种子数据创建失败:', e)
|
||||||
|
process.exit(1)
|
||||||
|
})
|
||||||
|
.finally(async () => {
|
||||||
|
await prisma.$disconnect()
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 配置种子数据脚本
|
||||||
|
|
||||||
|
更新 `backend/package.json`,添加 seed 脚本:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"prisma": {
|
||||||
|
"seed": "tsx prisma/seed.ts"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"prisma:seed": "tsx prisma/seed.ts"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 执行种子数据
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run prisma:seed
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6. 创建数据库工具类
|
||||||
|
|
||||||
|
创建 `backend/src/utils/prisma.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { PrismaClient } from '@prisma/client'
|
||||||
|
|
||||||
|
// 创建 Prisma Client 单例
|
||||||
|
const prismaClientSingleton = () => {
|
||||||
|
return new PrismaClient({
|
||||||
|
log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
var prisma: undefined | ReturnType<typeof prismaClientSingleton>
|
||||||
|
}
|
||||||
|
|
||||||
|
const prisma = globalThis.prisma ?? prismaClientSingleton()
|
||||||
|
|
||||||
|
if (process.env.NODE_ENV !== 'production') {
|
||||||
|
globalThis.prisma = prisma
|
||||||
|
}
|
||||||
|
|
||||||
|
export default prisma
|
||||||
|
```
|
||||||
|
|
||||||
|
## 验证步骤
|
||||||
|
|
||||||
|
### 1. 验证数据库连接
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
npx prisma studio
|
||||||
|
```
|
||||||
|
|
||||||
|
应该能打开 Prisma Studio 并看到所有表。
|
||||||
|
|
||||||
|
### 2. 验证表结构
|
||||||
|
|
||||||
|
在 Prisma Studio 中检查:
|
||||||
|
- 所有表都已创建
|
||||||
|
- 索引都已创建
|
||||||
|
- 外键关系正确
|
||||||
|
|
||||||
|
### 3. 验证种子数据
|
||||||
|
|
||||||
|
在 Prisma Studio 中检查:
|
||||||
|
- llm_configs 表有 1 条记录
|
||||||
|
- sources 表有 1 条记录
|
||||||
|
- channels 表有 1 条记录
|
||||||
|
- topics 表有 1 条记录
|
||||||
|
- topic_sources 表有 1 条记录
|
||||||
|
- topic_channels 表有 1 条记录
|
||||||
|
|
||||||
|
### 4. 验证 Prisma Client
|
||||||
|
|
||||||
|
创建测试文件 `backend/src/test-db.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import prisma from './utils/prisma'
|
||||||
|
|
||||||
|
async function test() {
|
||||||
|
const topics = await prisma.topic.findMany({
|
||||||
|
include: {
|
||||||
|
llmConfig: true,
|
||||||
|
topicSources: {
|
||||||
|
include: {
|
||||||
|
source: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
topicChannels: {
|
||||||
|
include: {
|
||||||
|
channel: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
console.log('主题列表:', JSON.stringify(topics, null, 2))
|
||||||
|
}
|
||||||
|
|
||||||
|
test()
|
||||||
|
.catch(console.error)
|
||||||
|
.finally(() => prisma.$disconnect())
|
||||||
|
```
|
||||||
|
|
||||||
|
运行测试:
|
||||||
|
```bash
|
||||||
|
npx tsx src/test-db.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
应该能看到完整的主题数据,包括关联的 LLM 配置、数据源、推送渠道。
|
||||||
|
|
||||||
|
## 预期产物
|
||||||
|
|
||||||
|
- ✅ Prisma Schema 创建完成
|
||||||
|
- ✅ 数据库迁移执行成功
|
||||||
|
- ✅ 所有表创建完成
|
||||||
|
- ✅ Prisma Client 生成成功
|
||||||
|
- ✅ 种子数据创建成功
|
||||||
|
- ✅ 数据库工具类创建完成
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
### 问题 1:数据库连接失败
|
||||||
|
**解决方案**:检查 `.env` 文件中的 `DATABASE_URL` 是否正确,确保 MySQL 服务已启动。
|
||||||
|
|
||||||
|
### 问题 2:迁移失败
|
||||||
|
**解决方案**:删除数据库重新创建,或使用 `npx prisma migrate reset` 重置数据库。
|
||||||
|
|
||||||
|
### 问题 3:Prisma Client 类型错误
|
||||||
|
**解决方案**:重新生成 Prisma Client:`npx prisma generate`
|
||||||
|
|
||||||
|
## 下一步
|
||||||
|
|
||||||
|
完成本任务后,继续 [任务 03:后端核心框架](./03-backend-core.md)。
|
||||||
@@ -0,0 +1,542 @@
|
|||||||
|
# 任务 03:后端核心框架
|
||||||
|
|
||||||
|
## 任务概述
|
||||||
|
搭建后端核心框架,包括 Fastify 应用初始化、配置管理、中间件、错误处理等基础设施。
|
||||||
|
|
||||||
|
## 前置条件
|
||||||
|
- 任务 01、02 已完成
|
||||||
|
- 数据库已初始化
|
||||||
|
|
||||||
|
## 任务目标
|
||||||
|
- 创建 Fastify 应用
|
||||||
|
- 配置管理
|
||||||
|
- 统一响应格式
|
||||||
|
- 错误处理中间件
|
||||||
|
- 日志系统
|
||||||
|
- 基础 API 路由
|
||||||
|
|
||||||
|
## 详细步骤
|
||||||
|
|
||||||
|
### 1. 创建配置管理
|
||||||
|
|
||||||
|
创建 `backend/src/config/index.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import dotenv from 'dotenv'
|
||||||
|
|
||||||
|
dotenv.config()
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
// 应用配置
|
||||||
|
app: {
|
||||||
|
env: process.env.NODE_ENV || 'development',
|
||||||
|
port: parseInt(process.env.PORT || '3000', 10),
|
||||||
|
host: process.env.HOST || '0.0.0.0',
|
||||||
|
},
|
||||||
|
|
||||||
|
// 数据库配置
|
||||||
|
database: {
|
||||||
|
url: process.env.DATABASE_URL || '',
|
||||||
|
},
|
||||||
|
|
||||||
|
// 日志配置
|
||||||
|
log: {
|
||||||
|
level: process.env.LOG_LEVEL || 'info',
|
||||||
|
},
|
||||||
|
|
||||||
|
// CORS 配置
|
||||||
|
cors: {
|
||||||
|
origin: process.env.CORS_ORIGIN || '*',
|
||||||
|
credentials: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证必需的环境变量
|
||||||
|
function validateConfig() {
|
||||||
|
const required = ['DATABASE_URL']
|
||||||
|
const missing = required.filter((key) => !process.env[key])
|
||||||
|
|
||||||
|
if (missing.length > 0) {
|
||||||
|
throw new Error(`缺少必需的环境变量: ${missing.join(', ')}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
validateConfig()
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 创建类型定义
|
||||||
|
|
||||||
|
创建 `backend/src/types/api.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// 统一响应格式
|
||||||
|
export interface ApiResponse<T = any> {
|
||||||
|
success: boolean
|
||||||
|
data?: T
|
||||||
|
error?: ApiError
|
||||||
|
message?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiError {
|
||||||
|
code: string
|
||||||
|
message: string
|
||||||
|
details?: any
|
||||||
|
}
|
||||||
|
|
||||||
|
// 分页参数
|
||||||
|
export interface PaginationParams {
|
||||||
|
page?: number
|
||||||
|
limit?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
// 分页响应
|
||||||
|
export interface PaginatedResponse<T> {
|
||||||
|
items: T[]
|
||||||
|
total: number
|
||||||
|
page: number
|
||||||
|
limit: number
|
||||||
|
totalPages: number
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
创建 `backend/src/types/index.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export * from './api'
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 创建工具函数
|
||||||
|
|
||||||
|
创建 `backend/src/utils/response.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import type { ApiResponse, ApiError } from '../types'
|
||||||
|
|
||||||
|
export class ResponseHelper {
|
||||||
|
static success<T>(data?: T, message?: string): ApiResponse<T> {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data,
|
||||||
|
message,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static error(code: string, message: string, details?: any): ApiResponse {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: {
|
||||||
|
code,
|
||||||
|
message,
|
||||||
|
details,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
创建 `backend/src/utils/logger.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { config } from '../config'
|
||||||
|
|
||||||
|
type LogLevel = 'debug' | 'info' | 'warn' | 'error'
|
||||||
|
|
||||||
|
class Logger {
|
||||||
|
private shouldLog(level: LogLevel): boolean {
|
||||||
|
const levels: LogLevel[] = ['debug', 'info', 'warn', 'error']
|
||||||
|
const configLevel = config.log.level as LogLevel
|
||||||
|
return levels.indexOf(level) >= levels.indexOf(configLevel)
|
||||||
|
}
|
||||||
|
|
||||||
|
private formatMessage(level: LogLevel, message: string, meta?: any): string {
|
||||||
|
const timestamp = new Date().toISOString()
|
||||||
|
const metaStr = meta ? ` ${JSON.stringify(meta)}` : ''
|
||||||
|
return `[${timestamp}] [${level.toUpperCase()}] ${message}${metaStr}`
|
||||||
|
}
|
||||||
|
|
||||||
|
debug(message: string, meta?: any) {
|
||||||
|
if (this.shouldLog('debug')) {
|
||||||
|
console.debug(this.formatMessage('debug', message, meta))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
info(message: string, meta?: any) {
|
||||||
|
if (this.shouldLog('info')) {
|
||||||
|
console.info(this.formatMessage('info', message, meta))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
warn(message: string, meta?: any) {
|
||||||
|
if (this.shouldLog('warn')) {
|
||||||
|
console.warn(this.formatMessage('warn', message, meta))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
error(message: string, meta?: any) {
|
||||||
|
if (this.shouldLog('error')) {
|
||||||
|
console.error(this.formatMessage('error', message, meta))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const logger = new Logger()
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 创建错误处理
|
||||||
|
|
||||||
|
创建 `backend/src/utils/errors.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export class AppError extends Error {
|
||||||
|
constructor(
|
||||||
|
public code: string,
|
||||||
|
message: string,
|
||||||
|
public statusCode: number = 500,
|
||||||
|
public details?: any
|
||||||
|
) {
|
||||||
|
super(message)
|
||||||
|
this.name = 'AppError'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ValidationError extends AppError {
|
||||||
|
constructor(message: string, details?: any) {
|
||||||
|
super('VALIDATION_ERROR', message, 400, details)
|
||||||
|
this.name = 'ValidationError'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class NotFoundError extends AppError {
|
||||||
|
constructor(resource: string) {
|
||||||
|
super('NOT_FOUND', `${resource} not found`, 404)
|
||||||
|
this.name = 'NotFoundError'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UnauthorizedError extends AppError {
|
||||||
|
constructor(message: string = 'Unauthorized') {
|
||||||
|
super('UNAUTHORIZED', message, 401)
|
||||||
|
this.name = 'UnauthorizedError'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ForbiddenError extends AppError {
|
||||||
|
constructor(message: string = 'Forbidden') {
|
||||||
|
super('FORBIDDEN', message, 403)
|
||||||
|
this.name = 'ForbiddenError'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 创建中间件
|
||||||
|
|
||||||
|
创建 `backend/src/web/middleware/error-handler.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import type { FastifyError, FastifyReply, FastifyRequest } from 'fastify'
|
||||||
|
import { AppError } from '../../utils/errors'
|
||||||
|
import { ResponseHelper } from '../../utils/response'
|
||||||
|
import { logger } from '../../utils/logger'
|
||||||
|
|
||||||
|
export async function errorHandler(
|
||||||
|
error: FastifyError,
|
||||||
|
request: FastifyRequest,
|
||||||
|
reply: FastifyReply
|
||||||
|
) {
|
||||||
|
logger.error('Request error', {
|
||||||
|
method: request.method,
|
||||||
|
url: request.url,
|
||||||
|
error: error.message,
|
||||||
|
stack: error.stack,
|
||||||
|
})
|
||||||
|
|
||||||
|
// 处理自定义错误
|
||||||
|
if (error instanceof AppError) {
|
||||||
|
return reply.status(error.statusCode).send(
|
||||||
|
ResponseHelper.error(error.code, error.message, error.details)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理 Fastify 验证错误
|
||||||
|
if (error.validation) {
|
||||||
|
return reply.status(400).send(
|
||||||
|
ResponseHelper.error('VALIDATION_ERROR', 'Validation failed', error.validation)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理未知错误
|
||||||
|
return reply.status(500).send(
|
||||||
|
ResponseHelper.error(
|
||||||
|
'INTERNAL_ERROR',
|
||||||
|
'Internal server error',
|
||||||
|
process.env.NODE_ENV === 'development' ? error.message : undefined
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
创建 `backend/src/web/middleware/request-logger.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import type { FastifyRequest, FastifyReply } from 'fastify'
|
||||||
|
import { logger } from '../../utils/logger'
|
||||||
|
|
||||||
|
export async function requestLogger(request: FastifyRequest, reply: FastifyReply) {
|
||||||
|
const start = Date.now()
|
||||||
|
|
||||||
|
reply.addHook('onSend', async () => {
|
||||||
|
const duration = Date.now() - start
|
||||||
|
logger.info('Request completed', {
|
||||||
|
method: request.method,
|
||||||
|
url: request.url,
|
||||||
|
statusCode: reply.statusCode,
|
||||||
|
duration: `${duration}ms`,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6. 创建健康检查路由
|
||||||
|
|
||||||
|
创建 `backend/src/web/routes/health.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import type { FastifyInstance } from 'fastify'
|
||||||
|
import { ResponseHelper } from '../../utils/response'
|
||||||
|
import prisma from '../../utils/prisma'
|
||||||
|
|
||||||
|
export async function healthRoutes(app: FastifyInstance) {
|
||||||
|
// 基础健康检查
|
||||||
|
app.get('/health', async () => {
|
||||||
|
return ResponseHelper.success({
|
||||||
|
status: 'ok',
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// 详细健康检查(包括数据库)
|
||||||
|
app.get('/health/detailed', async () => {
|
||||||
|
try {
|
||||||
|
// 检查数据库连接
|
||||||
|
await prisma.$queryRaw`SELECT 1`
|
||||||
|
|
||||||
|
return ResponseHelper.success({
|
||||||
|
status: 'ok',
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
services: {
|
||||||
|
database: 'ok',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
return ResponseHelper.error('HEALTH_CHECK_FAILED', 'Health check failed', {
|
||||||
|
database: 'error',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7. 创建 Fastify 应用
|
||||||
|
|
||||||
|
创建 `backend/src/app.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import Fastify from 'fastify'
|
||||||
|
import cors from '@fastify/cors'
|
||||||
|
import { config } from './config'
|
||||||
|
import { logger } from './utils/logger'
|
||||||
|
import { errorHandler } from './web/middleware/error-handler'
|
||||||
|
import { requestLogger } from './web/middleware/request-logger'
|
||||||
|
import { healthRoutes } from './web/routes/health'
|
||||||
|
|
||||||
|
export async function createApp() {
|
||||||
|
const app = Fastify({
|
||||||
|
logger: false, // 使用自定义 logger
|
||||||
|
})
|
||||||
|
|
||||||
|
// 注册 CORS
|
||||||
|
await app.register(cors, {
|
||||||
|
origin: config.cors.origin,
|
||||||
|
credentials: config.cors.credentials,
|
||||||
|
})
|
||||||
|
|
||||||
|
// 注册中间件
|
||||||
|
app.addHook('onRequest', requestLogger)
|
||||||
|
|
||||||
|
// 注册错误处理
|
||||||
|
app.setErrorHandler(errorHandler)
|
||||||
|
|
||||||
|
// 注册路由
|
||||||
|
await app.register(healthRoutes, { prefix: '/api' })
|
||||||
|
|
||||||
|
return app
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function startServer() {
|
||||||
|
try {
|
||||||
|
const app = await createApp()
|
||||||
|
|
||||||
|
await app.listen({
|
||||||
|
port: config.app.port,
|
||||||
|
host: config.app.host,
|
||||||
|
})
|
||||||
|
|
||||||
|
logger.info(`Server started on http://${config.app.host}:${config.app.port}`)
|
||||||
|
logger.info(`Environment: ${config.app.env}`)
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to start server', error)
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果直接运行此文件,则启动服务器
|
||||||
|
if (require.main === module) {
|
||||||
|
startServer()
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8. 更新 package.json
|
||||||
|
|
||||||
|
确保 `backend/package.json` 中的 scripts 正确:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"scripts": {
|
||||||
|
"dev": "tsx watch src/app.ts",
|
||||||
|
"build": "tsc",
|
||||||
|
"start": "node dist/app.js",
|
||||||
|
"prisma:generate": "prisma generate",
|
||||||
|
"prisma:migrate": "prisma migrate dev",
|
||||||
|
"prisma:studio": "prisma studio",
|
||||||
|
"prisma:seed": "tsx prisma/seed.ts"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 9. 创建 API 测试脚本
|
||||||
|
|
||||||
|
创建 `backend/test-api.http`(使用 REST Client 插件):
|
||||||
|
|
||||||
|
```http
|
||||||
|
### 健康检查
|
||||||
|
GET http://localhost:3000/api/health
|
||||||
|
|
||||||
|
### 详细健康检查
|
||||||
|
GET http://localhost:3000/api/health/detailed
|
||||||
|
```
|
||||||
|
|
||||||
|
## 验证步骤
|
||||||
|
|
||||||
|
### 1. 启动开发服务器
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
应该看到:
|
||||||
|
```
|
||||||
|
[2024-01-01T10:00:00.000Z] [INFO] Server started on http://0.0.0.0:3000
|
||||||
|
[2024-01-01T10:00:00.000Z] [INFO] Environment: development
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 测试健康检查 API
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 基础健康检查
|
||||||
|
curl http://localhost:3000/api/health
|
||||||
|
|
||||||
|
# 预期响应
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"data": {
|
||||||
|
"status": "ok",
|
||||||
|
"timestamp": "2024-01-01T10:00:00.000Z"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# 详细健康检查
|
||||||
|
curl http://localhost:3000/api/health/detailed
|
||||||
|
|
||||||
|
# 预期响应
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"data": {
|
||||||
|
"status": "ok",
|
||||||
|
"timestamp": "2024-01-01T10:00:00.000Z",
|
||||||
|
"services": {
|
||||||
|
"database": "ok"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 测试错误处理
|
||||||
|
|
||||||
|
访问不存在的路由:
|
||||||
|
```bash
|
||||||
|
curl http://localhost:3000/api/not-found
|
||||||
|
|
||||||
|
# 预期响应(404)
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"error": {
|
||||||
|
"code": "NOT_FOUND",
|
||||||
|
"message": "Route GET:/api/not-found not found"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 检查日志输出
|
||||||
|
|
||||||
|
在控制台应该能看到请求日志:
|
||||||
|
```
|
||||||
|
[2024-01-01T10:00:00.000Z] [INFO] Request completed {"method":"GET","url":"/api/health","statusCode":200,"duration":"5ms"}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 预期产物
|
||||||
|
|
||||||
|
- ✅ Fastify 应用创建完成
|
||||||
|
- ✅ 配置管理系统完成
|
||||||
|
- ✅ 统一响应格式实现
|
||||||
|
- ✅ 错误处理中间件完成
|
||||||
|
- ✅ 日志系统完成
|
||||||
|
- ✅ 健康检查 API 完成
|
||||||
|
- ✅ 服务器可以正常启动和响应请求
|
||||||
|
|
||||||
|
## 项目结构
|
||||||
|
|
||||||
|
完成后的目录结构:
|
||||||
|
|
||||||
|
```
|
||||||
|
backend/
|
||||||
|
├── src/
|
||||||
|
│ ├── config/
|
||||||
|
│ │ └── index.ts # 配置管理
|
||||||
|
│ ├── types/
|
||||||
|
│ │ ├── api.ts # API 类型定义
|
||||||
|
│ │ └── index.ts
|
||||||
|
│ ├── utils/
|
||||||
|
│ │ ├── prisma.ts # Prisma 客户端
|
||||||
|
│ │ ├── response.ts # 响应工具
|
||||||
|
│ │ ├── logger.ts # 日志工具
|
||||||
|
│ │ └── errors.ts # 错误类
|
||||||
|
│ ├── web/
|
||||||
|
│ │ ├── middleware/
|
||||||
|
│ │ │ ├── error-handler.ts # 错误处理
|
||||||
|
│ │ │ └── request-logger.ts # 请求日志
|
||||||
|
│ │ └── routes/
|
||||||
|
│ │ └── health.ts # 健康检查路由
|
||||||
|
│ └── app.ts # 应用入口
|
||||||
|
├── prisma/
|
||||||
|
│ ├── schema.prisma
|
||||||
|
│ └── seed.ts
|
||||||
|
├── .env
|
||||||
|
├── .env.example
|
||||||
|
├── package.json
|
||||||
|
└── tsconfig.json
|
||||||
|
```
|
||||||
|
|
||||||
|
## 下一步
|
||||||
|
|
||||||
|
完成本任务后,继续 [任务 04:采集器实现](./04-collectors.md)。
|
||||||
@@ -0,0 +1,757 @@
|
|||||||
|
# 任务 04:采集器实现
|
||||||
|
|
||||||
|
## 任务概述
|
||||||
|
实现插件式采集器架构,支持 API、Playwright 网页爬取、RSS 三种数据源类型。
|
||||||
|
|
||||||
|
## 前置条件
|
||||||
|
- 任务 01、02、03 已完成
|
||||||
|
- 后端核心框架已搭建
|
||||||
|
|
||||||
|
## 任务目标
|
||||||
|
- 创建采集器基类接口
|
||||||
|
- 实现 API 采集器
|
||||||
|
- 实现 Playwright 采集器
|
||||||
|
- 实现 RSS 采集器
|
||||||
|
- 创建采集器工厂
|
||||||
|
- 实现采集服务
|
||||||
|
|
||||||
|
## 详细步骤
|
||||||
|
|
||||||
|
### 1. 创建采集器类型定义
|
||||||
|
|
||||||
|
创建 `backend/src/types/collector.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export type CollectorType = 'api' | 'playwright' | 'rss'
|
||||||
|
|
||||||
|
export interface CollectorConfig {
|
||||||
|
[key: string]: any
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CollectedArticle {
|
||||||
|
title: string
|
||||||
|
content?: string
|
||||||
|
url?: string
|
||||||
|
publishedAt?: Date
|
||||||
|
rawData?: any
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CollectionResult {
|
||||||
|
articles: CollectedArticle[]
|
||||||
|
success: boolean
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 创建采集器基类
|
||||||
|
|
||||||
|
创建 `backend/src/collectors/base.collector.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import type { CollectorType, CollectorConfig, CollectionResult } from '../types/collector'
|
||||||
|
|
||||||
|
export abstract class BaseCollector {
|
||||||
|
constructor(
|
||||||
|
protected config: CollectorConfig,
|
||||||
|
protected sourceId: number
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行采集
|
||||||
|
*/
|
||||||
|
abstract collect(): Promise<CollectionResult>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证配置
|
||||||
|
*/
|
||||||
|
abstract validateConfig(): boolean
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取采集器类型
|
||||||
|
*/
|
||||||
|
abstract getType(): CollectorType
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理资源(可选)
|
||||||
|
*/
|
||||||
|
async cleanup(): Promise<void> {
|
||||||
|
// 默认不需要清理
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 实现 API 采集器
|
||||||
|
|
||||||
|
创建 `backend/src/collectors/api.collector.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { BaseCollector } from './base.collector'
|
||||||
|
import type { CollectorType, CollectionResult, CollectedArticle } from '../types/collector'
|
||||||
|
import { logger } from '../utils/logger'
|
||||||
|
|
||||||
|
interface ApiCollectorConfig {
|
||||||
|
url: string
|
||||||
|
method?: 'GET' | 'POST'
|
||||||
|
headers?: Record<string, string>
|
||||||
|
params?: Record<string, any>
|
||||||
|
body?: any
|
||||||
|
dataPath?: string // 数据在响应中的路径,如 "data.items"
|
||||||
|
mapping: {
|
||||||
|
title: string
|
||||||
|
content?: string
|
||||||
|
url?: string
|
||||||
|
publishedAt?: string
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ApiCollector extends BaseCollector {
|
||||||
|
private config: ApiCollectorConfig
|
||||||
|
|
||||||
|
constructor(config: ApiCollectorConfig, sourceId: number) {
|
||||||
|
super(config, sourceId)
|
||||||
|
this.config = config
|
||||||
|
}
|
||||||
|
|
||||||
|
async collect(): Promise<CollectionResult> {
|
||||||
|
try {
|
||||||
|
logger.info(`API采集器开始采集: ${this.config.url}`)
|
||||||
|
|
||||||
|
// 构建请求
|
||||||
|
const url = new URL(this.config.url)
|
||||||
|
if (this.config.params) {
|
||||||
|
Object.entries(this.config.params).forEach(([key, value]) => {
|
||||||
|
url.searchParams.append(key, String(value))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const options: RequestInit = {
|
||||||
|
method: this.config.method || 'GET',
|
||||||
|
headers: {
|
||||||
|
'User-Agent': 'News-Aggregator/1.0',
|
||||||
|
...this.config.headers,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.config.body && this.config.method === 'POST') {
|
||||||
|
options.body = JSON.stringify(this.config.body)
|
||||||
|
options.headers = {
|
||||||
|
...options.headers,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 发送请求
|
||||||
|
const response = await fetch(url.toString(), options)
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json()
|
||||||
|
|
||||||
|
// 提取数据
|
||||||
|
let items = data
|
||||||
|
if (this.config.dataPath) {
|
||||||
|
items = this.getNestedValue(data, this.config.dataPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Array.isArray(items)) {
|
||||||
|
items = [items]
|
||||||
|
}
|
||||||
|
|
||||||
|
// 映射数据
|
||||||
|
const articles: CollectedArticle[] = items.map((item: any) => {
|
||||||
|
const article: CollectedArticle = {
|
||||||
|
title: this.getNestedValue(item, this.config.mapping.title),
|
||||||
|
rawData: item,
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.config.mapping.content) {
|
||||||
|
article.content = this.getNestedValue(item, this.config.mapping.content)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.config.mapping.url) {
|
||||||
|
article.url = this.getNestedValue(item, this.config.mapping.url)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.config.mapping.publishedAt) {
|
||||||
|
const dateValue = this.getNestedValue(item, this.config.mapping.publishedAt)
|
||||||
|
article.publishedAt = this.parseDate(dateValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
return article
|
||||||
|
})
|
||||||
|
|
||||||
|
logger.info(`API采集器完成,采集到 ${articles.length} 条资讯`)
|
||||||
|
|
||||||
|
return {
|
||||||
|
articles,
|
||||||
|
success: true,
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('API采集器失败', error)
|
||||||
|
return {
|
||||||
|
articles: [],
|
||||||
|
success: false,
|
||||||
|
error: error instanceof Error ? error.message : 'Unknown error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
validateConfig(): boolean {
|
||||||
|
return !!(
|
||||||
|
this.config.url &&
|
||||||
|
this.config.mapping &&
|
||||||
|
this.config.mapping.title
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
getType(): CollectorType {
|
||||||
|
return 'api'
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取嵌套对象的值
|
||||||
|
*/
|
||||||
|
private getNestedValue(obj: any, path: string): any {
|
||||||
|
return path.split('.').reduce((current, key) => current?.[key], obj)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析日期
|
||||||
|
*/
|
||||||
|
private parseDate(value: any): Date | undefined {
|
||||||
|
if (!value) return undefined
|
||||||
|
|
||||||
|
// Unix 时间戳(秒)
|
||||||
|
if (typeof value === 'number' && value > 1000000000 && value < 10000000000) {
|
||||||
|
return new Date(value * 1000)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unix 时间戳(毫秒)
|
||||||
|
if (typeof value === 'number' && value > 1000000000000) {
|
||||||
|
return new Date(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ISO 字符串
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
const date = new Date(value)
|
||||||
|
return isNaN(date.getTime()) ? undefined : date
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 实现 Playwright 采集器
|
||||||
|
|
||||||
|
创建 `backend/src/collectors/playwright.collector.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { BaseCollector } from './base.collector'
|
||||||
|
import type { CollectorType, CollectionResult, CollectedArticle } from '../types/collector'
|
||||||
|
import { chromium, type Browser, type Page } from 'playwright'
|
||||||
|
import { logger } from '../utils/logger'
|
||||||
|
|
||||||
|
interface PlaywrightCollectorConfig {
|
||||||
|
url: string
|
||||||
|
selectors: {
|
||||||
|
items: string // 列表项选择器
|
||||||
|
title: string // 标题选择器(相对于 item)
|
||||||
|
content?: string // 内容选择器(相对于 item)
|
||||||
|
url?: string // 链接选择器(相对于 item)
|
||||||
|
publishedAt?: string // 日期选择器(相对于 item)
|
||||||
|
}
|
||||||
|
waitFor?: string // 等待的选择器
|
||||||
|
waitTimeout?: number // 等待超时时间(毫秒)
|
||||||
|
script?: string // 可选的自定义脚本
|
||||||
|
}
|
||||||
|
|
||||||
|
export class PlaywrightCollector extends BaseCollector {
|
||||||
|
private config: PlaywrightCollectorConfig
|
||||||
|
private browser?: Browser
|
||||||
|
|
||||||
|
constructor(config: PlaywrightCollectorConfig, sourceId: number) {
|
||||||
|
super(config, sourceId)
|
||||||
|
this.config = config
|
||||||
|
}
|
||||||
|
|
||||||
|
async collect(): Promise<CollectionResult> {
|
||||||
|
try {
|
||||||
|
logger.info(`Playwright采集器开始采集: ${this.config.url}`)
|
||||||
|
|
||||||
|
// 启动浏览器
|
||||||
|
this.browser = await chromium.launch({
|
||||||
|
headless: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
const page = await this.browser.newPage()
|
||||||
|
|
||||||
|
// 设置 User-Agent
|
||||||
|
await page.setExtraHTTPHeaders({
|
||||||
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
||||||
|
})
|
||||||
|
|
||||||
|
// 访问页面
|
||||||
|
await page.goto(this.config.url, {
|
||||||
|
waitUntil: 'networkidle',
|
||||||
|
timeout: 30000,
|
||||||
|
})
|
||||||
|
|
||||||
|
// 等待内容加载
|
||||||
|
if (this.config.waitFor) {
|
||||||
|
await page.waitForSelector(this.config.waitFor, {
|
||||||
|
timeout: this.config.waitTimeout || 10000,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 执行自定义脚本(如果有)
|
||||||
|
if (this.config.script) {
|
||||||
|
await page.evaluate(this.config.script)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提取数据
|
||||||
|
const articles = await this.extractArticles(page)
|
||||||
|
|
||||||
|
logger.info(`Playwright采集器完成,采集到 ${articles.length} 条资讯`)
|
||||||
|
|
||||||
|
return {
|
||||||
|
articles,
|
||||||
|
success: true,
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Playwright采集器失败', error)
|
||||||
|
return {
|
||||||
|
articles: [],
|
||||||
|
success: false,
|
||||||
|
error: error instanceof Error ? error.message : 'Unknown error',
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
await this.cleanup()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async extractArticles(page: Page): Promise<CollectedArticle[]> {
|
||||||
|
const items = await page.$$(this.config.selectors.items)
|
||||||
|
const articles: CollectedArticle[] = []
|
||||||
|
|
||||||
|
for (const item of items) {
|
||||||
|
try {
|
||||||
|
const article: CollectedArticle = {
|
||||||
|
title: '',
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提取标题
|
||||||
|
const titleElement = await item.$(this.config.selectors.title)
|
||||||
|
if (titleElement) {
|
||||||
|
article.title = (await titleElement.textContent())?.trim() || ''
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提取内容
|
||||||
|
if (this.config.selectors.content) {
|
||||||
|
const contentElement = await item.$(this.config.selectors.content)
|
||||||
|
if (contentElement) {
|
||||||
|
article.content = (await contentElement.textContent())?.trim()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提取链接
|
||||||
|
if (this.config.selectors.url) {
|
||||||
|
const urlElement = await item.$(this.config.selectors.url)
|
||||||
|
if (urlElement) {
|
||||||
|
const href = await urlElement.getAttribute('href')
|
||||||
|
if (href) {
|
||||||
|
// 处理相对路径
|
||||||
|
article.url = new URL(href, this.config.url).toString()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提取日期
|
||||||
|
if (this.config.selectors.publishedAt) {
|
||||||
|
const dateElement = await item.$(this.config.selectors.publishedAt)
|
||||||
|
if (dateElement) {
|
||||||
|
const dateText = (await dateElement.textContent())?.trim()
|
||||||
|
if (dateText) {
|
||||||
|
article.publishedAt = this.parseDate(dateText)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (article.title) {
|
||||||
|
articles.push(article)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn('提取单条资讯失败', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return articles
|
||||||
|
}
|
||||||
|
|
||||||
|
validateConfig(): boolean {
|
||||||
|
return !!(
|
||||||
|
this.config.url &&
|
||||||
|
this.config.selectors &&
|
||||||
|
this.config.selectors.items &&
|
||||||
|
this.config.selectors.title
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
getType(): CollectorType {
|
||||||
|
return 'playwright'
|
||||||
|
}
|
||||||
|
|
||||||
|
async cleanup(): Promise<void> {
|
||||||
|
if (this.browser) {
|
||||||
|
await this.browser.close()
|
||||||
|
this.browser = undefined
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseDate(value: string): Date | undefined {
|
||||||
|
const date = new Date(value)
|
||||||
|
return isNaN(date.getTime()) ? undefined : date
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 实现 RSS 采集器
|
||||||
|
|
||||||
|
安装 RSS 解析库:
|
||||||
|
```bash
|
||||||
|
npm install rss-parser
|
||||||
|
npm install -D @types/rss-parser
|
||||||
|
```
|
||||||
|
|
||||||
|
创建 `backend/src/collectors/rss.collector.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { BaseCollector } from './base.collector'
|
||||||
|
import type { CollectorType, CollectionResult, CollectedArticle } from '../types/collector'
|
||||||
|
import Parser from 'rss-parser'
|
||||||
|
import { logger } from '../utils/logger'
|
||||||
|
|
||||||
|
interface RssCollectorConfig {
|
||||||
|
url: string
|
||||||
|
customFields?: {
|
||||||
|
item?: string[]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class RssCollector extends BaseCollector {
|
||||||
|
private config: RssCollectorConfig
|
||||||
|
private parser: Parser
|
||||||
|
|
||||||
|
constructor(config: RssCollectorConfig, sourceId: number) {
|
||||||
|
super(config, sourceId)
|
||||||
|
this.config = config
|
||||||
|
this.parser = new Parser({
|
||||||
|
customFields: this.config.customFields,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async collect(): Promise<CollectionResult> {
|
||||||
|
try {
|
||||||
|
logger.info(`RSS采集器开始采集: ${this.config.url}`)
|
||||||
|
|
||||||
|
const feed = await this.parser.parseURL(this.config.url)
|
||||||
|
|
||||||
|
const articles: CollectedArticle[] = feed.items.map((item) => {
|
||||||
|
const article: CollectedArticle = {
|
||||||
|
title: item.title || '',
|
||||||
|
content: item.contentSnippet || item.content,
|
||||||
|
url: item.link,
|
||||||
|
rawData: item,
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.pubDate) {
|
||||||
|
article.publishedAt = new Date(item.pubDate)
|
||||||
|
} else if (item.isoDate) {
|
||||||
|
article.publishedAt = new Date(item.isoDate)
|
||||||
|
}
|
||||||
|
|
||||||
|
return article
|
||||||
|
})
|
||||||
|
|
||||||
|
logger.info(`RSS采集器完成,采集到 ${articles.length} 条资讯`)
|
||||||
|
|
||||||
|
return {
|
||||||
|
articles,
|
||||||
|
success: true,
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('RSS采集器失败', error)
|
||||||
|
return {
|
||||||
|
articles: [],
|
||||||
|
success: false,
|
||||||
|
error: error instanceof Error ? error.message : 'Unknown error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
validateConfig(): boolean {
|
||||||
|
return !!this.config.url
|
||||||
|
}
|
||||||
|
|
||||||
|
getType(): CollectorType {
|
||||||
|
return 'rss'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6. 创建采集器工厂
|
||||||
|
|
||||||
|
创建 `backend/src/collectors/collector.factory.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import type { BaseCollector } from './base.collector'
|
||||||
|
import { ApiCollector } from './api.collector'
|
||||||
|
import { PlaywrightCollector } from './playwright.collector'
|
||||||
|
import { RssCollector } from './rss.collector'
|
||||||
|
import type { CollectorType, CollectorConfig } from '../types/collector'
|
||||||
|
|
||||||
|
export class CollectorFactory {
|
||||||
|
static create(
|
||||||
|
type: CollectorType,
|
||||||
|
config: CollectorConfig,
|
||||||
|
sourceId: number
|
||||||
|
): BaseCollector {
|
||||||
|
switch (type) {
|
||||||
|
case 'api':
|
||||||
|
return new ApiCollector(config, sourceId)
|
||||||
|
case 'playwright':
|
||||||
|
return new PlaywrightCollector(config, sourceId)
|
||||||
|
case 'rss':
|
||||||
|
return new RssCollector(config, sourceId)
|
||||||
|
default:
|
||||||
|
throw new Error(`Unknown collector type: ${type}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7. 创建采集服务
|
||||||
|
|
||||||
|
创建 `backend/src/services/collector.service.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import prisma from '../utils/prisma'
|
||||||
|
import { CollectorFactory } from '../collectors/collector.factory'
|
||||||
|
import { logger } from '../utils/logger'
|
||||||
|
import type { Source } from '@prisma/client'
|
||||||
|
|
||||||
|
export class CollectorService {
|
||||||
|
/**
|
||||||
|
* 执行单个数据源的采集
|
||||||
|
*/
|
||||||
|
async collectSource(sourceId: number): Promise<void> {
|
||||||
|
const startTime = Date.now()
|
||||||
|
let articlesCount = 0
|
||||||
|
let status: 'success' | 'failed' = 'success'
|
||||||
|
let errorMessage: string | undefined
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 查询数据源
|
||||||
|
const source = await prisma.source.findUnique({
|
||||||
|
where: { id: sourceId },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!source) {
|
||||||
|
throw new Error(`Source ${sourceId} not found`)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!source.enabled) {
|
||||||
|
logger.info(`数据源 ${source.name} 已禁用,跳过采集`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`开始采集数据源: ${source.name}`)
|
||||||
|
|
||||||
|
// 创建采集器
|
||||||
|
const collector = CollectorFactory.create(
|
||||||
|
source.type as any,
|
||||||
|
source.config as any,
|
||||||
|
source.id
|
||||||
|
)
|
||||||
|
|
||||||
|
// 验证配置
|
||||||
|
if (!collector.validateConfig()) {
|
||||||
|
throw new Error('Invalid collector config')
|
||||||
|
}
|
||||||
|
|
||||||
|
// 执行采集
|
||||||
|
const result = await collector.collect()
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
throw new Error(result.error || 'Collection failed')
|
||||||
|
}
|
||||||
|
|
||||||
|
// 保存资讯
|
||||||
|
for (const article of result.articles) {
|
||||||
|
try {
|
||||||
|
await prisma.article.create({
|
||||||
|
data: {
|
||||||
|
sourceId: source.id,
|
||||||
|
title: article.title,
|
||||||
|
content: article.content,
|
||||||
|
url: article.url,
|
||||||
|
publishedAt: article.publishedAt,
|
||||||
|
collectedAt: new Date(),
|
||||||
|
rawData: article.rawData,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
articlesCount++
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn('保存资讯失败', { title: article.title, error })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新数据源的最后采集时间
|
||||||
|
await prisma.source.update({
|
||||||
|
where: { id: source.id },
|
||||||
|
data: { lastCollectedAt: new Date() },
|
||||||
|
})
|
||||||
|
|
||||||
|
logger.info(`数据源 ${source.name} 采集完成,保存 ${articlesCount} 条资讯`)
|
||||||
|
} catch (error) {
|
||||||
|
status = 'failed'
|
||||||
|
errorMessage = error instanceof Error ? error.message : 'Unknown error'
|
||||||
|
logger.error(`数据源采集失败`, { sourceId, error: errorMessage })
|
||||||
|
} finally {
|
||||||
|
// 记录采集日志
|
||||||
|
await prisma.collectionLog.create({
|
||||||
|
data: {
|
||||||
|
sourceId,
|
||||||
|
status,
|
||||||
|
errorMessage,
|
||||||
|
articlesCount,
|
||||||
|
startedAt: new Date(startTime),
|
||||||
|
finishedAt: new Date(),
|
||||||
|
durationMs: Date.now() - startTime,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 采集所有启用的数据源
|
||||||
|
*/
|
||||||
|
async collectAllSources(): Promise<void> {
|
||||||
|
const sources = await prisma.source.findMany({
|
||||||
|
where: { enabled: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
logger.info(`开始采集 ${sources.length} 个数据源`)
|
||||||
|
|
||||||
|
for (const source of sources) {
|
||||||
|
await this.collectSource(source.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info('所有数据源采集完成')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8. 创建采集器导出
|
||||||
|
|
||||||
|
创建 `backend/src/collectors/index.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export * from './base.collector'
|
||||||
|
export * from './api.collector'
|
||||||
|
export * from './playwright.collector'
|
||||||
|
export * from './rss.collector'
|
||||||
|
export * from './collector.factory'
|
||||||
|
```
|
||||||
|
|
||||||
|
创建 `backend/src/services/index.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export * from './collector.service'
|
||||||
|
```
|
||||||
|
|
||||||
|
## 验证步骤
|
||||||
|
|
||||||
|
### 1. 创建测试脚本
|
||||||
|
|
||||||
|
创建 `backend/src/test-collector.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { CollectorService } from './services/collector.service'
|
||||||
|
import prisma from './utils/prisma'
|
||||||
|
|
||||||
|
async function test() {
|
||||||
|
const collectorService = new CollectorService()
|
||||||
|
|
||||||
|
// 测试采集单个数据源
|
||||||
|
const sources = await prisma.source.findMany({
|
||||||
|
where: { enabled: true },
|
||||||
|
take: 1,
|
||||||
|
})
|
||||||
|
|
||||||
|
if (sources.length > 0) {
|
||||||
|
console.log(`测试采集数据源: ${sources[0].name}`)
|
||||||
|
await collectorService.collectSource(sources[0].id)
|
||||||
|
|
||||||
|
// 查看采集结果
|
||||||
|
const articles = await prisma.article.findMany({
|
||||||
|
where: { sourceId: sources[0].id },
|
||||||
|
take: 5,
|
||||||
|
orderBy: { collectedAt: 'desc' },
|
||||||
|
})
|
||||||
|
|
||||||
|
console.log(`采集到 ${articles.length} 条资讯:`)
|
||||||
|
articles.forEach((article) => {
|
||||||
|
console.log(`- ${article.title}`)
|
||||||
|
})
|
||||||
|
|
||||||
|
// 查看采集日志
|
||||||
|
const logs = await prisma.collectionLog.findMany({
|
||||||
|
where: { sourceId: sources[0].id },
|
||||||
|
take: 1,
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
})
|
||||||
|
|
||||||
|
console.log('最近的采集日志:', logs[0])
|
||||||
|
} else {
|
||||||
|
console.log('没有启用的数据源')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
test()
|
||||||
|
.catch(console.error)
|
||||||
|
.finally(() => prisma.$disconnect())
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 运行测试
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx tsx src/test-collector.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 验证数据库
|
||||||
|
|
||||||
|
使用 Prisma Studio 查看:
|
||||||
|
```bash
|
||||||
|
npm run prisma:studio
|
||||||
|
```
|
||||||
|
|
||||||
|
检查:
|
||||||
|
- articles 表有新数据
|
||||||
|
- collection_logs 表有采集记录
|
||||||
|
|
||||||
|
## 预期产物
|
||||||
|
|
||||||
|
- ✅ 采集器基类创建完成
|
||||||
|
- ✅ API 采集器实现完成
|
||||||
|
- ✅ Playwright 采集器实现完成
|
||||||
|
- ✅ RSS 采集器实现完成
|
||||||
|
- ✅ 采集器工厂创建完成
|
||||||
|
- ✅ 采集服务实现完成
|
||||||
|
- ✅ 采集功能测试通过
|
||||||
|
|
||||||
|
## 下一步
|
||||||
|
|
||||||
|
完成本任务后,继续 [任务 05:内容处理](./05-processor.md)。
|
||||||
@@ -0,0 +1,581 @@
|
|||||||
|
# 任务 05:内容处理
|
||||||
|
|
||||||
|
## 任务概述
|
||||||
|
实现基于 LLM 的内容处理服务,支持三种处理模式:简单聚合、AI 摘要、AI 深度整理。
|
||||||
|
|
||||||
|
## 前置条件
|
||||||
|
- 任务 01-04 已完成
|
||||||
|
- 采集器已实现
|
||||||
|
|
||||||
|
## 任务目标
|
||||||
|
- 创建 LLM 客户端封装
|
||||||
|
- 实现内容处理服务
|
||||||
|
- 支持三种处理模式
|
||||||
|
- 实现去重逻辑
|
||||||
|
|
||||||
|
## 详细步骤
|
||||||
|
|
||||||
|
### 1. 创建 LLM 类型定义
|
||||||
|
|
||||||
|
创建 `backend/src/types/llm.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export interface LlmMessage {
|
||||||
|
role: 'system' | 'user' | 'assistant'
|
||||||
|
content: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LlmResponse {
|
||||||
|
content: string
|
||||||
|
usage?: {
|
||||||
|
promptTokens: number
|
||||||
|
completionTokens: number
|
||||||
|
totalTokens: number
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LlmConfig {
|
||||||
|
baseUrl: string
|
||||||
|
model: string
|
||||||
|
apiKey: string
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 创建 LLM 客户端
|
||||||
|
|
||||||
|
创建 `backend/src/utils/llm-client.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import OpenAI from 'openai'
|
||||||
|
import type { LlmConfig, LlmMessage, LlmResponse } from '../types/llm'
|
||||||
|
import { logger } from './logger'
|
||||||
|
|
||||||
|
export class LlmClient {
|
||||||
|
private client: OpenAI
|
||||||
|
|
||||||
|
constructor(private config: LlmConfig) {
|
||||||
|
this.client = new OpenAI({
|
||||||
|
baseURL: config.baseUrl,
|
||||||
|
apiKey: config.apiKey,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async chat(messages: LlmMessage[], options?: {
|
||||||
|
temperature?: number
|
||||||
|
maxTokens?: number
|
||||||
|
}): Promise<LlmResponse> {
|
||||||
|
try {
|
||||||
|
logger.debug('调用 LLM', {
|
||||||
|
model: this.config.model,
|
||||||
|
messagesCount: messages.length,
|
||||||
|
})
|
||||||
|
|
||||||
|
const response = await this.client.chat.completions.create({
|
||||||
|
model: this.config.model,
|
||||||
|
messages: messages as any,
|
||||||
|
temperature: options?.temperature ?? 0.7,
|
||||||
|
max_tokens: options?.maxTokens,
|
||||||
|
})
|
||||||
|
|
||||||
|
const content = response.choices[0]?.message?.content || ''
|
||||||
|
|
||||||
|
logger.debug('LLM 响应完成', {
|
||||||
|
contentLength: content.length,
|
||||||
|
usage: response.usage,
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
content,
|
||||||
|
usage: response.usage ? {
|
||||||
|
promptTokens: response.usage.prompt_tokens,
|
||||||
|
completionTokens: response.usage.completion_tokens,
|
||||||
|
totalTokens: response.usage.total_tokens,
|
||||||
|
} : undefined,
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('LLM 调用失败', error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async streamChat(
|
||||||
|
messages: LlmMessage[],
|
||||||
|
onChunk: (chunk: string) => void,
|
||||||
|
options?: {
|
||||||
|
temperature?: number
|
||||||
|
maxTokens?: number
|
||||||
|
}
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
logger.debug('调用 LLM (流式)', {
|
||||||
|
model: this.config.model,
|
||||||
|
messagesCount: messages.length,
|
||||||
|
})
|
||||||
|
|
||||||
|
const stream = await this.client.chat.completions.create({
|
||||||
|
model: this.config.model,
|
||||||
|
messages: messages as any,
|
||||||
|
temperature: options?.temperature ?? 0.7,
|
||||||
|
max_tokens: options?.maxTokens,
|
||||||
|
stream: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
for await (const chunk of stream) {
|
||||||
|
const content = chunk.choices[0]?.delta?.content || ''
|
||||||
|
if (content) {
|
||||||
|
onChunk(content)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.debug('LLM 流式响应完成')
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('LLM 流式调用失败', error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 创建内容处理类型定义
|
||||||
|
|
||||||
|
更新 `backend/src/types/index.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export * from './api'
|
||||||
|
export * from './collector'
|
||||||
|
export * from './llm'
|
||||||
|
|
||||||
|
export type ProcessMode = 'aggregate' | 'summary' | 'deep_analysis'
|
||||||
|
|
||||||
|
export interface ProcessedContent {
|
||||||
|
content: string
|
||||||
|
mode: ProcessMode
|
||||||
|
articlesCount: number
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 创建内容处理服务
|
||||||
|
|
||||||
|
创建 `backend/src/services/processor.service.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import type { Article } from '@prisma/client'
|
||||||
|
import { LlmClient } from '../utils/llm-client'
|
||||||
|
import type { LlmConfig, ProcessMode, ProcessedContent } from '../types'
|
||||||
|
import { logger } from '../utils/logger'
|
||||||
|
|
||||||
|
export class ProcessorService {
|
||||||
|
/**
|
||||||
|
* 处理资讯列表
|
||||||
|
*/
|
||||||
|
async processArticles(
|
||||||
|
articles: Article[],
|
||||||
|
mode: ProcessMode,
|
||||||
|
llmConfig: LlmConfig
|
||||||
|
): Promise<ProcessedContent> {
|
||||||
|
logger.info(`开始处理 ${articles.length} 条资讯,模式: ${mode}`)
|
||||||
|
|
||||||
|
switch (mode) {
|
||||||
|
case 'aggregate':
|
||||||
|
return this.aggregateArticles(articles)
|
||||||
|
case 'summary':
|
||||||
|
return this.summarizeArticles(articles, llmConfig)
|
||||||
|
case 'deep_analysis':
|
||||||
|
return this.deepAnalyzeArticles(articles, llmConfig)
|
||||||
|
default:
|
||||||
|
throw new Error(`Unknown process mode: ${mode}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 简单聚合:按主题分类列出标题和链接
|
||||||
|
*/
|
||||||
|
private async aggregateArticles(articles: Article[]): Promise<ProcessedContent> {
|
||||||
|
const lines: string[] = []
|
||||||
|
|
||||||
|
articles.forEach((article, index) => {
|
||||||
|
lines.push(`${index + 1}. **${article.title}**`)
|
||||||
|
if (article.url) {
|
||||||
|
lines.push(` 链接: ${article.url}`)
|
||||||
|
}
|
||||||
|
if (article.publishedAt) {
|
||||||
|
lines.push(` 发布时间: ${article.publishedAt.toLocaleString('zh-CN')}`)
|
||||||
|
}
|
||||||
|
lines.push('')
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: lines.join('\n'),
|
||||||
|
mode: 'aggregate',
|
||||||
|
articlesCount: articles.length,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* AI 摘要:对每条资讯生成简短摘要
|
||||||
|
*/
|
||||||
|
private async summarizeArticles(
|
||||||
|
articles: Article[],
|
||||||
|
llmConfig: LlmConfig
|
||||||
|
): Promise<ProcessedContent> {
|
||||||
|
const llmClient = new LlmClient(llmConfig)
|
||||||
|
const lines: string[] = []
|
||||||
|
|
||||||
|
for (const article of articles) {
|
||||||
|
try {
|
||||||
|
const summary = await this.summarizeSingleArticle(article, llmClient)
|
||||||
|
lines.push(`### ${article.title}`)
|
||||||
|
lines.push('')
|
||||||
|
lines.push(summary)
|
||||||
|
lines.push('')
|
||||||
|
if (article.url) {
|
||||||
|
lines.push(`[查看原文](${article.url})`)
|
||||||
|
lines.push('')
|
||||||
|
}
|
||||||
|
lines.push('---')
|
||||||
|
lines.push('')
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn('摘要生成失败', { title: article.title, error })
|
||||||
|
// 失败时使用原始内容
|
||||||
|
lines.push(`### ${article.title}`)
|
||||||
|
lines.push('')
|
||||||
|
if (article.content) {
|
||||||
|
lines.push(article.content.substring(0, 200) + '...')
|
||||||
|
}
|
||||||
|
lines.push('')
|
||||||
|
if (article.url) {
|
||||||
|
lines.push(`[查看原文](${article.url})`)
|
||||||
|
lines.push('')
|
||||||
|
}
|
||||||
|
lines.push('---')
|
||||||
|
lines.push('')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: lines.join('\n'),
|
||||||
|
mode: 'summary',
|
||||||
|
articlesCount: articles.length,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 为单条资讯生成摘要
|
||||||
|
*/
|
||||||
|
private async summarizeSingleArticle(
|
||||||
|
article: Article,
|
||||||
|
llmClient: LlmClient
|
||||||
|
): Promise<string> {
|
||||||
|
const prompt = `请为以下资讯生成一个简短的摘要(100字以内):
|
||||||
|
|
||||||
|
标题:${article.title}
|
||||||
|
${article.content ? `内容:${article.content.substring(0, 1000)}` : ''}
|
||||||
|
|
||||||
|
要求:
|
||||||
|
1. 提取核心信息
|
||||||
|
2. 简洁明了
|
||||||
|
3. 使用中文`
|
||||||
|
|
||||||
|
const response = await llmClient.chat([
|
||||||
|
{ role: 'user', content: prompt },
|
||||||
|
], {
|
||||||
|
temperature: 0.3,
|
||||||
|
maxTokens: 200,
|
||||||
|
})
|
||||||
|
|
||||||
|
return response.content.trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* AI 深度整理:分析、去重、归纳要点,生成结构化报告
|
||||||
|
*/
|
||||||
|
private async deepAnalyzeArticles(
|
||||||
|
articles: Article[],
|
||||||
|
llmConfig: LlmConfig
|
||||||
|
): Promise<ProcessedContent> {
|
||||||
|
const llmClient = new LlmClient(llmConfig)
|
||||||
|
|
||||||
|
// 准备资讯列表
|
||||||
|
const articlesList = articles.map((article, index) => {
|
||||||
|
return `[${index + 1}] ${article.title}
|
||||||
|
${article.content ? article.content.substring(0, 500) : ''}
|
||||||
|
${article.url ? `链接: ${article.url}` : ''}
|
||||||
|
---`
|
||||||
|
}).join('\n\n')
|
||||||
|
|
||||||
|
const prompt = `你是一个专业的资讯分析师。请对以下资讯进行深度分析和整理:
|
||||||
|
|
||||||
|
${articlesList}
|
||||||
|
|
||||||
|
请按以下要求生成报告:
|
||||||
|
|
||||||
|
1. **核心主题**:识别这些资讯的主要主题和趋势
|
||||||
|
2. **重点资讯**:挑选出最重要的 3-5 条资讯,说明为什么重要
|
||||||
|
3. **关键要点**:提炼出关键信息和洞察
|
||||||
|
4. **相关性分析**:如果有相关或重复的资讯,进行合并说明
|
||||||
|
5. **总结**:用 2-3 句话总结整体情况
|
||||||
|
|
||||||
|
要求:
|
||||||
|
- 使用 Markdown 格式
|
||||||
|
- 结构清晰,层次分明
|
||||||
|
- 保留重要资讯的原文链接
|
||||||
|
- 使用中文`
|
||||||
|
|
||||||
|
const response = await llmClient.chat([
|
||||||
|
{ role: 'user', content: prompt },
|
||||||
|
], {
|
||||||
|
temperature: 0.5,
|
||||||
|
maxTokens: 2000,
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: response.content.trim(),
|
||||||
|
mode: 'deep_analysis',
|
||||||
|
articlesCount: articles.length,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 去重:基于 URL 和标题相似度
|
||||||
|
*/
|
||||||
|
async deduplicateArticles(articles: Article[]): Promise<Article[]> {
|
||||||
|
const seen = new Set<string>()
|
||||||
|
const deduplicated: Article[] = []
|
||||||
|
|
||||||
|
for (const article of articles) {
|
||||||
|
// 基于 URL 去重
|
||||||
|
if (article.url) {
|
||||||
|
if (seen.has(article.url)) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen.add(article.url)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 基于标题去重(简单的字符串匹配)
|
||||||
|
const normalizedTitle = article.title.toLowerCase().trim()
|
||||||
|
if (seen.has(normalizedTitle)) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen.add(normalizedTitle)
|
||||||
|
|
||||||
|
deduplicated.push(article)
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`去重完成: ${articles.length} -> ${deduplicated.length}`)
|
||||||
|
|
||||||
|
return deduplicated
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按发布时间排序
|
||||||
|
*/
|
||||||
|
sortArticlesByDate(articles: Article[], order: 'asc' | 'desc' = 'desc'): Article[] {
|
||||||
|
return [...articles].sort((a, b) => {
|
||||||
|
const dateA = a.publishedAt || a.collectedAt
|
||||||
|
const dateB = b.publishedAt || b.collectedAt
|
||||||
|
|
||||||
|
if (order === 'desc') {
|
||||||
|
return dateB.getTime() - dateA.getTime()
|
||||||
|
} else {
|
||||||
|
return dateA.getTime() - dateB.getTime()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 更新服务导出
|
||||||
|
|
||||||
|
更新 `backend/src/services/index.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export * from './collector.service'
|
||||||
|
export * from './processor.service'
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6. 创建测试脚本
|
||||||
|
|
||||||
|
创建 `backend/src/test-processor.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { ProcessorService } from './services/processor.service'
|
||||||
|
import prisma from './utils/prisma'
|
||||||
|
|
||||||
|
async function test() {
|
||||||
|
const processorService = new ProcessorService()
|
||||||
|
|
||||||
|
// 获取一些测试资讯
|
||||||
|
const articles = await prisma.article.findMany({
|
||||||
|
take: 5,
|
||||||
|
orderBy: { collectedAt: 'desc' },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (articles.length === 0) {
|
||||||
|
console.log('没有资讯数据,请先运行采集器')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`找到 ${articles.length} 条资讯`)
|
||||||
|
|
||||||
|
// 测试去重
|
||||||
|
console.log('\n=== 测试去重 ===')
|
||||||
|
const deduplicated = await processorService.deduplicateArticles(articles)
|
||||||
|
console.log(`去重后: ${deduplicated.length} 条`)
|
||||||
|
|
||||||
|
// 测试排序
|
||||||
|
console.log('\n=== 测试排序 ===')
|
||||||
|
const sorted = processorService.sortArticlesByDate(deduplicated)
|
||||||
|
console.log('最新的资讯:', sorted[0]?.title)
|
||||||
|
|
||||||
|
// 测试简单聚合
|
||||||
|
console.log('\n=== 测试简单聚合 ===')
|
||||||
|
const aggregated = await processorService.processArticles(
|
||||||
|
deduplicated,
|
||||||
|
'aggregate',
|
||||||
|
as any // 聚合模式不需要 LLM
|
||||||
|
)
|
||||||
|
console.log(aggregated.content.substring(0, 500))
|
||||||
|
|
||||||
|
// 测试 AI 摘要(需要配置 LLM)
|
||||||
|
const llmConfig = await prisma.llmConfig.findFirst({
|
||||||
|
where: { enabled: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (llmConfig) {
|
||||||
|
console.log('\n=== 测试 AI 摘要 ===')
|
||||||
|
try {
|
||||||
|
const summarized = await processorService.processArticles(
|
||||||
|
deduplicated.slice(0, 2), // 只测试 2 条
|
||||||
|
'summary',
|
||||||
|
{
|
||||||
|
baseUrl: llmConfig.baseUrl,
|
||||||
|
model: llmConfig.model,
|
||||||
|
apiKey: llmConfig.apiKey,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
console.log(summarized.content.substring(0, 500))
|
||||||
|
} catch (error) {
|
||||||
|
console.error('AI 摘要失败:', error)
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('\n=== 测试 AI 深度整理 ===')
|
||||||
|
try {
|
||||||
|
const analyzed = await processorService.processArticles(
|
||||||
|
deduplicated.slice(0, 3), // 只测试 3 条
|
||||||
|
'deep_analysis',
|
||||||
|
{
|
||||||
|
baseUrl: llmConfig.baseUrl,
|
||||||
|
model: llmConfig.model,
|
||||||
|
apiKey: llmConfig.apiKey,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
console.log(analyzed.content.substring(0, 500))
|
||||||
|
} catch (error) {
|
||||||
|
console.error('AI 深度整理失败:', error)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.log('\n没有启用的 LLM 配置,跳过 AI 测试')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
test()
|
||||||
|
.catch(console.error)
|
||||||
|
.finally(() => prisma.$disconnect())
|
||||||
|
```
|
||||||
|
|
||||||
|
## 验证步骤
|
||||||
|
|
||||||
|
### 1. 准备测试数据
|
||||||
|
|
||||||
|
确保数据库中有资讯数据:
|
||||||
|
```bash
|
||||||
|
# 如果没有,先运行采集器
|
||||||
|
npx tsx src/test-collector.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 配置 LLM
|
||||||
|
|
||||||
|
使用 Prisma Studio 更新 LLM 配置:
|
||||||
|
```bash
|
||||||
|
npm run prisma:studio
|
||||||
|
```
|
||||||
|
|
||||||
|
在 `llm_configs` 表中:
|
||||||
|
- 更新 `api_key` 为真实的 API Key
|
||||||
|
- 设置 `enabled` 为 `true`
|
||||||
|
|
||||||
|
### 3. 运行测试
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx tsx src/test-processor.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
预期输出:
|
||||||
|
```
|
||||||
|
找到 5 条资讯
|
||||||
|
|
||||||
|
=== 测试去重 ===
|
||||||
|
去重后: 5 条
|
||||||
|
|
||||||
|
=== 测试排序 ===
|
||||||
|
最新的资讯: xxx
|
||||||
|
|
||||||
|
=== 测试简单聚合 ===
|
||||||
|
1. **标题1**
|
||||||
|
链接: https://...
|
||||||
|
发布时间: 2024-01-01 10:00:00
|
||||||
|
...
|
||||||
|
|
||||||
|
=== 测试 AI 摘要 ===
|
||||||
|
### 标题1
|
||||||
|
|
||||||
|
这是一个关于...的摘要
|
||||||
|
|
||||||
|
[查看原文](https://...)
|
||||||
|
...
|
||||||
|
|
||||||
|
=== 测试 AI 深度整理 ===
|
||||||
|
## 核心主题
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 验证不同处理模式
|
||||||
|
|
||||||
|
测试三种模式的输出:
|
||||||
|
- **aggregate**:应该是简单的列表格式
|
||||||
|
- **summary**:应该有每条资讯的摘要
|
||||||
|
- **deep_analysis**:应该有结构化的分析报告
|
||||||
|
|
||||||
|
## 预期产物
|
||||||
|
|
||||||
|
- ✅ LLM 客户端封装完成
|
||||||
|
- ✅ 内容处理服务实现完成
|
||||||
|
- ✅ 三种处理模式实现完成
|
||||||
|
- ✅ 去重逻辑实现完成
|
||||||
|
- ✅ 排序功能实现完成
|
||||||
|
- ✅ 测试通过
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
### 问题 1:LLM 调用失败
|
||||||
|
**解决方案**:
|
||||||
|
- 检查 API Key 是否正确
|
||||||
|
- 检查 baseUrl 是否正确
|
||||||
|
- 检查网络连接
|
||||||
|
- 查看错误日志
|
||||||
|
|
||||||
|
### 问题 2:摘要质量不好
|
||||||
|
**解决方案**:
|
||||||
|
- 调整 prompt
|
||||||
|
- 调整 temperature 参数
|
||||||
|
- 尝试不同的模型
|
||||||
|
|
||||||
|
### 问题 3:处理速度慢
|
||||||
|
**解决方案**:
|
||||||
|
- 减少单次处理的资讯数量
|
||||||
|
- 使用更快的模型
|
||||||
|
- 考虑并发处理(后续优化)
|
||||||
|
|
||||||
|
## 下一步
|
||||||
|
|
||||||
|
完成本任务后,继续 [任务 06:报告生成](./06-report-generator.md)。
|
||||||
@@ -0,0 +1,649 @@
|
|||||||
|
# 任务 06:报告生成
|
||||||
|
|
||||||
|
## 任务概述
|
||||||
|
实现报告生成服务,根据主题配置查询资讯、处理内容、生成报告。
|
||||||
|
|
||||||
|
## 前置条件
|
||||||
|
- 任务 01-05 已完成
|
||||||
|
- 内容处理服务已实现
|
||||||
|
|
||||||
|
## 任务目标
|
||||||
|
- 创建报告生成服务
|
||||||
|
- 实现按时间范围查询资讯
|
||||||
|
- 集成内容处理
|
||||||
|
- 生成报告并保存到数据库
|
||||||
|
|
||||||
|
## 详细步骤
|
||||||
|
|
||||||
|
### 1. 创建报告类型定义
|
||||||
|
|
||||||
|
更新 `backend/src/types/index.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export * from './api'
|
||||||
|
export * from './collector'
|
||||||
|
export * from './llm'
|
||||||
|
|
||||||
|
export type ProcessMode = 'aggregate' | 'summary' | 'deep_analysis'
|
||||||
|
export type ReportStatus = 'pending' | 'generating' | 'completed' | 'failed'
|
||||||
|
|
||||||
|
export interface ProcessedContent {
|
||||||
|
content: string
|
||||||
|
mode: ProcessMode
|
||||||
|
articlesCount: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReportGenerationOptions {
|
||||||
|
topicId: number
|
||||||
|
periodStart: Date
|
||||||
|
periodEnd: Date
|
||||||
|
manualTrigger?: boolean
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 创建报告生成服务
|
||||||
|
|
||||||
|
创建 `backend/src/services/report.service.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import prisma from '../utils/prisma'
|
||||||
|
import { ProcessorService } from './processor.service'
|
||||||
|
import { logger } from '../utils/logger'
|
||||||
|
import type { ReportGenerationOptions, ProcessMode } from '../types'
|
||||||
|
import type { Article } from '@prisma/client'
|
||||||
|
|
||||||
|
export class ReportService {
|
||||||
|
private processorService: ProcessorService
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.processorService = new ProcessorService()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成报告
|
||||||
|
*/
|
||||||
|
async generateReport(options: ReportGenerationOptions): Promise<number> {
|
||||||
|
const { topicId, periodStart, periodEnd } = options
|
||||||
|
|
||||||
|
logger.info('开始生成报告', {
|
||||||
|
topicId,
|
||||||
|
periodStart,
|
||||||
|
periodEnd,
|
||||||
|
})
|
||||||
|
|
||||||
|
// 创建报告记录(状态:pending)
|
||||||
|
const report = await prisma.report.create({
|
||||||
|
data: {
|
||||||
|
topicId,
|
||||||
|
title: '', // 稍后更新
|
||||||
|
content: '',
|
||||||
|
periodStart,
|
||||||
|
periodEnd,
|
||||||
|
status: 'pending',
|
||||||
|
articleCount: 0,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 更新状态为 generating
|
||||||
|
await prisma.report.update({
|
||||||
|
where: { id: report.id },
|
||||||
|
data: { status: 'generating' },
|
||||||
|
})
|
||||||
|
|
||||||
|
// 查询主题配置
|
||||||
|
const topic = await prisma.topic.findUnique({
|
||||||
|
where: { id: topicId },
|
||||||
|
include: {
|
||||||
|
llmConfig: true,
|
||||||
|
topicSources: {
|
||||||
|
include: {
|
||||||
|
source: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!topic) {
|
||||||
|
throw new Error(`Topic ${topicId} not found`)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!topic.enabled) {
|
||||||
|
throw new Error(`Topic ${topic.name} is disabled`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查询资讯
|
||||||
|
const articles = await this.queryArticles(topic.topicSources.map(ts => ts.sourceId), periodStart, periodEnd)
|
||||||
|
|
||||||
|
if (articles.length === 0) {
|
||||||
|
logger.warn('没有找到资讯', { topicId, periodStart, periodEnd })
|
||||||
|
|
||||||
|
await prisma.report.update({
|
||||||
|
where: { id: report.id },
|
||||||
|
data: {
|
||||||
|
title: `${topic.name} - ${this.formatDateRange(periodStart, periodEnd)}`,
|
||||||
|
content: '本期没有新的资讯。',
|
||||||
|
status: 'completed',
|
||||||
|
articleCount: 0,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return report.id
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`找到 ${articles.length} 条资讯`)
|
||||||
|
|
||||||
|
// 去重和排序
|
||||||
|
const deduplicated = await this.processorService.deduplicateArticles(articles)
|
||||||
|
const sorted = this.processorService.sortArticlesByDate(deduplicated)
|
||||||
|
|
||||||
|
logger.info(`去重后 ${sorted.length} 条资讯`)
|
||||||
|
|
||||||
|
// 处理内容
|
||||||
|
let processedContent: string
|
||||||
|
|
||||||
|
if (!topic.llmConfig || !topic.llmConfig.enabled) {
|
||||||
|
// 没有 LLM 配置,使用简单聚合
|
||||||
|
logger.warn('没有启用的 LLM 配置,使用简单聚合模式')
|
||||||
|
const result = await this.processorService.processArticles(
|
||||||
|
sorted,
|
||||||
|
'aggregate',
|
||||||
|
{} as any
|
||||||
|
)
|
||||||
|
processedContent = result.content
|
||||||
|
} else {
|
||||||
|
// 使用配置的处理模式
|
||||||
|
const result = await this.processorService.processArticles(
|
||||||
|
sorted,
|
||||||
|
topic.processMode as ProcessMode,
|
||||||
|
{
|
||||||
|
baseUrl: topic.llmConfig.baseUrl,
|
||||||
|
model: topic.llmConfig.model,
|
||||||
|
apiKey: topic.llmConfig.apiKey,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
processedContent = result.content
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成报告标题
|
||||||
|
const title = `${topic.name} - ${this.formatDateRange(periodStart, periodEnd)}`
|
||||||
|
|
||||||
|
// 生成完整报告内容
|
||||||
|
const fullContent = this.buildReportContent(
|
||||||
|
title,
|
||||||
|
topic.name,
|
||||||
|
periodStart,
|
||||||
|
periodEnd,
|
||||||
|
sorted.length,
|
||||||
|
processedContent
|
||||||
|
)
|
||||||
|
|
||||||
|
// 更新报告
|
||||||
|
await prisma.report.update({
|
||||||
|
where: { id: report.id },
|
||||||
|
data: {
|
||||||
|
title,
|
||||||
|
content: fullContent,
|
||||||
|
status: 'completed',
|
||||||
|
articleCount: sorted.length,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
logger.info(`报告生成完成: ${report.id}`)
|
||||||
|
|
||||||
|
return report.id
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('报告生成失败', { reportId: report.id, error })
|
||||||
|
|
||||||
|
// 更新报告状态为失败
|
||||||
|
await prisma.report.update({
|
||||||
|
where: { id: report.id },
|
||||||
|
data: {
|
||||||
|
status: 'failed',
|
||||||
|
errorMessage: error instanceof Error ? error.message : 'Unknown error',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询资讯
|
||||||
|
*/
|
||||||
|
private async queryArticles(
|
||||||
|
sourceIds: number[],
|
||||||
|
periodStart: Date,
|
||||||
|
periodEnd: Date
|
||||||
|
): Promise<Article[]> {
|
||||||
|
return prisma.article.findMany({
|
||||||
|
where: {
|
||||||
|
sourceId: { in: sourceIds },
|
||||||
|
OR: [
|
||||||
|
{
|
||||||
|
publishedAt: {
|
||||||
|
gte: periodStart,
|
||||||
|
lte: periodEnd,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
publishedAt: null,
|
||||||
|
collectedAt: {
|
||||||
|
gte: periodStart,
|
||||||
|
lte: periodEnd,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
orderBy: [
|
||||||
|
{ publishedAt: 'desc' },
|
||||||
|
{ collectedAt: 'desc' },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建报告内容
|
||||||
|
*/
|
||||||
|
private buildReportContent(
|
||||||
|
title: string,
|
||||||
|
topicName: string,
|
||||||
|
periodStart: Date,
|
||||||
|
periodEnd: Date,
|
||||||
|
articleCount: number,
|
||||||
|
processedContent: string
|
||||||
|
): string {
|
||||||
|
const lines: string[] = []
|
||||||
|
|
||||||
|
lines.push(`# ${title}`)
|
||||||
|
lines.push('')
|
||||||
|
lines.push(`**主题**: ${topicName}`)
|
||||||
|
lines.push(`**时间范围**: ${this.formatDate(periodStart)} - ${this.formatDate(periodEnd)}`)
|
||||||
|
lines.push(`**资讯数量**: ${articleCount} 条`)
|
||||||
|
lines.push(`**生成时间**: ${this.formatDate(new Date())}`)
|
||||||
|
lines.push('')
|
||||||
|
lines.push('---')
|
||||||
|
lines.push('')
|
||||||
|
lines.push(processedContent)
|
||||||
|
lines.push('')
|
||||||
|
lines.push('---')
|
||||||
|
lines.push('')
|
||||||
|
lines.push('*本报告由 News Aggregator 自动生成*')
|
||||||
|
|
||||||
|
return lines.join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 格式化日期范围
|
||||||
|
*/
|
||||||
|
private formatDateRange(start: Date, end: Date): string {
|
||||||
|
const startStr = this.formatDate(start)
|
||||||
|
const endStr = this.formatDate(end)
|
||||||
|
|
||||||
|
if (startStr === endStr) {
|
||||||
|
return startStr
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${startStr} 至 ${endStr}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 格式化日期
|
||||||
|
*/
|
||||||
|
private formatDate(date: Date): string {
|
||||||
|
return date.toLocaleDateString('zh-CN', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: '2-digit',
|
||||||
|
day: '2-digit',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据主题配置计算时间范围
|
||||||
|
*/
|
||||||
|
calculatePeriod(scheduleConfig: any): { start: Date; end: Date } {
|
||||||
|
const now = new Date()
|
||||||
|
const lookback = scheduleConfig.lookback || 24 // 默认回溯 24 小时
|
||||||
|
|
||||||
|
const end = now
|
||||||
|
const start = new Date(now.getTime() - lookback * 60 * 60 * 1000)
|
||||||
|
|
||||||
|
return { start, end }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 为主题生成报告(使用主题的时间配置)
|
||||||
|
*/
|
||||||
|
async generateReportForTopic(topicId: number): Promise<number> {
|
||||||
|
const topic = await prisma.topic.findUnique({
|
||||||
|
where: { id: topicId },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!topic) {
|
||||||
|
throw new Error(`Topic ${topicId} not found`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const scheduleConfig = topic.scheduleConfig as any
|
||||||
|
const { start, end } = this.calculatePeriod(scheduleConfig)
|
||||||
|
|
||||||
|
return this.generateReport({
|
||||||
|
topicId,
|
||||||
|
periodStart: start,
|
||||||
|
periodEnd: end,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 为所有启用的主题生成报告
|
||||||
|
*/
|
||||||
|
async generateReportsForAllTopics(): Promise<number[]> {
|
||||||
|
const topics = await prisma.topic.findMany({
|
||||||
|
where: { enabled: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
logger.info(`开始为 ${topics.length} 个主题生成报告`)
|
||||||
|
|
||||||
|
const reportIds: number[] = []
|
||||||
|
|
||||||
|
for (const topic of topics) {
|
||||||
|
try {
|
||||||
|
const reportId = await this.generateReportForTopic(topic.id)
|
||||||
|
reportIds.push(reportId)
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`主题 ${topic.name} 报告生成失败`, error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`报告生成完成,成功 ${reportIds.length}/${topics.length}`)
|
||||||
|
|
||||||
|
return reportIds
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取报告详情
|
||||||
|
*/
|
||||||
|
async getReport(reportId: number) {
|
||||||
|
return prisma.report.findUnique({
|
||||||
|
where: { id: reportId },
|
||||||
|
include: {
|
||||||
|
topic: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取报告列表
|
||||||
|
*/
|
||||||
|
async getReports(options: {
|
||||||
|
topicId?: number
|
||||||
|
status?: string
|
||||||
|
page?: number
|
||||||
|
limit?: number
|
||||||
|
}) {
|
||||||
|
const { topicId, status, page = 1, limit = 20 } = options
|
||||||
|
|
||||||
|
const where: any = {}
|
||||||
|
if (topicId) where.topicId = topicId
|
||||||
|
if (status) where.status = status
|
||||||
|
|
||||||
|
const [items, total] = await Promise.all([
|
||||||
|
prisma.report.findMany({
|
||||||
|
where,
|
||||||
|
include: {
|
||||||
|
topic: true,
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
skip: (page - 1) * limit,
|
||||||
|
take: limit,
|
||||||
|
}),
|
||||||
|
prisma.report.count({ where }),
|
||||||
|
])
|
||||||
|
|
||||||
|
return {
|
||||||
|
items,
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
totalPages: Math.ceil(total / limit),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 更新服务导出
|
||||||
|
|
||||||
|
更新 `backend/src/services/index.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export * from './collector.service'
|
||||||
|
export * from './processor.service'
|
||||||
|
export * from './report.service'
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 创建测试脚本
|
||||||
|
|
||||||
|
创建 `backend/src/test-report.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { ReportService } from './services/report.service'
|
||||||
|
import prisma from './utils/prisma'
|
||||||
|
|
||||||
|
async function test() {
|
||||||
|
const reportService = new ReportService()
|
||||||
|
|
||||||
|
// 查询一个启用的主题
|
||||||
|
const topic = await prisma.topic.findFirst({
|
||||||
|
where: { enabled: true },
|
||||||
|
include: {
|
||||||
|
topicSources: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!topic) {
|
||||||
|
console.log('没有启用的主题')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`找到主题: ${topic.name}`)
|
||||||
|
console.log(`关联数据源数量: ${topic.topicSources.length}`)
|
||||||
|
|
||||||
|
// 生成报告
|
||||||
|
console.log('\n开始生成报告...')
|
||||||
|
try {
|
||||||
|
const reportId = await reportService.generateReportForTopic(topic.id)
|
||||||
|
console.log(`报告生成成功,ID: ${reportId}`)
|
||||||
|
|
||||||
|
// 查看报告
|
||||||
|
const report = await reportService.getReport(reportId)
|
||||||
|
if (report) {
|
||||||
|
console.log('\n=== 报告详情 ===')
|
||||||
|
console.log(`标题: ${report.title}`)
|
||||||
|
console.log(`状态: ${report.status}`)
|
||||||
|
console.log(`资讯数量: ${report.articleCount}`)
|
||||||
|
console.log(`时间范围: ${report.periodStart} - ${report.periodEnd}`)
|
||||||
|
console.log('\n内容预览:')
|
||||||
|
console.log(report.content.substring(0, 500))
|
||||||
|
console.log('...')
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('报告生成失败:', error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查询报告列表
|
||||||
|
console.log('\n=== 报告列表 ===')
|
||||||
|
const reports = await reportService.getReports({
|
||||||
|
topicId: topic.id,
|
||||||
|
page: 1,
|
||||||
|
limit: 5,
|
||||||
|
})
|
||||||
|
console.log(`共 ${reports.total} 条报告`)
|
||||||
|
reports.items.forEach((report) => {
|
||||||
|
console.log(`- [${report.status}] ${report.title} (${report.articleCount} 条资讯)`)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
test()
|
||||||
|
.catch(console.error)
|
||||||
|
.finally(() => prisma.$disconnect())
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 创建手动生成报告的脚本
|
||||||
|
|
||||||
|
创建 `backend/src/scripts/generate-report.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { ReportService } from '../services/report.service'
|
||||||
|
import prisma from '../utils/prisma'
|
||||||
|
import { logger } from '../utils/logger'
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const args = process.argv.slice(2)
|
||||||
|
const reportService = new ReportService()
|
||||||
|
|
||||||
|
if (args.length === 0) {
|
||||||
|
// 为所有主题生成报告
|
||||||
|
logger.info('为所有启用的主题生成报告')
|
||||||
|
const reportIds = await reportService.generateReportsForAllTopics()
|
||||||
|
logger.info(`完成,生成了 ${reportIds.length} 份报告`)
|
||||||
|
} else {
|
||||||
|
// 为指定主题生成报告
|
||||||
|
const topicId = parseInt(args[0], 10)
|
||||||
|
if (isNaN(topicId)) {
|
||||||
|
console.error('用法: tsx src/scripts/generate-report.ts [topicId]')
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`为主题 ${topicId} 生成报告`)
|
||||||
|
const reportId = await reportService.generateReportForTopic(topicId)
|
||||||
|
logger.info(`完成,报告 ID: ${reportId}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
.catch((error) => {
|
||||||
|
logger.error('报告生成失败', error)
|
||||||
|
process.exit(1)
|
||||||
|
})
|
||||||
|
.finally(() => prisma.$disconnect())
|
||||||
|
```
|
||||||
|
|
||||||
|
## 验证步骤
|
||||||
|
|
||||||
|
### 1. 准备测试数据
|
||||||
|
|
||||||
|
确保有资讯数据和启用的主题:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 查看主题
|
||||||
|
npm run prisma:studio
|
||||||
|
|
||||||
|
# 确保:
|
||||||
|
# 1. topics 表有启用的主题
|
||||||
|
# 2. topic_sources 表有关联
|
||||||
|
# 3. articles 表有资讯数据
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 运行测试
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx tsx src/test-report.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
预期输出:
|
||||||
|
```
|
||||||
|
找到主题: 科技资讯
|
||||||
|
关联数据源数量: 1
|
||||||
|
|
||||||
|
开始生成报告...
|
||||||
|
报告生成成功,ID: 1
|
||||||
|
|
||||||
|
=== 报告详情 ===
|
||||||
|
标题: 科技资讯 - 2024-01-01 至 2024-01-02
|
||||||
|
状态: completed
|
||||||
|
资讯数量: 5
|
||||||
|
时间范围: 2024-01-01 - 2024-01-02
|
||||||
|
|
||||||
|
内容预览:
|
||||||
|
# 科技资讯 - 2024-01-01 至 2024-01-02
|
||||||
|
|
||||||
|
**主题**: 科技资讯
|
||||||
|
**时间范围**: 2024-01-01 - 2024-01-02
|
||||||
|
**资讯数量**: 5 条
|
||||||
|
**生成时间**: 2024-01-02
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
1. **标题1**
|
||||||
|
链接: https://...
|
||||||
|
...
|
||||||
|
|
||||||
|
=== 报告列表 ===
|
||||||
|
共 1 条报告
|
||||||
|
- [completed] 科技资讯 - 2024-01-01 至 2024-01-02 (5 条资讯)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 测试手动生成报告
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 为所有主题生成报告
|
||||||
|
npx tsx src/scripts/generate-report.ts
|
||||||
|
|
||||||
|
# 为指定主题生成报告
|
||||||
|
npx tsx src/scripts/generate-report.ts 1
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 验证数据库
|
||||||
|
|
||||||
|
使用 Prisma Studio 查看:
|
||||||
|
```bash
|
||||||
|
npm run prisma:studio
|
||||||
|
```
|
||||||
|
|
||||||
|
检查 `reports` 表:
|
||||||
|
- 有新的报告记录
|
||||||
|
- status 为 completed
|
||||||
|
- content 有完整内容
|
||||||
|
- articleCount 正确
|
||||||
|
|
||||||
|
### 5. 测试不同处理模式
|
||||||
|
|
||||||
|
在 Prisma Studio 中修改主题的 `process_mode`:
|
||||||
|
- `aggregate` - 简单聚合
|
||||||
|
- `summary` - AI 摘要
|
||||||
|
- `deep_analysis` - AI 深度整理
|
||||||
|
|
||||||
|
然后重新生成报告,查看不同的输出效果。
|
||||||
|
|
||||||
|
## 预期产物
|
||||||
|
|
||||||
|
- ✅ 报告生成服务实现完成
|
||||||
|
- ✅ 按时间范围查询资讯功能完成
|
||||||
|
- ✅ 集成内容处理功能完成
|
||||||
|
- ✅ 报告保存到数据库完成
|
||||||
|
- ✅ 报告查询功能完成
|
||||||
|
- ✅ 手动生成报告脚本完成
|
||||||
|
- ✅ 测试通过
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
### 问题 1:没有找到资讯
|
||||||
|
**解决方案**:
|
||||||
|
- 检查时间范围是否正确
|
||||||
|
- 检查数据源是否有采集到资讯
|
||||||
|
- 检查主题是否关联了数据源
|
||||||
|
|
||||||
|
### 问题 2:报告生成失败
|
||||||
|
**解决方案**:
|
||||||
|
- 查看错误日志
|
||||||
|
- 检查 LLM 配置是否正确
|
||||||
|
- 检查资讯数据是否完整
|
||||||
|
|
||||||
|
### 问题 3:报告内容为空
|
||||||
|
**解决方案**:
|
||||||
|
- 检查时间范围内是否有资讯
|
||||||
|
- 检查内容处理是否正常
|
||||||
|
- 查看 reports 表的 error_message 字段
|
||||||
|
|
||||||
|
## 下一步
|
||||||
|
|
||||||
|
完成本任务后,继续 [任务 07:分发器实现](./07-distributors.md)。
|
||||||
@@ -0,0 +1,951 @@
|
|||||||
|
# 任务 07:分发器实现
|
||||||
|
|
||||||
|
## 任务概述
|
||||||
|
实现插件式分发器架构,支持邮件、钉钉、企业微信、Slack 等多种推送渠道。
|
||||||
|
|
||||||
|
## 前置条件
|
||||||
|
- 任务 01-06 已完成
|
||||||
|
- 报告生成服务已实现
|
||||||
|
|
||||||
|
## 任务目标
|
||||||
|
- 创建分发器基类接口
|
||||||
|
- 实现邮件分发器
|
||||||
|
- 实现钉钉分发器
|
||||||
|
- 实现企业微信分发器
|
||||||
|
- 实现 Slack 分发器
|
||||||
|
- 创建分发器工厂
|
||||||
|
- 实现分发服务
|
||||||
|
|
||||||
|
## 详细步骤
|
||||||
|
|
||||||
|
### 1. 安装依赖
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
npm install nodemailer
|
||||||
|
npm install -D @types/nodemailer
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 创建分发器类型定义
|
||||||
|
|
||||||
|
创建 `backend/src/types/distributor.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export type DistributorType = 'email' | 'dingtalk' | 'wechat' | 'slack'
|
||||||
|
|
||||||
|
export interface DistributorConfig {
|
||||||
|
[key: string]: any
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DistributionResult {
|
||||||
|
success: boolean
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReportSummary {
|
||||||
|
title: string
|
||||||
|
topicName: string
|
||||||
|
articleCount: number
|
||||||
|
periodStart: Date
|
||||||
|
periodEnd: Date
|
||||||
|
webUrl: string
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 创建分发器基类
|
||||||
|
|
||||||
|
创建 `backend/src/distributors/base.distributor.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import type { DistributorType, DistributorConfig, DistributionResult, ReportSummary } from '../types/distributor'
|
||||||
|
|
||||||
|
export abstract class BaseDistributor {
|
||||||
|
constructor(
|
||||||
|
protected config: DistributorConfig,
|
||||||
|
protected channelId: number
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行分发
|
||||||
|
*/
|
||||||
|
abstract distribute(summary: ReportSummary, fullContent: string): Promise<DistributionResult>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证配置
|
||||||
|
*/
|
||||||
|
abstract validateConfig(): boolean
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取分发器类型
|
||||||
|
*/
|
||||||
|
abstract getType(): DistributorType
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 实现邮件分发器
|
||||||
|
|
||||||
|
创建 `backend/src/distributors/email.distributor.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { BaseDistributor } from './base.distributor'
|
||||||
|
import type { DistributorType, DistributionResult, ReportSummary } from '../types/distributor'
|
||||||
|
import nodemailer from 'nodemailer'
|
||||||
|
import { logger } from '../utils/logger'
|
||||||
|
|
||||||
|
interface EmailConfig {
|
||||||
|
smtp: {
|
||||||
|
host: string
|
||||||
|
port: number
|
||||||
|
secure: boolean
|
||||||
|
auth: {
|
||||||
|
user: string
|
||||||
|
pass: string
|
||||||
|
}
|
||||||
|
}
|
||||||
|
from: string
|
||||||
|
to: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export class EmailDistributor extends BaseDistributor {
|
||||||
|
private config: EmailConfig
|
||||||
|
|
||||||
|
constructor(config: EmailConfig, channelId: number) {
|
||||||
|
super(config, channelId)
|
||||||
|
this.config = config
|
||||||
|
}
|
||||||
|
|
||||||
|
async distribute(summary: ReportSummary, fullContent: string): Promise<DistributionResult> {
|
||||||
|
try {
|
||||||
|
logger.info('邮件分发器开始发送', {
|
||||||
|
to: this.config.to,
|
||||||
|
title: summary.title,
|
||||||
|
})
|
||||||
|
|
||||||
|
// 创建邮件传输器
|
||||||
|
const transporter = nodemailer.createTransport(this.config.smtp)
|
||||||
|
|
||||||
|
// 构建邮件内容
|
||||||
|
const htmlContent = this.buildHtmlContent(summary, fullContent)
|
||||||
|
const textContent = this.buildTextContent(summary)
|
||||||
|
|
||||||
|
// 发送邮件
|
||||||
|
await transporter.sendMail({
|
||||||
|
from: this.config.from,
|
||||||
|
to: this.config.to.join(', '),
|
||||||
|
subject: summary.title,
|
||||||
|
text: textContent,
|
||||||
|
html: htmlContent,
|
||||||
|
})
|
||||||
|
|
||||||
|
logger.info('邮件发送成功')
|
||||||
|
|
||||||
|
return { success: true }
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('邮件发送失败', error)
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: error instanceof Error ? error.message : 'Unknown error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
validateConfig(): boolean {
|
||||||
|
return !!(
|
||||||
|
this.config.smtp &&
|
||||||
|
this.config.smtp.host &&
|
||||||
|
this.config.smtp.auth &&
|
||||||
|
this.config.from &&
|
||||||
|
this.config.to &&
|
||||||
|
this.config.to.length > 0
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
getType(): DistributorType {
|
||||||
|
return 'email'
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildHtmlContent(summary: ReportSummary, fullContent: string): string {
|
||||||
|
// 将 Markdown 转换为简单的 HTML(这里简化处理)
|
||||||
|
const htmlContent = fullContent
|
||||||
|
.replace(/^# (.+)$/gm, '<h1>$1</h1>')
|
||||||
|
.replace(/^## (.+)$/gm, '<h2>$1</h2>')
|
||||||
|
.replace(/^### (.+)$/gm, '<h3>$1</h3>')
|
||||||
|
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
|
||||||
|
.replace(/\*(.+?)\*/g, '<em>$1</em>')
|
||||||
|
.replace(/\[(.+?)\]\((.+?)\)/g, '<a href="$2">$1</a>')
|
||||||
|
.replace(/\n/g, '<br>')
|
||||||
|
|
||||||
|
return `
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<style>
|
||||||
|
body {
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||||
|
line-height: 1.6;
|
||||||
|
color: #333;
|
||||||
|
max-width: 800px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
h1 { color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px; }
|
||||||
|
h2 { color: #34495e; margin-top: 30px; }
|
||||||
|
h3 { color: #7f8c8d; }
|
||||||
|
a { color: #3498db; text-decoration: none; }
|
||||||
|
a:hover { text-decoration: underline; }
|
||||||
|
.summary {
|
||||||
|
background: #ecf0f1;
|
||||||
|
padding: 15px;
|
||||||
|
border-radius: 5px;
|
||||||
|
margin: 20px 0;
|
||||||
|
}
|
||||||
|
.button {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 10px 20px;
|
||||||
|
background: #3498db;
|
||||||
|
color: white !important;
|
||||||
|
text-decoration: none;
|
||||||
|
border-radius: 5px;
|
||||||
|
margin: 20px 0;
|
||||||
|
}
|
||||||
|
.footer {
|
||||||
|
margin-top: 40px;
|
||||||
|
padding-top: 20px;
|
||||||
|
border-top: 1px solid #ecf0f1;
|
||||||
|
color: #7f8c8d;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="summary">
|
||||||
|
<p><strong>主题:</strong> ${summary.topicName}</p>
|
||||||
|
<p><strong>资讯数量:</strong> ${summary.articleCount} 条</p>
|
||||||
|
<p><strong>时间范围:</strong> ${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<a href="${summary.webUrl}" class="button">查看完整报告</a>
|
||||||
|
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
<div class="content">
|
||||||
|
${htmlContent}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="footer">
|
||||||
|
<p>本邮件由 News Aggregator 自动发送</p>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
`
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildTextContent(summary: ReportSummary): string {
|
||||||
|
return `
|
||||||
|
${summary.title}
|
||||||
|
|
||||||
|
主题: ${summary.topicName}
|
||||||
|
资讯数量: ${summary.articleCount} 条
|
||||||
|
时间范围: ${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}
|
||||||
|
|
||||||
|
查看完整报告: ${summary.webUrl}
|
||||||
|
|
||||||
|
---
|
||||||
|
本邮件由 News Aggregator 自动发送
|
||||||
|
`.trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
private formatDate(date: Date): string {
|
||||||
|
return date.toLocaleDateString('zh-CN')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 实现钉钉分发器
|
||||||
|
|
||||||
|
创建 `backend/src/distributors/dingtalk.distributor.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { BaseDistributor } from './base.distributor'
|
||||||
|
import type { DistributorType, DistributionResult, ReportSummary } from '../types/distributor'
|
||||||
|
import crypto from 'crypto'
|
||||||
|
import { logger } from '../utils/logger'
|
||||||
|
|
||||||
|
interface DingtalkConfig {
|
||||||
|
webhook: string
|
||||||
|
secret?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export class DingtalkDistributor extends BaseDistributor {
|
||||||
|
private config: DingtalkConfig
|
||||||
|
|
||||||
|
constructor(config: DingtalkConfig, channelId: number) {
|
||||||
|
super(config, channelId)
|
||||||
|
this.config = config
|
||||||
|
}
|
||||||
|
|
||||||
|
async distribute(summary: ReportSummary, fullContent: string): Promise<DistributionResult> {
|
||||||
|
try {
|
||||||
|
logger.info('钉钉分发器开始发送', { title: summary.title })
|
||||||
|
|
||||||
|
// 构建签名(如果有 secret)
|
||||||
|
let url = this.config.webhook
|
||||||
|
if (this.config.secret) {
|
||||||
|
const timestamp = Date.now()
|
||||||
|
const sign = this.generateSign(timestamp, this.config.secret)
|
||||||
|
url = `${url}×tamp=${timestamp}&sign=${sign}`
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构建消息内容
|
||||||
|
const message = this.buildMessage(summary)
|
||||||
|
|
||||||
|
// 发送请求
|
||||||
|
const response = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify(message),
|
||||||
|
})
|
||||||
|
|
||||||
|
const result = await response.json()
|
||||||
|
|
||||||
|
if (result.errcode !== 0) {
|
||||||
|
throw new Error(`钉钉 API 错误: ${result.errmsg}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info('钉钉消息发送成功')
|
||||||
|
|
||||||
|
return { success: true }
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('钉钉消息发送失败', error)
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: error instanceof Error ? error.message : 'Unknown error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
validateConfig(): boolean {
|
||||||
|
return !!this.config.webhook
|
||||||
|
}
|
||||||
|
|
||||||
|
getType(): DistributorType {
|
||||||
|
return 'dingtalk'
|
||||||
|
}
|
||||||
|
|
||||||
|
private generateSign(timestamp: number, secret: string): string {
|
||||||
|
const stringToSign = `${timestamp}\n${secret}`
|
||||||
|
const hmac = crypto.createHmac('sha256', secret)
|
||||||
|
hmac.update(stringToSign)
|
||||||
|
return encodeURIComponent(hmac.digest('base64'))
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildMessage(summary: ReportSummary) {
|
||||||
|
const text = `# ${summary.title}
|
||||||
|
|
||||||
|
**主题**: ${summary.topicName}
|
||||||
|
**资讯数量**: ${summary.articleCount} 条
|
||||||
|
**时间范围**: ${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}
|
||||||
|
|
||||||
|
[查看完整报告](${summary.webUrl})`
|
||||||
|
|
||||||
|
return {
|
||||||
|
msgtype: 'markdown',
|
||||||
|
markdown: {
|
||||||
|
title: summary.title,
|
||||||
|
text,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private formatDate(date: Date): string {
|
||||||
|
return date.toLocaleDateString('zh-CN')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6. 实现企业微信分发器
|
||||||
|
|
||||||
|
创建 `backend/src/distributors/wechat.distributor.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { BaseDistributor } from './base.distributor'
|
||||||
|
import type { DistributorType, DistributionResult, ReportSummary } from '../types/distributor'
|
||||||
|
import { logger } from '../utils/logger'
|
||||||
|
|
||||||
|
interface WechatConfig {
|
||||||
|
webhook: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export class WechatDistributor extends BaseDistributor {
|
||||||
|
private config: WechatConfig
|
||||||
|
|
||||||
|
constructor(config: WechatConfig, channelId: number) {
|
||||||
|
super(config, channelId)
|
||||||
|
this.config = config
|
||||||
|
}
|
||||||
|
|
||||||
|
async distribute(summary: ReportSummary, fullContent: string): Promise<DistributionResult> {
|
||||||
|
try {
|
||||||
|
logger.info('企业微信分发器开始发送', { title: summary.title })
|
||||||
|
|
||||||
|
// 构建消息内容
|
||||||
|
const message = this.buildMessage(summary)
|
||||||
|
|
||||||
|
// 发送请求
|
||||||
|
const response = await fetch(this.config.webhook, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify(message),
|
||||||
|
})
|
||||||
|
|
||||||
|
const result = await response.json()
|
||||||
|
|
||||||
|
if (result.errcode !== 0) {
|
||||||
|
throw new Error(`企业微信 API 错误: ${result.errmsg}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info('企业微信消息发送成功')
|
||||||
|
|
||||||
|
return { success: true }
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('企业微信消息发送失败', error)
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: error instanceof Error ? error.message : 'Unknown error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
validateConfig(): boolean {
|
||||||
|
return !!this.config.webhook
|
||||||
|
}
|
||||||
|
|
||||||
|
getType(): DistributorType {
|
||||||
|
return 'wechat'
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildMessage(summary: ReportSummary) {
|
||||||
|
const content = `# ${summary.title}
|
||||||
|
|
||||||
|
> 主题: ${summary.topicName}
|
||||||
|
> 资讯数量: ${summary.articleCount} 条
|
||||||
|
> 时间范围: ${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}
|
||||||
|
|
||||||
|
[查看完整报告](${summary.webUrl})`
|
||||||
|
|
||||||
|
return {
|
||||||
|
msgtype: 'markdown',
|
||||||
|
markdown: {
|
||||||
|
content,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private formatDate(date: Date): string {
|
||||||
|
return date.toLocaleDateString('zh-CN')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7. 实现 Slack 分发器
|
||||||
|
|
||||||
|
创建 `backend/src/distributors/slack.distributor.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { BaseDistributor } from './base.distributor'
|
||||||
|
import type { DistributorType, DistributionResult, ReportSummary } from '../types/distributor'
|
||||||
|
import { logger } from '../utils/logger'
|
||||||
|
|
||||||
|
interface SlackConfig {
|
||||||
|
webhook: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SlackDistributor extends BaseDistributor {
|
||||||
|
private config: SlackConfig
|
||||||
|
|
||||||
|
constructor(config: SlackConfig, channelId: number) {
|
||||||
|
super(config, channelId)
|
||||||
|
this.config = config
|
||||||
|
}
|
||||||
|
|
||||||
|
async distribute(summary: ReportSummary, fullContent: string): Promise<DistributionResult> {
|
||||||
|
try {
|
||||||
|
logger.info('Slack 分发器开始发送', { title: summary.title })
|
||||||
|
|
||||||
|
// 构建消息内容
|
||||||
|
const message = this.buildMessage(summary)
|
||||||
|
|
||||||
|
// 发送请求
|
||||||
|
const response = await fetch(this.config.webhook, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify(message),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Slack API 错误: ${response.statusText}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info('Slack 消息发送成功')
|
||||||
|
|
||||||
|
return { success: true }
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Slack 消息发送失败', error)
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: error instanceof Error ? error.message : 'Unknown error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
validateConfig(): boolean {
|
||||||
|
return !!this.config.webhook
|
||||||
|
}
|
||||||
|
|
||||||
|
getType(): DistributorType {
|
||||||
|
return 'slack'
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildMessage(summary: ReportSummary) {
|
||||||
|
return {
|
||||||
|
blocks: [
|
||||||
|
{
|
||||||
|
type: 'header',
|
||||||
|
text: {
|
||||||
|
type: 'plain_text',
|
||||||
|
text: summary.title,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'section',
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
type: 'mrkdwn',
|
||||||
|
text: `*主题:*\n${summary.topicName}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'mrkdwn',
|
||||||
|
text: `*资讯数量:*\n${summary.articleCount} 条`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'mrkdwn',
|
||||||
|
text: `*时间范围:*\n${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}`,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'actions',
|
||||||
|
elements: [
|
||||||
|
{
|
||||||
|
type: 'button',
|
||||||
|
text: {
|
||||||
|
type: 'plain_text',
|
||||||
|
text: '查看完整报告',
|
||||||
|
},
|
||||||
|
url: summary.webUrl,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private formatDate(date: Date): string {
|
||||||
|
return date.toLocaleDateString('zh-CN')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8. 创建分发器工厂
|
||||||
|
|
||||||
|
创建 `backend/src/distributors/distributor.factory.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import type { BaseDistributor } from './base.distributor'
|
||||||
|
import { EmailDistributor } from './email.distributor'
|
||||||
|
import { DingtalkDistributor } from './dingtalk.distributor'
|
||||||
|
import { WechatDistributor } from './wechat.distributor'
|
||||||
|
import { SlackDistributor } from './slack.distributor'
|
||||||
|
import type { DistributorType, DistributorConfig } from '../types/distributor'
|
||||||
|
|
||||||
|
export class DistributorFactory {
|
||||||
|
static create(
|
||||||
|
type: DistributorType,
|
||||||
|
config: DistributorConfig,
|
||||||
|
channelId: number
|
||||||
|
): BaseDistributor {
|
||||||
|
switch (type) {
|
||||||
|
case 'email':
|
||||||
|
return new EmailDistributor(config, channelId)
|
||||||
|
case 'dingtalk':
|
||||||
|
return new DingtalkDistributor(config, channelId)
|
||||||
|
case 'wechat':
|
||||||
|
return new WechatDistributor(config, channelId)
|
||||||
|
case 'slack':
|
||||||
|
return new SlackDistributor(config, channelId)
|
||||||
|
default:
|
||||||
|
throw new Error(`Unknown distributor type: ${type}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 9. 创建分发服务
|
||||||
|
|
||||||
|
创建 `backend/src/services/distributor.service.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import prisma from '../utils/prisma'
|
||||||
|
import { DistributorFactory } from '../distributors/distributor.factory'
|
||||||
|
import { logger } from '../utils/logger'
|
||||||
|
import type { ReportSummary } from '../types/distributor'
|
||||||
|
import { config } from '../config'
|
||||||
|
|
||||||
|
export class DistributorService {
|
||||||
|
/**
|
||||||
|
* 分发报告到指定渠道
|
||||||
|
*/
|
||||||
|
async distributeReport(reportId: number, channelId: number): Promise<void> {
|
||||||
|
let status: 'success' | 'failed' = 'success'
|
||||||
|
let errorMessage: string | undefined
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 查询报告
|
||||||
|
const report = await prisma.report.findUnique({
|
||||||
|
where: { id: reportId },
|
||||||
|
include: {
|
||||||
|
topic: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!report) {
|
||||||
|
throw new Error(`Report ${reportId} not found`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查询渠道
|
||||||
|
const channel = await prisma.channel.findUnique({
|
||||||
|
where: { id: channelId },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!channel) {
|
||||||
|
throw new Error(`Channel ${channelId} not found`)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!channel.enabled) {
|
||||||
|
logger.info(`渠道 ${channel.name} 已禁用,跳过分发`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`开始分发报告: ${report.title} -> ${channel.name}`)
|
||||||
|
|
||||||
|
// 创建分发器
|
||||||
|
const distributor = DistributorFactory.create(
|
||||||
|
channel.type as any,
|
||||||
|
channel.config as any,
|
||||||
|
channel.id
|
||||||
|
)
|
||||||
|
|
||||||
|
// 验证配置
|
||||||
|
if (!distributor.validateConfig()) {
|
||||||
|
throw new Error('Invalid distributor config')
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构建报告摘要
|
||||||
|
const summary: ReportSummary = {
|
||||||
|
title: report.title,
|
||||||
|
topicName: report.topic.name,
|
||||||
|
articleCount: report.articleCount,
|
||||||
|
periodStart: report.periodStart,
|
||||||
|
periodEnd: report.periodEnd,
|
||||||
|
webUrl: this.buildReportUrl(reportId),
|
||||||
|
}
|
||||||
|
|
||||||
|
// 执行分发
|
||||||
|
const result = await distributor.distribute(summary, report.content)
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
throw new Error(result.error || 'Distribution failed')
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`报告分发成功: ${channel.name}`)
|
||||||
|
} catch (error) {
|
||||||
|
status = 'failed'
|
||||||
|
errorMessage = error instanceof Error ? error.message : 'Unknown error'
|
||||||
|
logger.error('报告分发失败', { reportId, channelId, error: errorMessage })
|
||||||
|
} finally {
|
||||||
|
// 记录分发日志
|
||||||
|
await prisma.pushLog.create({
|
||||||
|
data: {
|
||||||
|
reportId,
|
||||||
|
channelId,
|
||||||
|
status,
|
||||||
|
errorMessage,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分发报告到所有关联的渠道
|
||||||
|
*/
|
||||||
|
async distributeReportToAllChannels(reportId: number): Promise<void> {
|
||||||
|
const report = await prisma.report.findUnique({
|
||||||
|
where: { id: reportId },
|
||||||
|
include: {
|
||||||
|
topic: {
|
||||||
|
include: {
|
||||||
|
topicChannels: {
|
||||||
|
include: {
|
||||||
|
channel: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!report) {
|
||||||
|
throw new Error(`Report ${reportId} not found`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const channels = report.topic.topicChannels
|
||||||
|
.map(tc => tc.channel)
|
||||||
|
.filter(c => c.enabled)
|
||||||
|
|
||||||
|
logger.info(`开始分发报告到 ${channels.length} 个渠道`)
|
||||||
|
|
||||||
|
for (const channel of channels) {
|
||||||
|
await this.distributeReport(reportId, channel.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info('报告分发完成')
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建报告 Web URL
|
||||||
|
*/
|
||||||
|
private buildReportUrl(reportId: number): string {
|
||||||
|
const baseUrl = process.env.WEB_BASE_URL || `http://localhost:${config.app.port}`
|
||||||
|
return `${baseUrl}/reports/${reportId}`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 10. 更新类型导出
|
||||||
|
|
||||||
|
更新 `backend/src/types/index.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export * from './api'
|
||||||
|
export * from './collector'
|
||||||
|
export * from './llm'
|
||||||
|
export * from './distributor'
|
||||||
|
|
||||||
|
export type ProcessMode = 'aggregate' | 'summary' | 'deep_analysis'
|
||||||
|
export type ReportStatus = 'pending' | 'generating' | 'completed' | 'failed'
|
||||||
|
|
||||||
|
export interface ProcessedContent {
|
||||||
|
content: string
|
||||||
|
mode: ProcessMode
|
||||||
|
articlesCount: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReportGenerationOptions {
|
||||||
|
topicId: number
|
||||||
|
periodStart: Date
|
||||||
|
periodEnd: Date
|
||||||
|
manualTrigger?: boolean
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 11. 更新服务导出
|
||||||
|
|
||||||
|
更新 `backend/src/services/index.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export * from './collector.service'
|
||||||
|
export * from './processor.service'
|
||||||
|
export * from './report.service'
|
||||||
|
export * from './distributor.service'
|
||||||
|
```
|
||||||
|
|
||||||
|
### 12. 创建分发器导出
|
||||||
|
|
||||||
|
创建 `backend/src/distributors/index.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export * from './base.distributor'
|
||||||
|
export * from './email.distributor'
|
||||||
|
export * from './dingtalk.distributor'
|
||||||
|
export * from './wechat.distributor'
|
||||||
|
export * from './slack.distributor'
|
||||||
|
export * from './distributor.factory'
|
||||||
|
```
|
||||||
|
|
||||||
|
## 验证步骤
|
||||||
|
|
||||||
|
### 1. 配置测试渠道
|
||||||
|
|
||||||
|
使用 Prisma Studio 配置一个测试渠道:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run prisma:studio
|
||||||
|
```
|
||||||
|
|
||||||
|
在 `channels` 表中添加或更新记录,例如钉钉:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"webhook": "https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN",
|
||||||
|
"secret": "YOUR_SECRET"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 创建测试脚本
|
||||||
|
|
||||||
|
创建 `backend/src/test-distributor.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { DistributorService } from './services/distributor.service'
|
||||||
|
import { ReportService } from './services/report.service'
|
||||||
|
import prisma from './utils/prisma'
|
||||||
|
|
||||||
|
async function test() {
|
||||||
|
const distributorService = new DistributorService()
|
||||||
|
const reportService = new ReportService()
|
||||||
|
|
||||||
|
// 查询一个已完成的报告
|
||||||
|
let report = await prisma.report.findFirst({
|
||||||
|
where: { status: 'completed' },
|
||||||
|
include: {
|
||||||
|
topic: {
|
||||||
|
include: {
|
||||||
|
topicChannels: {
|
||||||
|
include: {
|
||||||
|
channel: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 如果没有报告,先生成一个
|
||||||
|
if (!report) {
|
||||||
|
console.log('没有找到报告,先生成一个...')
|
||||||
|
const topic = await prisma.topic.findFirst({
|
||||||
|
where: { enabled: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!topic) {
|
||||||
|
console.log('没有启用的主题')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const reportId = await reportService.generateReportForTopic(topic.id)
|
||||||
|
report = await prisma.report.findUnique({
|
||||||
|
where: { id: reportId },
|
||||||
|
include: {
|
||||||
|
topic: {
|
||||||
|
include: {
|
||||||
|
topicChannels: {
|
||||||
|
include: {
|
||||||
|
channel: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!report) {
|
||||||
|
console.log('无法获取报告')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`找到报告: ${report.title}`)
|
||||||
|
console.log(`关联渠道数量: ${report.topic.topicChannels.length}`)
|
||||||
|
|
||||||
|
// 测试分发
|
||||||
|
console.log('\n开始分发报告...')
|
||||||
|
await distributorService.distributeReportToAllChannels(report.id)
|
||||||
|
|
||||||
|
// 查看分发日志
|
||||||
|
const logs = await prisma.pushLog.findMany({
|
||||||
|
where: { reportId: report.id },
|
||||||
|
include: {
|
||||||
|
channel: true,
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
})
|
||||||
|
|
||||||
|
console.log('\n=== 分发日志 ===')
|
||||||
|
logs.forEach((log) => {
|
||||||
|
console.log(`- [${log.status}] ${log.channel.name}${log.errorMessage ? `: ${log.errorMessage}` : ''}`)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
test()
|
||||||
|
.catch(console.error)
|
||||||
|
.finally(() => prisma.$disconnect())
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 运行测试
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx tsx src/test-distributor.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 验证推送
|
||||||
|
|
||||||
|
检查对应的渠道是否收到消息:
|
||||||
|
- 邮件:检查邮箱
|
||||||
|
- 钉钉:检查钉钉群
|
||||||
|
- 企业微信:检查企业微信群
|
||||||
|
- Slack:检查 Slack 频道
|
||||||
|
|
||||||
|
### 5. 验证数据库
|
||||||
|
|
||||||
|
使用 Prisma Studio 查看 `push_logs` 表,确认有分发记录。
|
||||||
|
|
||||||
|
## 预期产物
|
||||||
|
|
||||||
|
- ✅ 分发器基类创建完成
|
||||||
|
- ✅ 邮件分发器实现完成
|
||||||
|
- ✅ 钉钉分发器实现完成
|
||||||
|
- ✅ 企业微信分发器实现完成
|
||||||
|
- ✅ Slack 分发器实现完成
|
||||||
|
- ✅ 分发器工厂创建完成
|
||||||
|
- ✅ 分发服务实现完成
|
||||||
|
- ✅ 测试通过
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
### 问题 1:邮件发送失败
|
||||||
|
**解决方案**:
|
||||||
|
- 检查 SMTP 配置是否正确
|
||||||
|
- 检查邮箱密码(可能需要使用应用专用密码)
|
||||||
|
- 检查网络连接
|
||||||
|
|
||||||
|
### 问题 2:钉钉/企业微信消息发送失败
|
||||||
|
**解决方案**:
|
||||||
|
- 检查 webhook 地址是否正确
|
||||||
|
- 检查签名配置(钉钉)
|
||||||
|
- 查看错误日志
|
||||||
|
|
||||||
|
### 问题 3:消息格式不正确
|
||||||
|
**解决方案**:
|
||||||
|
- 检查各平台的消息格式要求
|
||||||
|
- 调整消息构建逻辑
|
||||||
|
|
||||||
|
## 下一步
|
||||||
|
|
||||||
|
完成本任务后,继续 [任务 08:定时任务](./08-scheduler.md)。
|
||||||
@@ -0,0 +1,708 @@
|
|||||||
|
# 任务 08:定时任务调度
|
||||||
|
|
||||||
|
## 任务概述
|
||||||
|
实现定时任务调度服务,自动执行采集、报告生成、推送等任务。
|
||||||
|
|
||||||
|
## 前置条件
|
||||||
|
- 任务 01-07 已完成
|
||||||
|
- 采集器、报告生成、分发器已实现
|
||||||
|
|
||||||
|
## 任务目标
|
||||||
|
- 创建调度服务
|
||||||
|
- 实现采集任务调度
|
||||||
|
- 实现报告生成任务调度
|
||||||
|
- 支持动态更新调度任务
|
||||||
|
- 集成到应用启动流程
|
||||||
|
|
||||||
|
## 详细步骤
|
||||||
|
|
||||||
|
### 1. 创建调度服务
|
||||||
|
|
||||||
|
创建 `backend/src/services/scheduler.service.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import cron from 'node-cron'
|
||||||
|
import { CollectorService } from './collector.service'
|
||||||
|
import { ReportService } from './report.service'
|
||||||
|
import { DistributorService } from './distributor.service'
|
||||||
|
import prisma from '../utils/prisma'
|
||||||
|
import { logger } from '../utils/logger'
|
||||||
|
|
||||||
|
interface ScheduledTask {
|
||||||
|
id: string
|
||||||
|
type: 'collection' | 'report'
|
||||||
|
cronExpression: string
|
||||||
|
task: cron.ScheduledTask
|
||||||
|
resourceId: number // sourceId 或 topicId
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SchedulerService {
|
||||||
|
private tasks: Map<string, ScheduledTask> = new Map()
|
||||||
|
private collectorService: CollectorService
|
||||||
|
private reportService: ReportService
|
||||||
|
private distributorService: DistributorService
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.collectorService = new CollectorService()
|
||||||
|
this.reportService = new ReportService()
|
||||||
|
this.distributorService = new DistributorService()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 启动调度器
|
||||||
|
*/
|
||||||
|
async start(): Promise<void> {
|
||||||
|
logger.info('启动调度器...')
|
||||||
|
|
||||||
|
// 加载采集任务
|
||||||
|
await this.loadCollectionTasks()
|
||||||
|
|
||||||
|
// 加载报告生成任务
|
||||||
|
await this.loadReportTasks()
|
||||||
|
|
||||||
|
logger.info(`调度器启动完成,共 ${this.tasks.size} 个任务`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 停止调度器
|
||||||
|
*/
|
||||||
|
stop(): void {
|
||||||
|
logger.info('停止调度器...')
|
||||||
|
|
||||||
|
this.tasks.forEach((task) => {
|
||||||
|
task.task.stop()
|
||||||
|
})
|
||||||
|
|
||||||
|
this.tasks.clear()
|
||||||
|
|
||||||
|
logger.info('调度器已停止')
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 加载采集任务
|
||||||
|
*/
|
||||||
|
private async loadCollectionTasks(): Promise<void> {
|
||||||
|
const sources = await prisma.source.findMany({
|
||||||
|
where: { enabled: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
logger.info(`加载 ${sources.length} 个采集任务`)
|
||||||
|
|
||||||
|
for (const source of sources) {
|
||||||
|
this.scheduleCollectionTask(source.id, source.cronExpression)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 加载报告生成任务
|
||||||
|
*/
|
||||||
|
private async loadReportTasks(): Promise<void> {
|
||||||
|
const topics = await prisma.topic.findMany({
|
||||||
|
where: { enabled: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
logger.info(`加载 ${topics.length} 个报告生成任务`)
|
||||||
|
|
||||||
|
for (const topic of topics) {
|
||||||
|
const scheduleConfig = topic.scheduleConfig as any
|
||||||
|
if (scheduleConfig.cron) {
|
||||||
|
this.scheduleReportTask(topic.id, scheduleConfig.cron)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 调度采集任务
|
||||||
|
*/
|
||||||
|
scheduleCollectionTask(sourceId: number, cronExpression: string): void {
|
||||||
|
const taskId = `collection-${sourceId}`
|
||||||
|
|
||||||
|
// 如果任务已存在,先停止
|
||||||
|
if (this.tasks.has(taskId)) {
|
||||||
|
this.unscheduleTask(taskId)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证 cron 表达式
|
||||||
|
if (!cron.validate(cronExpression)) {
|
||||||
|
logger.error(`无效的 cron 表达式: ${cronExpression}`, { sourceId })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建定时任务
|
||||||
|
const task = cron.schedule(cronExpression, async () => {
|
||||||
|
logger.info(`执行采集任务: sourceId=${sourceId}`)
|
||||||
|
try {
|
||||||
|
await this.collectorService.collectSource(sourceId)
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('采集任务执行失败', { sourceId, error })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
this.tasks.set(taskId, {
|
||||||
|
id: taskId,
|
||||||
|
type: 'collection',
|
||||||
|
cronExpression,
|
||||||
|
task,
|
||||||
|
resourceId: sourceId,
|
||||||
|
})
|
||||||
|
|
||||||
|
logger.info(`采集任务已调度: sourceId=${sourceId}, cron=${cronExpression}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 调度报告生成任务
|
||||||
|
*/
|
||||||
|
scheduleReportTask(topicId: number, cronExpression: string): void {
|
||||||
|
const taskId = `report-${topicId}`
|
||||||
|
|
||||||
|
// 如果任务已存在,先停止
|
||||||
|
if (this.tasks.has(taskId)) {
|
||||||
|
this.unscheduleTask(taskId)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证 cron 表达式
|
||||||
|
if (!cron.validate(cronExpression)) {
|
||||||
|
logger.error(`无效的 cron 表达式: ${cronExpression}`, { topicId })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建定时任务
|
||||||
|
const task = cron.schedule(cronExpression, async () => {
|
||||||
|
logger.info(`执行报告生成任务: topicId=${topicId}`)
|
||||||
|
try {
|
||||||
|
// 生成报告
|
||||||
|
const reportId = await this.reportService.generateReportForTopic(topicId)
|
||||||
|
|
||||||
|
// 分发报告
|
||||||
|
await this.distributorService.distributeReportToAllChannels(reportId)
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('报告生成任务执行失败', { topicId, error })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
this.tasks.set(taskId, {
|
||||||
|
id: taskId,
|
||||||
|
type: 'report',
|
||||||
|
cronExpression,
|
||||||
|
task,
|
||||||
|
resourceId: topicId,
|
||||||
|
})
|
||||||
|
|
||||||
|
logger.info(`报告生成任务已调度: topicId=${topicId}, cron=${cronExpression}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消调度任务
|
||||||
|
*/
|
||||||
|
unscheduleTask(taskId: string): void {
|
||||||
|
const scheduledTask = this.tasks.get(taskId)
|
||||||
|
if (scheduledTask) {
|
||||||
|
scheduledTask.task.stop()
|
||||||
|
this.tasks.delete(taskId)
|
||||||
|
logger.info(`任务已取消: ${taskId}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 重新加载所有任务
|
||||||
|
*/
|
||||||
|
async reload(): Promise<void> {
|
||||||
|
logger.info('重新加载调度任务...')
|
||||||
|
|
||||||
|
// 停止所有任务
|
||||||
|
this.stop()
|
||||||
|
|
||||||
|
// 重新加载
|
||||||
|
await this.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取所有任务状态
|
||||||
|
*/
|
||||||
|
getTasksStatus(): Array<{
|
||||||
|
id: string
|
||||||
|
type: string
|
||||||
|
cronExpression: string
|
||||||
|
resourceId: number
|
||||||
|
}> {
|
||||||
|
return Array.from(this.tasks.values()).map((task) => ({
|
||||||
|
id: task.id,
|
||||||
|
type: task.type,
|
||||||
|
cronExpression: task.cronExpression,
|
||||||
|
resourceId: task.resourceId,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手动触发采集任务
|
||||||
|
*/
|
||||||
|
async triggerCollection(sourceId: number): Promise<void> {
|
||||||
|
logger.info(`手动触发采集任务: sourceId=${sourceId}`)
|
||||||
|
await this.collectorService.collectSource(sourceId)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手动触发报告生成任务
|
||||||
|
*/
|
||||||
|
async triggerReport(topicId: number): Promise<number> {
|
||||||
|
logger.info(`手动触发报告生成任务: topicId=${topicId}`)
|
||||||
|
const reportId = await this.reportService.generateReportForTopic(topicId)
|
||||||
|
await this.distributorService.distributeReportToAllChannels(reportId)
|
||||||
|
return reportId
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 更新应用入口
|
||||||
|
|
||||||
|
更新 `backend/src/app.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import Fastify from 'fastify'
|
||||||
|
import cors from '@fastify/cors'
|
||||||
|
import { config } from './config'
|
||||||
|
import { logger } from './utils/logger'
|
||||||
|
import { errorHandler } from './web/middleware/error-handler'
|
||||||
|
import { requestLogger } from './web/middleware/request-logger'
|
||||||
|
import { healthRoutes } from './web/routes/health'
|
||||||
|
import { SchedulerService } from './services/scheduler.service'
|
||||||
|
|
||||||
|
let schedulerService: SchedulerService | null = null
|
||||||
|
|
||||||
|
export async function createApp() {
|
||||||
|
const app = Fastify({
|
||||||
|
logger: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
// 注册 CORS
|
||||||
|
await app.register(cors, {
|
||||||
|
origin: config.cors.origin,
|
||||||
|
credentials: config.cors.credentials,
|
||||||
|
})
|
||||||
|
|
||||||
|
// 注册中间件
|
||||||
|
app.addHook('onRequest', requestLogger)
|
||||||
|
|
||||||
|
// 注册错误处理
|
||||||
|
app.setErrorHandler(errorHandler)
|
||||||
|
|
||||||
|
// 注册路由
|
||||||
|
await app.register(healthRoutes, { prefix: '/api' })
|
||||||
|
|
||||||
|
// 启动调度器
|
||||||
|
schedulerService = new SchedulerService()
|
||||||
|
await schedulerService.start()
|
||||||
|
|
||||||
|
// 优雅关闭
|
||||||
|
app.addHook('onClose', async () => {
|
||||||
|
logger.info('应用关闭中...')
|
||||||
|
if (schedulerService) {
|
||||||
|
schedulerService.stop()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return app
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function startServer() {
|
||||||
|
try {
|
||||||
|
const app = await createApp()
|
||||||
|
|
||||||
|
await app.listen({
|
||||||
|
port: config.app.port,
|
||||||
|
host: config.app.host,
|
||||||
|
})
|
||||||
|
|
||||||
|
logger.info(`Server started on http://${config.app.host}:${config.app.port}`)
|
||||||
|
logger.info(`Environment: ${config.app.env}`)
|
||||||
|
|
||||||
|
// 处理进程信号
|
||||||
|
const signals = ['SIGINT', 'SIGTERM']
|
||||||
|
signals.forEach((signal) => {
|
||||||
|
process.on(signal, async () => {
|
||||||
|
logger.info(`收到 ${signal} 信号,准备关闭...`)
|
||||||
|
await app.close()
|
||||||
|
process.exit(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Failed to start server', error)
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果直接运行此文件,则启动服务器
|
||||||
|
if (require.main === module) {
|
||||||
|
startServer()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 导出调度器实例供其他模块使用
|
||||||
|
export function getScheduler(): SchedulerService | null {
|
||||||
|
return schedulerService
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 更新服务导出
|
||||||
|
|
||||||
|
更新 `backend/src/services/index.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export * from './collector.service'
|
||||||
|
export * from './processor.service'
|
||||||
|
export * from './report.service'
|
||||||
|
export * from './distributor.service'
|
||||||
|
export * from './scheduler.service'
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 创建测试脚本
|
||||||
|
|
||||||
|
创建 `backend/src/test-scheduler.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { SchedulerService } from './services/scheduler.service'
|
||||||
|
import { logger } from './utils/logger'
|
||||||
|
|
||||||
|
async function test() {
|
||||||
|
const scheduler = new SchedulerService()
|
||||||
|
|
||||||
|
// 启动调度器
|
||||||
|
await scheduler.start()
|
||||||
|
|
||||||
|
// 查看任务状态
|
||||||
|
console.log('\n=== 调度任务状态 ===')
|
||||||
|
const tasks = scheduler.getTasksStatus()
|
||||||
|
tasks.forEach((task) => {
|
||||||
|
console.log(`- [${task.type}] ${task.id}: ${task.cronExpression}`)
|
||||||
|
})
|
||||||
|
|
||||||
|
// 测试手动触发
|
||||||
|
console.log('\n=== 测试手动触发 ===')
|
||||||
|
|
||||||
|
// 手动触发采集
|
||||||
|
const collectionTask = tasks.find((t) => t.type === 'collection')
|
||||||
|
if (collectionTask) {
|
||||||
|
console.log(`手动触发采集: sourceId=${collectionTask.resourceId}`)
|
||||||
|
await scheduler.triggerCollection(collectionTask.resourceId)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 手动触发报告生成
|
||||||
|
const reportTask = tasks.find((t) => t.type === 'report')
|
||||||
|
if (reportTask) {
|
||||||
|
console.log(`手动触发报告生成: topicId=${reportTask.resourceId}`)
|
||||||
|
const reportId = await scheduler.triggerReport(reportTask.resourceId)
|
||||||
|
console.log(`报告生成完成: reportId=${reportId}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 保持运行一段时间以观察定时任务
|
||||||
|
console.log('\n调度器将运行 60 秒,观察定时任务执行情况...')
|
||||||
|
console.log('按 Ctrl+C 停止')
|
||||||
|
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 60000))
|
||||||
|
|
||||||
|
// 停止调度器
|
||||||
|
scheduler.stop()
|
||||||
|
}
|
||||||
|
|
||||||
|
test().catch((error) => {
|
||||||
|
logger.error('测试失败', error)
|
||||||
|
process.exit(1)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 创建调度管理脚本
|
||||||
|
|
||||||
|
创建 `backend/src/scripts/scheduler-cli.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { SchedulerService } from '../services/scheduler.service'
|
||||||
|
import { logger } from '../utils/logger'
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const args = process.argv.slice(2)
|
||||||
|
const command = args[0]
|
||||||
|
|
||||||
|
const scheduler = new SchedulerService()
|
||||||
|
|
||||||
|
switch (command) {
|
||||||
|
case 'start':
|
||||||
|
logger.info('启动调度器(前台运行)')
|
||||||
|
await scheduler.start()
|
||||||
|
logger.info('调度器运行中,按 Ctrl+C 停止')
|
||||||
|
// 保持运行
|
||||||
|
await new Promise(() => {})
|
||||||
|
break
|
||||||
|
|
||||||
|
case 'status':
|
||||||
|
await scheduler.start()
|
||||||
|
const tasks = scheduler.getTasksStatus()
|
||||||
|
console.log(`\n共 ${tasks.length} 个调度任务:\n`)
|
||||||
|
tasks.forEach((task) => {
|
||||||
|
console.log(`[${task.type}] ${task.id}`)
|
||||||
|
console.log(` Cron: ${task.cronExpression}`)
|
||||||
|
console.log(` Resource ID: ${task.resourceId}`)
|
||||||
|
console.log()
|
||||||
|
})
|
||||||
|
scheduler.stop()
|
||||||
|
break
|
||||||
|
|
||||||
|
case 'trigger-collection':
|
||||||
|
const sourceId = parseInt(args[1], 10)
|
||||||
|
if (isNaN(sourceId)) {
|
||||||
|
console.error('用法: tsx src/scripts/scheduler-cli.ts trigger-collection <sourceId>')
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
await scheduler.start()
|
||||||
|
await scheduler.triggerCollection(sourceId)
|
||||||
|
scheduler.stop()
|
||||||
|
break
|
||||||
|
|
||||||
|
case 'trigger-report':
|
||||||
|
const topicId = parseInt(args[1], 10)
|
||||||
|
if (isNaN(topicId)) {
|
||||||
|
console.error('用法: tsx src/scripts/scheduler-cli.ts trigger-report <topicId>')
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
await scheduler.start()
|
||||||
|
const reportId = await scheduler.triggerReport(topicId)
|
||||||
|
logger.info(`报告生成完成: ${reportId}`)
|
||||||
|
scheduler.stop()
|
||||||
|
break
|
||||||
|
|
||||||
|
default:
|
||||||
|
console.log(`
|
||||||
|
News Aggregator 调度器管理工具
|
||||||
|
|
||||||
|
用法:
|
||||||
|
tsx src/scripts/scheduler-cli.ts <command> [options]
|
||||||
|
|
||||||
|
命令:
|
||||||
|
start 启动调度器(前台运行)
|
||||||
|
status 查看调度任务状态
|
||||||
|
trigger-collection <sourceId> 手动触发采集任务
|
||||||
|
trigger-report <topicId> 手动触发报告生成任务
|
||||||
|
|
||||||
|
示例:
|
||||||
|
tsx src/scripts/scheduler-cli.ts start
|
||||||
|
tsx src/scripts/scheduler-cli.ts status
|
||||||
|
tsx src/scripts/scheduler-cli.ts trigger-collection 1
|
||||||
|
tsx src/scripts/scheduler-cli.ts trigger-report 1
|
||||||
|
`)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
.catch((error) => {
|
||||||
|
logger.error('命令执行失败', error)
|
||||||
|
process.exit(1)
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
process.exit(0)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6. 更新 package.json
|
||||||
|
|
||||||
|
更新 `backend/package.json`,添加调度器相关脚本:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"scripts": {
|
||||||
|
"dev": "tsx watch src/app.ts",
|
||||||
|
"build": "tsc",
|
||||||
|
"start": "node dist/app.js",
|
||||||
|
"scheduler:start": "tsx src/scripts/scheduler-cli.ts start",
|
||||||
|
"scheduler:status": "tsx src/scripts/scheduler-cli.ts status",
|
||||||
|
"prisma:generate": "prisma generate",
|
||||||
|
"prisma:migrate": "prisma migrate dev",
|
||||||
|
"prisma:studio": "prisma studio",
|
||||||
|
"prisma:seed": "tsx prisma/seed.ts"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7. 创建 PM2 配置文件
|
||||||
|
|
||||||
|
创建 `backend/ecosystem.config.js`:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
module.exports = {
|
||||||
|
apps: [
|
||||||
|
{
|
||||||
|
name: 'news-aggregator',
|
||||||
|
script: './dist/app.js',
|
||||||
|
instances: 1,
|
||||||
|
exec_mode: 'fork',
|
||||||
|
env: {
|
||||||
|
NODE_ENV: 'production',
|
||||||
|
},
|
||||||
|
error_file: './logs/error.log',
|
||||||
|
out_file: './logs/out.log',
|
||||||
|
log_date_format: 'YYYY-MM-DD HH:mm:ss',
|
||||||
|
merge_logs: true,
|
||||||
|
autorestart: true,
|
||||||
|
max_restarts: 10,
|
||||||
|
min_uptime: '10s',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 验证步骤
|
||||||
|
|
||||||
|
### 1. 测试调度器启动
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
npx tsx src/test-scheduler.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
预期输出:
|
||||||
|
```
|
||||||
|
[INFO] 启动调度器...
|
||||||
|
[INFO] 加载 1 个采集任务
|
||||||
|
[INFO] 采集任务已调度: sourceId=1, cron=0 */6 * * *
|
||||||
|
[INFO] 加载 1 个报告生成任务
|
||||||
|
[INFO] 报告生成任务已调度: topicId=1, cron=0 9 * * *
|
||||||
|
[INFO] 调度器启动完成,共 2 个任务
|
||||||
|
|
||||||
|
=== 调度任务状态 ===
|
||||||
|
- [collection] collection-1: 0 */6 * * *
|
||||||
|
- [report] report-1: 0 9 * * *
|
||||||
|
|
||||||
|
=== 测试手动触发 ===
|
||||||
|
手动触发采集: sourceId=1
|
||||||
|
[INFO] 手动触发采集任务: sourceId=1
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 测试调度器命令行工具
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 查看状态
|
||||||
|
npm run scheduler:status
|
||||||
|
|
||||||
|
# 手动触发采集
|
||||||
|
npx tsx src/scripts/scheduler-cli.ts trigger-collection 1
|
||||||
|
|
||||||
|
# 手动触发报告生成
|
||||||
|
npx tsx src/scripts/scheduler-cli.ts trigger-report 1
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 测试应用启动
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
应该看到:
|
||||||
|
```
|
||||||
|
[INFO] 启动调度器...
|
||||||
|
[INFO] 加载 1 个采集任务
|
||||||
|
[INFO] 加载 1 个报告生成任务
|
||||||
|
[INFO] 调度器启动完成,共 2 个任务
|
||||||
|
[INFO] Server started on http://0.0.0.0:3000
|
||||||
|
[INFO] Environment: development
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 测试定时任务执行
|
||||||
|
|
||||||
|
修改数据源的 cron 表达式为每分钟执行一次:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run prisma:studio
|
||||||
|
```
|
||||||
|
|
||||||
|
在 `sources` 表中,将 `cron_expression` 改为 `* * * * *`(每分钟)。
|
||||||
|
|
||||||
|
重启应用,观察日志,应该每分钟看到采集任务执行。
|
||||||
|
|
||||||
|
### 5. 测试优雅关闭
|
||||||
|
|
||||||
|
启动应用后,按 `Ctrl+C`,应该看到:
|
||||||
|
|
||||||
|
```
|
||||||
|
[INFO] 收到 SIGINT 信号,准备关闭...
|
||||||
|
[INFO] 应用关闭中...
|
||||||
|
[INFO] 停止调度器...
|
||||||
|
[INFO] 调度器已停止
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6. 测试 PM2 部署
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 构建
|
||||||
|
npm run build
|
||||||
|
|
||||||
|
# 创建日志目录
|
||||||
|
mkdir -p logs
|
||||||
|
|
||||||
|
# 使用 PM2 启动
|
||||||
|
pm2 start ecosystem.config.js
|
||||||
|
|
||||||
|
# 查看状态
|
||||||
|
pm2 status
|
||||||
|
|
||||||
|
# 查看日志
|
||||||
|
pm2 logs news-aggregator
|
||||||
|
|
||||||
|
# 停止
|
||||||
|
pm2 stop news-aggregator
|
||||||
|
|
||||||
|
# 删除
|
||||||
|
pm2 delete news-aggregator
|
||||||
|
```
|
||||||
|
|
||||||
|
## 预期产物
|
||||||
|
|
||||||
|
- ✅ 调度服务实现完成
|
||||||
|
- ✅ 采集任务调度完成
|
||||||
|
- ✅ 报告生成任务调度完成
|
||||||
|
- ✅ 手动触发功能完成
|
||||||
|
- ✅ 调度器集成到应用完成
|
||||||
|
- ✅ 命令行工具完成
|
||||||
|
- ✅ PM2 配置完成
|
||||||
|
- ✅ 优雅关闭实现完成
|
||||||
|
- ✅ 测试通过
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
### 问题 1:定时任务不执行
|
||||||
|
**解决方案**:
|
||||||
|
- 检查 cron 表达式是否正确
|
||||||
|
- 检查数据源/主题是否启用
|
||||||
|
- 查看日志是否有错误
|
||||||
|
|
||||||
|
### 问题 2:应用无法优雅关闭
|
||||||
|
**解决方案**:
|
||||||
|
- 检查信号处理是否正确
|
||||||
|
- 确保所有异步任务都能正常结束
|
||||||
|
|
||||||
|
### 问题 3:PM2 启动失败
|
||||||
|
**解决方案**:
|
||||||
|
- 检查构建是否成功
|
||||||
|
- 检查环境变量是否配置
|
||||||
|
- 查看 PM2 日志
|
||||||
|
|
||||||
|
## Cron 表达式参考
|
||||||
|
|
||||||
|
```
|
||||||
|
* * * * *
|
||||||
|
│ │ │ │ │
|
||||||
|
│ │ │ │ └─ 星期几 (0-7, 0和7都表示周日)
|
||||||
|
│ │ │ └─── 月份 (1-12)
|
||||||
|
│ │ └───── 日期 (1-31)
|
||||||
|
│ └─────── 小时 (0-23)
|
||||||
|
└───────── 分钟 (0-59)
|
||||||
|
|
||||||
|
示例:
|
||||||
|
0 9 * * * 每天 9:00
|
||||||
|
0 */6 * * * 每 6 小时
|
||||||
|
*/30 * * * * 每 30 分钟
|
||||||
|
0 0 * * 0 每周日 0:00
|
||||||
|
0 0 1 * * 每月 1 号 0:00
|
||||||
|
```
|
||||||
|
|
||||||
|
## 下一步
|
||||||
|
|
||||||
|
完成本任务后,继续 [任务 09:Web API](./09-web-api.md)。
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,960 @@
|
|||||||
|
# 任务 10:前端项目初始化
|
||||||
|
|
||||||
|
## 任务概述
|
||||||
|
初始化 Vue 3 前端项目,配置路由、状态管理、UI 组件库等基础设施。
|
||||||
|
|
||||||
|
## 前置条件
|
||||||
|
- 任务 01-09 已完成
|
||||||
|
- 后端 API 已实现
|
||||||
|
|
||||||
|
## 任务目标
|
||||||
|
- 配置 Vue Router
|
||||||
|
- 配置 Pinia 状态管理
|
||||||
|
- 配置 Element Plus
|
||||||
|
- 创建基础布局
|
||||||
|
- 配置 API 请求
|
||||||
|
- 实现登录页面(预留)
|
||||||
|
|
||||||
|
## 详细步骤
|
||||||
|
|
||||||
|
### 1. 配置路由
|
||||||
|
|
||||||
|
创建 `frontend/src/router/index.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { createRouter, createWebHistory } from 'vue-router'
|
||||||
|
import type { RouteRecordRaw } from 'vue-router'
|
||||||
|
|
||||||
|
const routes: RouteRecordRaw[] = [
|
||||||
|
{
|
||||||
|
path: '/',
|
||||||
|
redirect: '/dashboard',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/dashboard',
|
||||||
|
name: 'Dashboard',
|
||||||
|
component: () => import('@/views/Dashboard.vue'),
|
||||||
|
meta: { title: '仪表盘' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/config',
|
||||||
|
name: 'Config',
|
||||||
|
redirect: '/config/llm',
|
||||||
|
meta: { title: '配置管理' },
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
path: 'llm',
|
||||||
|
name: 'LlmConfig',
|
||||||
|
component: () => import('@/views/config/LlmConfig.vue'),
|
||||||
|
meta: { title: 'LLM 配置' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'sources',
|
||||||
|
name: 'Sources',
|
||||||
|
component: () => import('@/views/config/Sources.vue'),
|
||||||
|
meta: { title: '数据源管理' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'channels',
|
||||||
|
name: 'Channels',
|
||||||
|
component: () => import('@/views/config/Channels.vue'),
|
||||||
|
meta: { title: '推送渠道' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'topics',
|
||||||
|
name: 'Topics',
|
||||||
|
component: () => import('@/views/config/Topics.vue'),
|
||||||
|
meta: { title: '主题管理' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/reports',
|
||||||
|
name: 'Reports',
|
||||||
|
component: () => import('@/views/reports/ReportList.vue'),
|
||||||
|
meta: { title: '报告中心' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/reports/:id',
|
||||||
|
name: 'ReportDetail',
|
||||||
|
component: () => import('@/views/reports/ReportDetail.vue'),
|
||||||
|
meta: { title: '报告详情' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/articles',
|
||||||
|
name: 'Articles',
|
||||||
|
component: () => import('@/views/articles/ArticleList.vue'),
|
||||||
|
meta: { title: '资讯浏览' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/monitoring',
|
||||||
|
name: 'Monitoring',
|
||||||
|
component: () => import('@/views/monitoring/Monitoring.vue'),
|
||||||
|
meta: { title: '采集监控' },
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
const router = createRouter({
|
||||||
|
history: createWebHistory(),
|
||||||
|
routes,
|
||||||
|
})
|
||||||
|
|
||||||
|
// 路由守卫
|
||||||
|
router.beforeEach((to, from, next) => {
|
||||||
|
// 设置页面标题
|
||||||
|
if (to.meta.title) {
|
||||||
|
document.title = `${to.meta.title} - News Aggregator`
|
||||||
|
}
|
||||||
|
next()
|
||||||
|
})
|
||||||
|
|
||||||
|
export default router
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 配置 Pinia 状态管理
|
||||||
|
|
||||||
|
创建 `frontend/src/stores/app.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { ref } from 'vue'
|
||||||
|
|
||||||
|
export const useAppStore = defineStore('app', () => {
|
||||||
|
// 侧边栏折叠状态
|
||||||
|
const sidebarCollapsed = ref(false)
|
||||||
|
|
||||||
|
// 切换侧边栏
|
||||||
|
const toggleSidebar = () => {
|
||||||
|
sidebarCollapsed.value = !sidebarCollapsed.value
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
sidebarCollapsed,
|
||||||
|
toggleSidebar,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
创建 `frontend/src/stores/user.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { ref } from 'vue'
|
||||||
|
|
||||||
|
export const useUserStore = defineStore('user', () => {
|
||||||
|
const token = ref<string | null>(null)
|
||||||
|
const userInfo = ref<any>(null)
|
||||||
|
|
||||||
|
const setToken = (newToken: string) => {
|
||||||
|
token.value = newToken
|
||||||
|
localStorage.setItem('token', newToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
const setUserInfo = (info: any) => {
|
||||||
|
userInfo.value = info
|
||||||
|
}
|
||||||
|
|
||||||
|
const logout = () => {
|
||||||
|
token.value = null
|
||||||
|
userInfo.value = null
|
||||||
|
localStorage.removeItem('token')
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化时从 localStorage 恢复 token
|
||||||
|
const initToken = () => {
|
||||||
|
const savedToken = localStorage.getItem('token')
|
||||||
|
if (savedToken) {
|
||||||
|
token.value = savedToken
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
token,
|
||||||
|
userInfo,
|
||||||
|
setToken,
|
||||||
|
setUserInfo,
|
||||||
|
logout,
|
||||||
|
initToken,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 配置 API 请求
|
||||||
|
|
||||||
|
创建 `frontend/src/api/request.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import axios from 'axios'
|
||||||
|
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
import { useUserStore } from '@/stores/user'
|
||||||
|
|
||||||
|
// 创建 axios 实例
|
||||||
|
const service: AxiosInstance = axios.create({
|
||||||
|
baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
|
||||||
|
timeout: 30000,
|
||||||
|
})
|
||||||
|
|
||||||
|
// 请求拦截器
|
||||||
|
service.interceptors.request.use(
|
||||||
|
(config) => {
|
||||||
|
const userStore = useUserStore()
|
||||||
|
if (userStore.token) {
|
||||||
|
config.headers.Authorization = `Bearer ${userStore.token}`
|
||||||
|
}
|
||||||
|
return config
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
console.error('Request error:', error)
|
||||||
|
return Promise.reject(error)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// 响应拦截器
|
||||||
|
service.interceptors.response.use(
|
||||||
|
(response: AxiosResponse) => {
|
||||||
|
const res = response.data
|
||||||
|
|
||||||
|
// 如果响应格式不是标准格式,直接返回
|
||||||
|
if (res.success === undefined) {
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理业务错误
|
||||||
|
if (!res.success) {
|
||||||
|
ElMessage.error(res.error?.message || '请求失败')
|
||||||
|
return Promise.reject(new Error(res.error?.message || '请求失败'))
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.data
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
console.error('Response error:', error)
|
||||||
|
|
||||||
|
// 处理 HTTP 错误
|
||||||
|
if (error.response) {
|
||||||
|
const status = error.response.status
|
||||||
|
switch (status) {
|
||||||
|
case 401:
|
||||||
|
ElMessage.error('未授权,请登录')
|
||||||
|
// 跳转到登录页
|
||||||
|
break
|
||||||
|
case 403:
|
||||||
|
ElMessage.error('拒绝访问')
|
||||||
|
break
|
||||||
|
case 404:
|
||||||
|
ElMessage.error('请求的资源不存在')
|
||||||
|
break
|
||||||
|
case 500:
|
||||||
|
ElMessage.error('服务器错误')
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
ElMessage.error(error.response.data?.error?.message || '请求失败')
|
||||||
|
}
|
||||||
|
} else if (error.request) {
|
||||||
|
ElMessage.error('网络错误,请检查网络连接')
|
||||||
|
} else {
|
||||||
|
ElMessage.error('请求配置错误')
|
||||||
|
}
|
||||||
|
|
||||||
|
return Promise.reject(error)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
export default service
|
||||||
|
```
|
||||||
|
|
||||||
|
创建 `frontend/src/api/types.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// 分页参数
|
||||||
|
export interface PaginationParams {
|
||||||
|
page?: number
|
||||||
|
limit?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
// 分页响应
|
||||||
|
export interface PaginatedResponse<T> {
|
||||||
|
items: T[]
|
||||||
|
total: number
|
||||||
|
page: number
|
||||||
|
limit: number
|
||||||
|
totalPages: number
|
||||||
|
}
|
||||||
|
|
||||||
|
// LLM 配置
|
||||||
|
export interface LlmConfig {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
baseUrl: string
|
||||||
|
model: string
|
||||||
|
apiKey: string
|
||||||
|
enabled: boolean
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// 数据源
|
||||||
|
export interface Source {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
type: 'api' | 'playwright' | 'rss'
|
||||||
|
config: any
|
||||||
|
cronExpression: string
|
||||||
|
enabled: boolean
|
||||||
|
lastCollectedAt: string | null
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// 推送渠道
|
||||||
|
export interface Channel {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
type: 'email' | 'dingtalk' | 'wechat' | 'slack'
|
||||||
|
config: any
|
||||||
|
enabled: boolean
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// 主题
|
||||||
|
export interface Topic {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
description: string | null
|
||||||
|
processMode: 'aggregate' | 'summary' | 'deep_analysis'
|
||||||
|
llmConfigId: number | null
|
||||||
|
scheduleConfig: any
|
||||||
|
enabled: boolean
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
llmConfig?: LlmConfig
|
||||||
|
topicSources?: Array<{ source: Source }>
|
||||||
|
topicChannels?: Array<{ channel: Channel }>
|
||||||
|
}
|
||||||
|
|
||||||
|
// 报告
|
||||||
|
export interface Report {
|
||||||
|
id: number
|
||||||
|
topicId: number
|
||||||
|
title: string
|
||||||
|
content: string
|
||||||
|
periodStart: string
|
||||||
|
periodEnd: string
|
||||||
|
status: 'pending' | 'generating' | 'completed' | 'failed'
|
||||||
|
errorMessage: string | null
|
||||||
|
articleCount: number
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
topic?: Topic
|
||||||
|
}
|
||||||
|
|
||||||
|
// 资讯
|
||||||
|
export interface Article {
|
||||||
|
id: number
|
||||||
|
sourceId: number
|
||||||
|
title: string
|
||||||
|
content: string | null
|
||||||
|
summary: string | null
|
||||||
|
url: string | null
|
||||||
|
publishedAt: string | null
|
||||||
|
collectedAt: string
|
||||||
|
createdAt: string
|
||||||
|
source?: Source
|
||||||
|
}
|
||||||
|
|
||||||
|
// 采集日志
|
||||||
|
export interface CollectionLog {
|
||||||
|
id: number
|
||||||
|
sourceId: number
|
||||||
|
status: 'success' | 'failed'
|
||||||
|
errorMessage: string | null
|
||||||
|
articlesCount: number
|
||||||
|
startedAt: string
|
||||||
|
finishedAt: string | null
|
||||||
|
durationMs: number | null
|
||||||
|
createdAt: string
|
||||||
|
source?: Source
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 创建基础布局
|
||||||
|
|
||||||
|
创建 `frontend/src/layouts/MainLayout.vue`:
|
||||||
|
|
||||||
|
```vue
|
||||||
|
<template>
|
||||||
|
<el-container class="main-layout">
|
||||||
|
<!-- 侧边栏 -->
|
||||||
|
<el-aside :width="sidebarWidth">
|
||||||
|
<div class="logo">
|
||||||
|
<h2 v-if="!appStore.sidebarCollapsed">News Aggregator</h2>
|
||||||
|
<h2 v-else>NA</h2>
|
||||||
|
</div>
|
||||||
|
<el-menu
|
||||||
|
:default-active="activeMenu"
|
||||||
|
:collapse="appStore.sidebarCollapsed"
|
||||||
|
router
|
||||||
|
>
|
||||||
|
<el-menu-item index="/dashboard">
|
||||||
|
<el-icon><HomeFilled /></el-icon>
|
||||||
|
<template #title>仪表盘</template>
|
||||||
|
</el-menu-item>
|
||||||
|
|
||||||
|
<el-sub-menu index="/config">
|
||||||
|
<template #title>
|
||||||
|
<el-icon><Setting /></el-icon>
|
||||||
|
<span>配置管理</span>
|
||||||
|
</template>
|
||||||
|
<el-menu-item index="/config/llm">LLM 配置</el-menu-item>
|
||||||
|
<el-menu-item index="/config/sources">数据源</el-menu-item>
|
||||||
|
<el-menu-item index="/config/channels">推送渠道</el-menu-item>
|
||||||
|
<el-menu-item index="/config/topics">主题</el-menu-item>
|
||||||
|
</el-sub-menu>
|
||||||
|
|
||||||
|
<el-menu-item index="/reports">
|
||||||
|
<el-icon><Document /></el-icon>
|
||||||
|
<template #title>报告中心</template>
|
||||||
|
</el-menu-item>
|
||||||
|
|
||||||
|
<el-menu-item index="/articles">
|
||||||
|
<el-icon><Reading /></el-icon>
|
||||||
|
<template #title>资讯浏览</template>
|
||||||
|
</el-menu-item>
|
||||||
|
|
||||||
|
<el-menu-item index="/monitoring">
|
||||||
|
<el-icon><Monitor /></el-icon>
|
||||||
|
<template #title>采集监控</template>
|
||||||
|
</el-menu-item>
|
||||||
|
</el-menu>
|
||||||
|
</el-aside>
|
||||||
|
|
||||||
|
<!-- 主内容区 -->
|
||||||
|
<el-container>
|
||||||
|
<!-- 顶部栏 -->
|
||||||
|
<el-header>
|
||||||
|
<div class="header-left">
|
||||||
|
<el-button
|
||||||
|
:icon="appStore.sidebarCollapsed ? Expand : Fold"
|
||||||
|
@click="appStore.toggleSidebar"
|
||||||
|
/>
|
||||||
|
<el-breadcrumb separator="/">
|
||||||
|
<el-breadcrumb-item
|
||||||
|
v-for="item in breadcrumbs"
|
||||||
|
:key="item.path"
|
||||||
|
:to="item.path"
|
||||||
|
>
|
||||||
|
{{ item.title }}
|
||||||
|
</el-breadcrumb-item>
|
||||||
|
</el-breadcrumb>
|
||||||
|
</div>
|
||||||
|
<div class="header-right">
|
||||||
|
<!-- 预留用户信息 -->
|
||||||
|
</div>
|
||||||
|
</el-header>
|
||||||
|
|
||||||
|
<!-- 内容区 -->
|
||||||
|
<el-main>
|
||||||
|
<router-view />
|
||||||
|
</el-main>
|
||||||
|
</el-container>
|
||||||
|
</el-container>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import { useRoute } from 'vue-router'
|
||||||
|
import { useAppStore } from '@/stores/app'
|
||||||
|
import {
|
||||||
|
HomeFilled,
|
||||||
|
Setting,
|
||||||
|
Document,
|
||||||
|
Reading,
|
||||||
|
Monitor,
|
||||||
|
Expand,
|
||||||
|
Fold,
|
||||||
|
} from '@element-plus/icons-vue'
|
||||||
|
|
||||||
|
const route = useRoute()
|
||||||
|
const appStore = useAppStore()
|
||||||
|
|
||||||
|
const sidebarWidth = computed(() => {
|
||||||
|
return appStore.sidebarCollapsed ? '64px' : '200px'
|
||||||
|
})
|
||||||
|
|
||||||
|
const activeMenu = computed(() => {
|
||||||
|
return route.path
|
||||||
|
})
|
||||||
|
|
||||||
|
const breadcrumbs = computed(() => {
|
||||||
|
const matched = route.matched.filter((item) => item.meta?.title)
|
||||||
|
return matched.map((item) => ({
|
||||||
|
path: item.path,
|
||||||
|
title: item.meta.title as string,
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.main-layout {
|
||||||
|
height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
.el-aside {
|
||||||
|
background-color: #304156;
|
||||||
|
transition: width 0.3s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.logo {
|
||||||
|
height: 60px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
color: #fff;
|
||||||
|
font-size: 20px;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.el-menu {
|
||||||
|
border-right: none;
|
||||||
|
background-color: #304156;
|
||||||
|
}
|
||||||
|
|
||||||
|
.el-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
background-color: #fff;
|
||||||
|
border-bottom: 1px solid #e6e6e6;
|
||||||
|
padding: 0 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-left {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.el-main {
|
||||||
|
background-color: #f0f2f5;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 创建仪表盘页面
|
||||||
|
|
||||||
|
创建 `frontend/src/views/Dashboard.vue`:
|
||||||
|
|
||||||
|
```vue
|
||||||
|
<template>
|
||||||
|
<div class="dashboard">
|
||||||
|
<el-row :gutter="20">
|
||||||
|
<el-col :span="6">
|
||||||
|
<el-card>
|
||||||
|
<template #header>
|
||||||
|
<div class="card-header">
|
||||||
|
<span>数据源</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<div class="stat-item">
|
||||||
|
<div class="stat-value">{{ stats.sources }}</div>
|
||||||
|
<div class="stat-label">总数</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
|
||||||
|
<el-col :span="6">
|
||||||
|
<el-card>
|
||||||
|
<template #header>
|
||||||
|
<div class="card-header">
|
||||||
|
<span>主题</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<div class="stat-item">
|
||||||
|
<div class="stat-value">{{ stats.topics }}</div>
|
||||||
|
<div class="stat-label">总数</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
|
||||||
|
<el-col :span="6">
|
||||||
|
<el-card>
|
||||||
|
<template #header>
|
||||||
|
<div class="card-header">
|
||||||
|
<span>报告</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<div class="stat-item">
|
||||||
|
<div class="stat-value">{{ stats.reports }}</div>
|
||||||
|
<div class="stat-label">总数</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
|
||||||
|
<el-col :span="6">
|
||||||
|
<el-card>
|
||||||
|
<template #header>
|
||||||
|
<div class="card-header">
|
||||||
|
<span>资讯</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<div class="stat-item">
|
||||||
|
<div class="stat-value">{{ stats.articles }}</div>
|
||||||
|
<div class="stat-label">总数</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
|
||||||
|
<el-row :gutter="20" style="margin-top: 20px">
|
||||||
|
<el-col :span="12">
|
||||||
|
<el-card>
|
||||||
|
<template #header>
|
||||||
|
<div class="card-header">
|
||||||
|
<span>最近报告</span>
|
||||||
|
<el-button type="primary" link @click="$router.push('/reports')">
|
||||||
|
查看更多
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<el-empty v-if="recentReports.length === 0" description="暂无报告" />
|
||||||
|
<div v-else class="report-list">
|
||||||
|
<div
|
||||||
|
v-for="report in recentReports"
|
||||||
|
:key="report.id"
|
||||||
|
class="report-item"
|
||||||
|
@click="$router.push(`/reports/${report.id}`)"
|
||||||
|
>
|
||||||
|
<div class="report-title">{{ report.title }}</div>
|
||||||
|
<div class="report-meta">
|
||||||
|
<el-tag :type="getStatusType(report.status)" size="small">
|
||||||
|
{{ getStatusText(report.status) }}
|
||||||
|
</el-tag>
|
||||||
|
<span class="report-time">
|
||||||
|
{{ formatTime(report.createdAt) }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
|
||||||
|
<el-col :span="12">
|
||||||
|
<el-card>
|
||||||
|
<template #header>
|
||||||
|
<div class="card-header">
|
||||||
|
<span>采集状态</span>
|
||||||
|
<el-button type="primary" link @click="$router.push('/monitoring')">
|
||||||
|
查看详情
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<el-empty v-if="collectionStats.length === 0" description="暂无数据" />
|
||||||
|
<div v-else class="collection-list">
|
||||||
|
<div
|
||||||
|
v-for="stat in collectionStats"
|
||||||
|
:key="stat.id"
|
||||||
|
class="collection-item"
|
||||||
|
>
|
||||||
|
<div class="collection-name">{{ stat.name }}</div>
|
||||||
|
<div class="collection-meta">
|
||||||
|
<el-tag
|
||||||
|
:type="stat.lastLog?.status === 'success' ? 'success' : 'danger'"
|
||||||
|
size="small"
|
||||||
|
>
|
||||||
|
{{ stat.lastLog?.status === 'success' ? '成功' : '失败' }}
|
||||||
|
</el-tag>
|
||||||
|
<span class="collection-time">
|
||||||
|
{{ formatTime(stat.lastCollectedAt) }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, onMounted } from 'vue'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
import request from '@/api/request'
|
||||||
|
import type { Report } from '@/api/types'
|
||||||
|
|
||||||
|
const stats = ref({
|
||||||
|
sources: 0,
|
||||||
|
topics: 0,
|
||||||
|
reports: 0,
|
||||||
|
articles: 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
const recentReports = ref<Report[]>([])
|
||||||
|
const collectionStats = ref<any[]>([])
|
||||||
|
|
||||||
|
const loadStats = async () => {
|
||||||
|
try {
|
||||||
|
const [sourcesRes, topicsRes, reportsRes, articlesRes] = await Promise.all([
|
||||||
|
request.get('/sources', { params: { limit: 1 } }),
|
||||||
|
request.get('/topics', { params: { limit: 1 } }),
|
||||||
|
request.get('/reports', { params: { limit: 1 } }),
|
||||||
|
request.get('/articles', { params: { limit: 1 } }),
|
||||||
|
])
|
||||||
|
|
||||||
|
stats.value = {
|
||||||
|
sources: sourcesRes.total || 0,
|
||||||
|
topics: topicsRes.total || 0,
|
||||||
|
reports: reportsRes.total || 0,
|
||||||
|
articles: articlesRes.total || 0,
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
ElMessage.error('加载统计数据失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadRecentReports = async () => {
|
||||||
|
try {
|
||||||
|
const res = await request.get('/reports', { params: { limit: 5 } })
|
||||||
|
recentReports.value = res.items || []
|
||||||
|
} catch (error) {
|
||||||
|
ElMessage.error('加载最近报告失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadCollectionStats = async () => {
|
||||||
|
try {
|
||||||
|
const res = await request.get('/collection-logs/stats')
|
||||||
|
collectionStats.value = res.slice(0, 5)
|
||||||
|
} catch (error) {
|
||||||
|
ElMessage.error('加载采集状态失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const getStatusType = (status: string) => {
|
||||||
|
const map: Record<string, any> = {
|
||||||
|
pending: 'info',
|
||||||
|
generating: 'warning',
|
||||||
|
completed: 'success',
|
||||||
|
failed: 'danger',
|
||||||
|
}
|
||||||
|
return map[status] || 'info'
|
||||||
|
}
|
||||||
|
|
||||||
|
const getStatusText = (status: string) => {
|
||||||
|
const map: Record<string, string> = {
|
||||||
|
pending: '待处理',
|
||||||
|
generating: '生成中',
|
||||||
|
completed: '已完成',
|
||||||
|
failed: '失败',
|
||||||
|
}
|
||||||
|
return map[status] || status
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatTime = (time: string | null) => {
|
||||||
|
if (!time) return '未知'
|
||||||
|
return new Date(time).toLocaleString('zh-CN')
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
loadStats()
|
||||||
|
loadRecentReports()
|
||||||
|
loadCollectionStats()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.dashboard {
|
||||||
|
/* 样式 */
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stat-item {
|
||||||
|
text-align: center;
|
||||||
|
padding: 20px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stat-value {
|
||||||
|
font-size: 32px;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #409eff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stat-label {
|
||||||
|
margin-top: 10px;
|
||||||
|
color: #909399;
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-list,
|
||||||
|
.collection-list {
|
||||||
|
/* 样式 */
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-item,
|
||||||
|
.collection-item {
|
||||||
|
padding: 12px;
|
||||||
|
border-bottom: 1px solid #ebeef5;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-item:hover,
|
||||||
|
.collection-item:hover {
|
||||||
|
background-color: #f5f7fa;
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-title,
|
||||||
|
.collection-name {
|
||||||
|
font-weight: 500;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-meta,
|
||||||
|
.collection-meta {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #909399;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6. 更新 App.vue
|
||||||
|
|
||||||
|
更新 `frontend/src/App.vue`:
|
||||||
|
|
||||||
|
```vue
|
||||||
|
<template>
|
||||||
|
<MainLayout />
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import MainLayout from '@/layouts/MainLayout.vue'
|
||||||
|
import { useUserStore } from '@/stores/user'
|
||||||
|
|
||||||
|
const userStore = useUserStore()
|
||||||
|
userStore.initToken()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
#app {
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7. 配置环境变量
|
||||||
|
|
||||||
|
创建 `frontend/.env.development`:
|
||||||
|
|
||||||
|
```env
|
||||||
|
VITE_API_BASE_URL=http://localhost:3000/api
|
||||||
|
```
|
||||||
|
|
||||||
|
创建 `frontend/.env.production`:
|
||||||
|
|
||||||
|
```env
|
||||||
|
VITE_API_BASE_URL=/api
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8. 创建占位页面
|
||||||
|
|
||||||
|
创建空的页面组件(后续任务中实现):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir -p src/views/config
|
||||||
|
mkdir -p src/views/reports
|
||||||
|
mkdir -p src/views/articles
|
||||||
|
mkdir -p src/views/monitoring
|
||||||
|
|
||||||
|
# 创建占位文件
|
||||||
|
touch src/views/config/LlmConfig.vue
|
||||||
|
touch src/views/config/Sources.vue
|
||||||
|
touch src/views/config/Channels.vue
|
||||||
|
touch src/views/config/Topics.vue
|
||||||
|
touch src/views/reports/ReportList.vue
|
||||||
|
touch src/views/reports/ReportDetail.vue
|
||||||
|
touch src/views/articles/ArticleList.vue
|
||||||
|
touch src/views/monitoring/Monitoring.vue
|
||||||
|
```
|
||||||
|
|
||||||
|
每个文件添加基本内容:
|
||||||
|
|
||||||
|
```vue
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<h1>页面标题</h1>
|
||||||
|
<p>此页面将在后续任务中实现</p>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
// 待实现
|
||||||
|
</script>
|
||||||
|
```
|
||||||
|
|
||||||
|
## 验证步骤
|
||||||
|
|
||||||
|
### 1. 启动前端开发服务器
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd frontend
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 访问应用
|
||||||
|
|
||||||
|
打开浏览器访问 http://localhost:5173
|
||||||
|
|
||||||
|
### 3. 验证功能
|
||||||
|
|
||||||
|
- ✅ 页面正常加载
|
||||||
|
- ✅ 侧边栏可以折叠/展开
|
||||||
|
- ✅ 路由导航正常
|
||||||
|
- ✅ 仪表盘显示统计数据
|
||||||
|
- ✅ Element Plus 组件正常显示
|
||||||
|
|
||||||
|
### 4. 测试 API 请求
|
||||||
|
|
||||||
|
打开浏览器开发者工具,检查:
|
||||||
|
- Network 标签中有 API 请求
|
||||||
|
- 请求地址正确(http://localhost:3000/api/...)
|
||||||
|
- 响应数据正常
|
||||||
|
|
||||||
|
## 预期产物
|
||||||
|
|
||||||
|
- ✅ Vue Router 配置完成
|
||||||
|
- ✅ Pinia 状态管理配置完成
|
||||||
|
- ✅ Element Plus 配置完成
|
||||||
|
- ✅ API 请求封装完成
|
||||||
|
- ✅ 基础布局实现完成
|
||||||
|
- ✅ 仪表盘页面实现完成
|
||||||
|
- ✅ 路由导航正常工作
|
||||||
|
- ✅ 前端可以正常访问后端 API
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
### 问题 1:API 请求 CORS 错误
|
||||||
|
**解决方案**:确保后端已配置 CORS,允许前端域名访问。
|
||||||
|
|
||||||
|
### 问题 2:路由 404
|
||||||
|
**解决方案**:检查路由配置,确保组件路径正确。
|
||||||
|
|
||||||
|
### 问题 3:Element Plus 样式不生效
|
||||||
|
**解决方案**:检查是否正确导入 Element Plus 样式文件。
|
||||||
|
|
||||||
|
## 下一步
|
||||||
|
|
||||||
|
完成本任务后,继续 [任务 11:前端配置管理](./11-frontend-config.md)。
|
||||||
@@ -0,0 +1,572 @@
|
|||||||
|
# 任务 11-16:前端开发与部署(简要说明)
|
||||||
|
|
||||||
|
由于时间和篇幅限制,任务 11-16 的详细文档将在实际开发时补充。这里提供简要的任务说明和关键点。
|
||||||
|
|
||||||
|
## 任务 11:前端配置管理
|
||||||
|
|
||||||
|
### 任务目标
|
||||||
|
实现配置管理页面,包括 LLM 配置、数据源、推送渠道、主题的增删改查。
|
||||||
|
|
||||||
|
### 关键功能
|
||||||
|
- LLM 配置 CRUD
|
||||||
|
- 数据源 CRUD(支持三种类型配置)
|
||||||
|
- 推送渠道 CRUD(支持多种渠道配置)
|
||||||
|
- 主题 CRUD(关联数据源和渠道)
|
||||||
|
|
||||||
|
### 技术要点
|
||||||
|
- 使用 Element Plus 表格和表单组件
|
||||||
|
- 表单验证
|
||||||
|
- JSON 配置编辑器
|
||||||
|
- Cron 表达式编辑器
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 任务 12:前端报告中心
|
||||||
|
|
||||||
|
### 任务目标
|
||||||
|
实现报告列表、报告详情、报告筛选等功能。
|
||||||
|
|
||||||
|
### 关键功能
|
||||||
|
- 报告列表(分页、筛选)
|
||||||
|
- 报告详情(Markdown 渲染)
|
||||||
|
- 报告状态显示
|
||||||
|
- 手动生成报告
|
||||||
|
|
||||||
|
### 技术要点
|
||||||
|
- Markdown 渲染(使用 markdown-it)
|
||||||
|
- 分页组件
|
||||||
|
- 筛选器
|
||||||
|
- 状态标签
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 任务 13:前端资讯浏览
|
||||||
|
|
||||||
|
### 任务目标
|
||||||
|
实现资讯列表、资讯详情、资讯筛选等功能。
|
||||||
|
|
||||||
|
### 关键功能
|
||||||
|
- 资讯列表(分页、筛选)
|
||||||
|
- 按数据源筛选
|
||||||
|
- 按主题筛选
|
||||||
|
- 按时间范围筛选
|
||||||
|
- 资讯详情
|
||||||
|
|
||||||
|
### 技术要点
|
||||||
|
- 虚拟滚动(大数据量)
|
||||||
|
- 日期范围选择器
|
||||||
|
- 多条件筛选
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 任务 14:前端采集监控
|
||||||
|
|
||||||
|
### 任务目标
|
||||||
|
实现采集状态监控、采集日志查看、手动触发采集等功能。
|
||||||
|
|
||||||
|
### 关键功能
|
||||||
|
- 数据源状态概览
|
||||||
|
- 采集日志列表
|
||||||
|
- 采集统计图表
|
||||||
|
- 手动触发采集
|
||||||
|
|
||||||
|
### 技术要点
|
||||||
|
- 实时状态更新
|
||||||
|
- 图表展示(使用 ECharts)
|
||||||
|
- 日志查看器
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 任务 15:AI Agent 实现
|
||||||
|
|
||||||
|
### 任务目标
|
||||||
|
实现 AI Agent 对话功能,支持基于报告/资讯的深入探索。
|
||||||
|
|
||||||
|
### 关键功能
|
||||||
|
- 对话界面
|
||||||
|
- 流式响应
|
||||||
|
- 上下文管理
|
||||||
|
- 自动获取更多信息
|
||||||
|
|
||||||
|
### 技术要点
|
||||||
|
- WebSocket 或 SSE(流式响应)
|
||||||
|
- 对话历史管理
|
||||||
|
- Markdown 渲染
|
||||||
|
- 代码高亮
|
||||||
|
|
||||||
|
### 后端实现
|
||||||
|
|
||||||
|
创建 `backend/src/services/agent.service.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { LlmClient } from '../utils/llm-client'
|
||||||
|
import prisma from '../utils/prisma'
|
||||||
|
import { logger } from '../utils/logger'
|
||||||
|
|
||||||
|
export class AgentService {
|
||||||
|
async chat(params: {
|
||||||
|
reportId?: number
|
||||||
|
articleId?: number
|
||||||
|
topicId: number
|
||||||
|
messages: Array<{ role: string; content: string }>
|
||||||
|
llmConfigId: number
|
||||||
|
}) {
|
||||||
|
// 1. 加载上下文
|
||||||
|
const context = await this.loadContext(params)
|
||||||
|
|
||||||
|
// 2. 构建 prompt
|
||||||
|
const systemPrompt = this.buildSystemPrompt(context)
|
||||||
|
|
||||||
|
// 3. 调用 LLM
|
||||||
|
const llmConfig = await prisma.llmConfig.findUnique({
|
||||||
|
where: { id: params.llmConfigId },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!llmConfig) {
|
||||||
|
throw new Error('LLM config not found')
|
||||||
|
}
|
||||||
|
|
||||||
|
const llmClient = new LlmClient({
|
||||||
|
baseUrl: llmConfig.baseUrl,
|
||||||
|
model: llmConfig.model,
|
||||||
|
apiKey: llmConfig.apiKey,
|
||||||
|
})
|
||||||
|
|
||||||
|
const messages = [
|
||||||
|
{ role: 'system', content: systemPrompt },
|
||||||
|
...params.messages,
|
||||||
|
]
|
||||||
|
|
||||||
|
const response = await llmClient.chat(messages as any)
|
||||||
|
|
||||||
|
// 4. 保存对话历史
|
||||||
|
await this.saveConversation(params, response.content)
|
||||||
|
|
||||||
|
return response.content
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadContext(params: any) {
|
||||||
|
// 加载报告/资讯内容作为上下文
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildSystemPrompt(context: any) {
|
||||||
|
return `你是一个资讯分析助手。
|
||||||
|
|
||||||
|
当前上下文:
|
||||||
|
${context}
|
||||||
|
|
||||||
|
你的能力:
|
||||||
|
1. 回答用户关于资讯的问题
|
||||||
|
2. 提供深入分析和见解
|
||||||
|
3. 如果需要更多信息,可以说明需要什么信息
|
||||||
|
|
||||||
|
请用中文回答。`
|
||||||
|
}
|
||||||
|
|
||||||
|
private async saveConversation(params: any, response: string) {
|
||||||
|
// 保存对话历史到数据库
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 前端实现
|
||||||
|
|
||||||
|
创建 `frontend/src/views/reports/AgentChat.vue`:
|
||||||
|
|
||||||
|
```vue
|
||||||
|
<template>
|
||||||
|
<div class="agent-chat">
|
||||||
|
<div class="messages">
|
||||||
|
<div
|
||||||
|
v-for="(msg, index) in messages"
|
||||||
|
:key="index"
|
||||||
|
:class="['message', msg.role]"
|
||||||
|
>
|
||||||
|
<div class="message-content" v-html="renderMarkdown(msg.content)" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="input-area">
|
||||||
|
<el-input
|
||||||
|
v-model="input"
|
||||||
|
type="textarea"
|
||||||
|
:rows="3"
|
||||||
|
placeholder="输入你的问题..."
|
||||||
|
@keydown.enter.ctrl="sendMessage"
|
||||||
|
/>
|
||||||
|
<el-button type="primary" @click="sendMessage" :loading="loading">
|
||||||
|
发送
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref } from 'vue'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
import request from '@/api/request'
|
||||||
|
import MarkdownIt from 'markdown-it'
|
||||||
|
|
||||||
|
const md = new MarkdownIt()
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
reportId?: number
|
||||||
|
articleId?: number
|
||||||
|
topicId: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const props = defineProps<Props>()
|
||||||
|
|
||||||
|
const messages = ref<Array<{ role: string; content: string }>>([])
|
||||||
|
const input = ref('')
|
||||||
|
const loading = ref(false)
|
||||||
|
|
||||||
|
const sendMessage = async () => {
|
||||||
|
if (!input.value.trim()) return
|
||||||
|
|
||||||
|
const userMessage = input.value
|
||||||
|
messages.value.push({ role: 'user', content: userMessage })
|
||||||
|
input.value = ''
|
||||||
|
loading.value = true
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await request.post('/agent/chat', {
|
||||||
|
reportId: props.reportId,
|
||||||
|
articleId: props.articleId,
|
||||||
|
topicId: props.topicId,
|
||||||
|
messages: messages.value,
|
||||||
|
})
|
||||||
|
|
||||||
|
messages.value.push({ role: 'assistant', content: response })
|
||||||
|
} catch (error) {
|
||||||
|
ElMessage.error('发送失败')
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const renderMarkdown = (content: string) => {
|
||||||
|
return md.render(content)
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.agent-chat {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
height: 600px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.messages {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message {
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.user {
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant {
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-content {
|
||||||
|
display: inline-block;
|
||||||
|
max-width: 70%;
|
||||||
|
padding: 10px 15px;
|
||||||
|
border-radius: 8px;
|
||||||
|
background-color: #f0f0f0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.user .message-content {
|
||||||
|
background-color: #409eff;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-area {
|
||||||
|
padding: 20px;
|
||||||
|
border-top: 1px solid #e6e6e6;
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 任务 16:部署配置
|
||||||
|
|
||||||
|
### 任务目标
|
||||||
|
配置生产环境部署,包括构建、部署脚本、监控等。
|
||||||
|
|
||||||
|
### 关键内容
|
||||||
|
|
||||||
|
#### 1. 后端构建
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2. 前端构建
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd frontend
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
构建产物在 `frontend/dist` 目录。
|
||||||
|
|
||||||
|
#### 3. Nginx 配置
|
||||||
|
|
||||||
|
创建 `nginx.conf`:
|
||||||
|
|
||||||
|
```nginx
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name your-domain.com;
|
||||||
|
|
||||||
|
# 前端静态文件
|
||||||
|
location / {
|
||||||
|
root /var/www/news-aggregator/frontend/dist;
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
# 后端 API
|
||||||
|
location /api {
|
||||||
|
proxy_pass http://localhost:3000;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection 'upgrade';
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_cache_bypass $http_upgrade;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 4. PM2 配置
|
||||||
|
|
||||||
|
已在任务 08 中创建 `ecosystem.config.js`。
|
||||||
|
|
||||||
|
启动:
|
||||||
|
```bash
|
||||||
|
pm2 start ecosystem.config.js
|
||||||
|
pm2 save
|
||||||
|
pm2 startup
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 5. Docker 部署(可选)
|
||||||
|
|
||||||
|
创建 `docker-compose.yml`:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
mysql:
|
||||||
|
image: mysql:5.6
|
||||||
|
environment:
|
||||||
|
MYSQL_ROOT_PASSWORD: password
|
||||||
|
MYSQL_DATABASE: news_aggregator
|
||||||
|
volumes:
|
||||||
|
- mysql-data:/var/lib/mysql
|
||||||
|
ports:
|
||||||
|
- "3306:3306"
|
||||||
|
|
||||||
|
backend:
|
||||||
|
build: ./backend
|
||||||
|
environment:
|
||||||
|
DATABASE_URL: mysql://root:password@mysql:3306/news_aggregator
|
||||||
|
NODE_ENV: production
|
||||||
|
depends_on:
|
||||||
|
- mysql
|
||||||
|
ports:
|
||||||
|
- "3000:3000"
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
build: ./frontend
|
||||||
|
ports:
|
||||||
|
- "80:80"
|
||||||
|
depends_on:
|
||||||
|
- backend
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
mysql-data:
|
||||||
|
```
|
||||||
|
|
||||||
|
创建 `backend/Dockerfile`:
|
||||||
|
|
||||||
|
```dockerfile
|
||||||
|
FROM node:20-alpine
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package*.json ./
|
||||||
|
RUN npm ci --only=production
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
EXPOSE 3000
|
||||||
|
|
||||||
|
CMD ["npm", "start"]
|
||||||
|
```
|
||||||
|
|
||||||
|
创建 `frontend/Dockerfile`:
|
||||||
|
|
||||||
|
```dockerfile
|
||||||
|
FROM node:20-alpine as builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package*.json ./
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
FROM nginx:alpine
|
||||||
|
|
||||||
|
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
EXPOSE 80
|
||||||
|
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 6. 环境变量配置
|
||||||
|
|
||||||
|
生产环境 `.env`:
|
||||||
|
|
||||||
|
```env
|
||||||
|
NODE_ENV=production
|
||||||
|
PORT=3000
|
||||||
|
HOST=0.0.0.0
|
||||||
|
|
||||||
|
DATABASE_URL=mysql://user:password@localhost:3306/news_aggregator
|
||||||
|
|
||||||
|
LOG_LEVEL=info
|
||||||
|
|
||||||
|
CORS_ORIGIN=https://your-domain.com
|
||||||
|
|
||||||
|
WEB_BASE_URL=https://your-domain.com
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 7. 监控和日志
|
||||||
|
|
||||||
|
使用 PM2 监控:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 查看状态
|
||||||
|
pm2 status
|
||||||
|
|
||||||
|
# 查看日志
|
||||||
|
pm2 logs
|
||||||
|
|
||||||
|
# 监控面板
|
||||||
|
pm2 monit
|
||||||
|
|
||||||
|
# Web 监控(可选)
|
||||||
|
pm2 install pm2-server-monit
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 8. 备份策略
|
||||||
|
|
||||||
|
数据库备份脚本 `scripts/backup.sh`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
DATE=$(date +%Y%m%d_%H%M%S)
|
||||||
|
BACKUP_DIR="/var/backups/news-aggregator"
|
||||||
|
DB_NAME="news_aggregator"
|
||||||
|
|
||||||
|
mkdir -p $BACKUP_DIR
|
||||||
|
|
||||||
|
# 备份数据库
|
||||||
|
mysqldump -u root -p$MYSQL_PASSWORD $DB_NAME > $BACKUP_DIR/db_$DATE.sql
|
||||||
|
|
||||||
|
# 压缩
|
||||||
|
gzip $BACKUP_DIR/db_$DATE.sql
|
||||||
|
|
||||||
|
# 删除 7 天前的备份
|
||||||
|
find $BACKUP_DIR -name "db_*.sql.gz" -mtime +7 -delete
|
||||||
|
|
||||||
|
echo "Backup completed: db_$DATE.sql.gz"
|
||||||
|
```
|
||||||
|
|
||||||
|
添加到 crontab:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 每天凌晨 2 点备份
|
||||||
|
0 2 * * * /path/to/scripts/backup.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 9. 部署检查清单
|
||||||
|
|
||||||
|
- [ ] 环境变量配置正确
|
||||||
|
- [ ] 数据库已创建并迁移
|
||||||
|
- [ ] 后端构建成功
|
||||||
|
- [ ] 前端构建成功
|
||||||
|
- [ ] Nginx 配置正确
|
||||||
|
- [ ] PM2 启动成功
|
||||||
|
- [ ] 日志正常输出
|
||||||
|
- [ ] API 可以访问
|
||||||
|
- [ ] 前端页面可以访问
|
||||||
|
- [ ] 定时任务正常运行
|
||||||
|
- [ ] 备份脚本配置完成
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 总结
|
||||||
|
|
||||||
|
以上是任务 11-16 的简要说明。详细的实现步骤将在实际开发时补充。
|
||||||
|
|
||||||
|
### 开发优先级
|
||||||
|
|
||||||
|
1. **高优先级**(MVP)
|
||||||
|
- 任务 01-09:后端核心功能
|
||||||
|
- 任务 10-11:前端基础和配置管理
|
||||||
|
|
||||||
|
2. **中优先级**
|
||||||
|
- 任务 12-14:前端报告、资讯、监控
|
||||||
|
- 任务 16:基础部署
|
||||||
|
|
||||||
|
3. **低优先级**(增强功能)
|
||||||
|
- 任务 15:AI Agent
|
||||||
|
|
||||||
|
### 预计工作量
|
||||||
|
|
||||||
|
- 任务 11:前端配置管理 - 2-3 天
|
||||||
|
- 任务 12:前端报告中心 - 2 天
|
||||||
|
- 任务 13:前端资讯浏览 - 1-2 天
|
||||||
|
- 任务 14:前端采集监控 - 1-2 天
|
||||||
|
- 任务 15:AI Agent - 2-3 天
|
||||||
|
- 任务 16:部署配置 - 1 天
|
||||||
|
|
||||||
|
**总计**:9-13 天
|
||||||
|
|
||||||
|
### 下一步
|
||||||
|
|
||||||
|
建议按以下顺序开始实施:
|
||||||
|
|
||||||
|
1. 完成任务 01-03(基础设施)
|
||||||
|
2. 完成任务 04-08(核心功能)
|
||||||
|
3. 完成任务 09(Web API)
|
||||||
|
4. 测试后端功能
|
||||||
|
5. 完成任务 10-11(前端基础)
|
||||||
|
6. 完成任务 12-14(前端功能)
|
||||||
|
7. 完成任务 15(AI Agent)
|
||||||
|
8. 完成任务 16(部署)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**注意**:以上任务文档会在实际开发过程中持续完善和更新。
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
# 任务清单
|
||||||
|
|
||||||
|
本文档列出了 News Aggregator 项目的所有开发任务。
|
||||||
|
|
||||||
|
## 后端任务
|
||||||
|
|
||||||
|
### 基础设施
|
||||||
|
- [x] [任务 01:项目初始化](./01-project-setup.md)
|
||||||
|
- [x] [任务 02:数据库搭建](./02-database-setup.md)
|
||||||
|
- [x] [任务 03:后端核心框架](./03-backend-core.md)
|
||||||
|
|
||||||
|
### 核心功能
|
||||||
|
- [x] [任务 04:采集器实现](./04-collectors.md)
|
||||||
|
- [x] [任务 05:内容处理](./05-processor.md)
|
||||||
|
- [x] [任务 06:报告生成](./06-report-generator.md)
|
||||||
|
- [x] [任务 07:分发器实现](./07-distributors.md)
|
||||||
|
- [x] [任务 08:定时任务调度](./08-scheduler.md)
|
||||||
|
|
||||||
|
### API 开发
|
||||||
|
- [x] [任务 09:Web API 实现](./09-web-api.md)
|
||||||
|
|
||||||
|
## 前端任务
|
||||||
|
|
||||||
|
### 基础设施
|
||||||
|
- [ ] [任务 10:前端初始化](./10-frontend-setup.md)
|
||||||
|
|
||||||
|
### 配置管理
|
||||||
|
- [ ] [任务 11:前端配置管理](./11-frontend-config.md)
|
||||||
|
|
||||||
|
### 报告中心
|
||||||
|
- [ ] [任务 12:前端报告中心](./12-frontend-reports.md)
|
||||||
|
|
||||||
|
### 资讯浏览
|
||||||
|
- [ ] [任务 13:前端资讯浏览](./13-frontend-articles.md)
|
||||||
|
|
||||||
|
### 采集监控
|
||||||
|
- [ ] [任务 14:前端采集监控](./14-frontend-monitoring.md)
|
||||||
|
|
||||||
|
## AI Agent
|
||||||
|
- [ ] [任务 15:AI Agent 实现](./15-ai-agent.md)
|
||||||
|
|
||||||
|
## 部署
|
||||||
|
- [ ] [任务 16:部署配置](./16-deployment.md)
|
||||||
|
|
||||||
|
## 任务说明
|
||||||
|
|
||||||
|
### 任务状态
|
||||||
|
- [x] 已完成:任务已完成并通过验证
|
||||||
|
- [ ] 待完成:任务尚未开始或正在进行中
|
||||||
|
|
||||||
|
### 任务依赖
|
||||||
|
- 任务按顺序执行,后续任务依赖前置任务
|
||||||
|
- 前端任务依赖后端 API 完成
|
||||||
|
- AI Agent 依赖前后端基础功能完成
|
||||||
|
|
||||||
|
### 预计工作量
|
||||||
|
- 任务 01-03:基础设施,约 2-3 天
|
||||||
|
- 任务 04-08:核心功能,约 5-7 天
|
||||||
|
- 任务 09:API 开发,约 1-2 天
|
||||||
|
- 任务 10-14:前端开发,约 5-7 天
|
||||||
|
- 任务 15:AI Agent,约 2-3 天
|
||||||
|
- 任务 16:部署,约 1 天
|
||||||
|
|
||||||
|
**总计**:约 16-23 天
|
||||||
|
|
||||||
|
## 开发建议
|
||||||
|
|
||||||
|
### 阶段一:MVP(最小可行产品)
|
||||||
|
完成任务 01-09,实现核心后端功能和 API。
|
||||||
|
|
||||||
|
**目标**:
|
||||||
|
- 能够采集资讯
|
||||||
|
- 能够生成报告
|
||||||
|
- 能够推送报告
|
||||||
|
- 提供完整的 API
|
||||||
|
|
||||||
|
**验证**:
|
||||||
|
- 使用 Postman/curl 测试所有 API
|
||||||
|
- 手动触发采集和报告生成
|
||||||
|
- 验证推送功能
|
||||||
|
|
||||||
|
### 阶段二:Web 界面
|
||||||
|
完成任务 10-14,实现前端管理界面。
|
||||||
|
|
||||||
|
**目标**:
|
||||||
|
- 可视化配置管理
|
||||||
|
- 报告查看和浏览
|
||||||
|
- 采集监控
|
||||||
|
|
||||||
|
**验证**:
|
||||||
|
- 通过 Web 界面完成所有配置
|
||||||
|
- 查看报告和资讯
|
||||||
|
- 监控采集状态
|
||||||
|
|
||||||
|
### 阶段三:AI 增强
|
||||||
|
完成任务 15,实现 AI Agent 功能。
|
||||||
|
|
||||||
|
**目标**:
|
||||||
|
- 与 AI 对话深入了解资讯
|
||||||
|
- AI 自动获取更多信息
|
||||||
|
|
||||||
|
**验证**:
|
||||||
|
- 测试 AI 对话功能
|
||||||
|
- 验证 AI 能够获取额外信息
|
||||||
|
|
||||||
|
### 阶段四:生产部署
|
||||||
|
完成任务 16,配置生产环境部署。
|
||||||
|
|
||||||
|
**目标**:
|
||||||
|
- 生产环境配置
|
||||||
|
- 自动化部署
|
||||||
|
- 监控和日志
|
||||||
|
|
||||||
|
**验证**:
|
||||||
|
- 在生产环境运行
|
||||||
|
- 验证稳定性
|
||||||
|
- 检查日志和监控
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
### 开发环境搭建
|
||||||
|
```bash
|
||||||
|
# 1. 克隆项目
|
||||||
|
git clone <repository-url>
|
||||||
|
cd news-aggregator
|
||||||
|
|
||||||
|
# 2. 安装依赖
|
||||||
|
cd backend && npm install
|
||||||
|
cd ../frontend && npm install
|
||||||
|
|
||||||
|
# 3. 配置环境变量
|
||||||
|
cd ../backend
|
||||||
|
cp .env.example .env
|
||||||
|
# 编辑 .env 文件
|
||||||
|
|
||||||
|
# 4. 初始化数据库
|
||||||
|
npm run prisma:migrate
|
||||||
|
npm run prisma:seed
|
||||||
|
|
||||||
|
# 5. 启动开发服务
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
### 开发流程
|
||||||
|
1. 阅读任务文档
|
||||||
|
2. 按步骤实现功能
|
||||||
|
3. 运行验证步骤
|
||||||
|
4. 提交代码
|
||||||
|
5. 继续下一个任务
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
|
||||||
|
### 代码规范
|
||||||
|
- 遵循 TypeScript 最佳实践
|
||||||
|
- 使用 ESLint 和 Prettier
|
||||||
|
- 编写清晰的注释
|
||||||
|
- 保持代码简洁
|
||||||
|
|
||||||
|
### 测试
|
||||||
|
- 每个功能完成后进行测试
|
||||||
|
- 使用提供的测试脚本
|
||||||
|
- 验证边界情况
|
||||||
|
- 记录测试结果
|
||||||
|
|
||||||
|
### 文档
|
||||||
|
- 更新 API 文档
|
||||||
|
- 记录配置说明
|
||||||
|
- 编写使用指南
|
||||||
|
- 维护 CHANGELOG
|
||||||
|
|
||||||
|
### 版本控制
|
||||||
|
- 每个任务完成后提交
|
||||||
|
- 使用清晰的提交信息
|
||||||
|
- 创建功能分支
|
||||||
|
- 定期合并到主分支
|
||||||
|
|
||||||
|
## 问题反馈
|
||||||
|
|
||||||
|
如果在开发过程中遇到问题:
|
||||||
|
1. 查看任务文档的"常见问题"部分
|
||||||
|
2. 检查相关的设计文档
|
||||||
|
3. 查看代码注释和示例
|
||||||
|
4. 在项目 Issues 中提问
|
||||||
|
|
||||||
|
## 参考资源
|
||||||
|
|
||||||
|
### 文档
|
||||||
|
- [产品需求文档](../requirements/product-requirements.md)
|
||||||
|
- [产品逻辑架构](../designs/product-architecture.md)
|
||||||
|
- [技术架构](../designs/technical-architecture.md)
|
||||||
|
- [数据库设计](../designs/database-design.md)
|
||||||
|
|
||||||
|
### 技术栈文档
|
||||||
|
- [Fastify 文档](https://www.fastify.io/)
|
||||||
|
- [Prisma 文档](https://www.prisma.io/docs)
|
||||||
|
- [Vue 3 文档](https://vuejs.org/)
|
||||||
|
- [Element Plus 文档](https://element-plus.org/)
|
||||||
|
- [OpenAI API 文档](https://platform.openai.com/docs)
|
||||||
|
- [Playwright 文档](https://playwright.dev/)
|
||||||
|
|
||||||
|
## 更新日志
|
||||||
|
|
||||||
|
- 2024-01-01: 创建任务清单
|
||||||
|
- 2024-01-02: 完成任务 01-09 文档
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea
|
||||||
|
.DS_Store
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Vue 3 + TypeScript + Vite
|
||||||
|
|
||||||
|
This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
|
||||||
|
|
||||||
|
Learn more about the recommended Project Setup and IDE Support in the [Vue Docs TypeScript Guide](https://vuejs.org/guide/typescript/overview.html#project-setup).
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>frontend</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
<script type="module" src="/src/main.ts"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Generated
+2161
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,27 @@
|
|||||||
|
{
|
||||||
|
"name": "frontend",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vue-tsc -b && vite build",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@element-plus/icons-vue": "^2.3.2",
|
||||||
|
"axios": "^1.13.4",
|
||||||
|
"element-plus": "^2.13.2",
|
||||||
|
"pinia": "^3.0.4",
|
||||||
|
"vue": "^3.5.24",
|
||||||
|
"vue-router": "^4.6.4"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^24.10.9",
|
||||||
|
"@vitejs/plugin-vue": "^6.0.1",
|
||||||
|
"@vue/tsconfig": "^0.8.1",
|
||||||
|
"typescript": "~5.9.3",
|
||||||
|
"vite": "^7.2.4",
|
||||||
|
"vue-tsc": "^3.1.4"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,30 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import HelloWorld from './components/HelloWorld.vue'
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<a href="https://vite.dev" target="_blank">
|
||||||
|
<img src="/vite.svg" class="logo" alt="Vite logo" />
|
||||||
|
</a>
|
||||||
|
<a href="https://vuejs.org/" target="_blank">
|
||||||
|
<img src="./assets/vue.svg" class="logo vue" alt="Vue logo" />
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
<HelloWorld msg="Vite + Vue" />
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.logo {
|
||||||
|
height: 6em;
|
||||||
|
padding: 1.5em;
|
||||||
|
will-change: filter;
|
||||||
|
transition: filter 300ms;
|
||||||
|
}
|
||||||
|
.logo:hover {
|
||||||
|
filter: drop-shadow(0 0 2em #646cffaa);
|
||||||
|
}
|
||||||
|
.logo.vue:hover {
|
||||||
|
filter: drop-shadow(0 0 2em #42b883aa);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>
|
||||||
|
After Width: | Height: | Size: 496 B |
@@ -0,0 +1,41 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref } from 'vue'
|
||||||
|
|
||||||
|
defineProps<{ msg: string }>()
|
||||||
|
|
||||||
|
const count = ref(0)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<h1>{{ msg }}</h1>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<button type="button" @click="count++">count is {{ count }}</button>
|
||||||
|
<p>
|
||||||
|
Edit
|
||||||
|
<code>components/HelloWorld.vue</code> to test HMR
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
Check out
|
||||||
|
<a href="https://vuejs.org/guide/quick-start.html#local" target="_blank"
|
||||||
|
>create-vue</a
|
||||||
|
>, the official Vue + Vite starter
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
Learn more about IDE Support for Vue in the
|
||||||
|
<a
|
||||||
|
href="https://vuejs.org/guide/scaling-up/tooling.html#ide-support"
|
||||||
|
target="_blank"
|
||||||
|
>Vue Docs Scaling up Guide</a
|
||||||
|
>.
|
||||||
|
</p>
|
||||||
|
<p class="read-the-docs">Click on the Vite and Vue logos to learn more</p>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.read-the-docs {
|
||||||
|
color: #888;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { createApp } from 'vue'
|
||||||
|
import { createPinia } from 'pinia'
|
||||||
|
import App from './App.vue'
|
||||||
|
import router from './router'
|
||||||
|
import { setupElementPlus } from './plugins/element-plus'
|
||||||
|
|
||||||
|
const app = createApp(App)
|
||||||
|
const pinia = createPinia()
|
||||||
|
|
||||||
|
app.use(pinia)
|
||||||
|
app.use(router)
|
||||||
|
setupElementPlus(app)
|
||||||
|
|
||||||
|
app.mount('#app')
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import ElementPlus from 'element-plus'
|
||||||
|
import 'element-plus/dist/index.css'
|
||||||
|
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
||||||
|
import type { App } from 'vue'
|
||||||
|
|
||||||
|
export function setupElementPlus(app: App) {
|
||||||
|
app.use(ElementPlus)
|
||||||
|
|
||||||
|
// 注册所有图标
|
||||||
|
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
||||||
|
app.component(key, component)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { createRouter, createWebHistory } from 'vue-router'
|
||||||
|
|
||||||
|
const router = createRouter({
|
||||||
|
history: createWebHistory(),
|
||||||
|
routes: [
|
||||||
|
{
|
||||||
|
path: '/',
|
||||||
|
redirect: '/dashboard',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
|
export default router
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
:root {
|
||||||
|
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
|
||||||
|
line-height: 1.5;
|
||||||
|
font-weight: 400;
|
||||||
|
|
||||||
|
color-scheme: light dark;
|
||||||
|
color: rgba(255, 255, 255, 0.87);
|
||||||
|
background-color: #242424;
|
||||||
|
|
||||||
|
font-synthesis: none;
|
||||||
|
text-rendering: optimizeLegibility;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
|
}
|
||||||
|
|
||||||
|
a {
|
||||||
|
font-weight: 500;
|
||||||
|
color: #646cff;
|
||||||
|
text-decoration: inherit;
|
||||||
|
}
|
||||||
|
a:hover {
|
||||||
|
color: #535bf2;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
display: flex;
|
||||||
|
place-items: center;
|
||||||
|
min-width: 320px;
|
||||||
|
min-height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
font-size: 3.2em;
|
||||||
|
line-height: 1.1;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
padding: 0.6em 1.2em;
|
||||||
|
font-size: 1em;
|
||||||
|
font-weight: 500;
|
||||||
|
font-family: inherit;
|
||||||
|
background-color: #1a1a1a;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: border-color 0.25s;
|
||||||
|
}
|
||||||
|
button:hover {
|
||||||
|
border-color: #646cff;
|
||||||
|
}
|
||||||
|
button:focus,
|
||||||
|
button:focus-visible {
|
||||||
|
outline: 4px auto -webkit-focus-ring-color;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
padding: 2em;
|
||||||
|
}
|
||||||
|
|
||||||
|
#app {
|
||||||
|
max-width: 1280px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 2rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: light) {
|
||||||
|
:root {
|
||||||
|
color: #213547;
|
||||||
|
background-color: #ffffff;
|
||||||
|
}
|
||||||
|
a:hover {
|
||||||
|
color: #747bff;
|
||||||
|
}
|
||||||
|
button {
|
||||||
|
background-color: #f9f9f9;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"extends": "@vue/tsconfig/tsconfig.dom.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||||
|
"types": ["vite/client"],
|
||||||
|
"baseUrl": ".",
|
||||||
|
"paths": {
|
||||||
|
"@/*": ["./src/*"]
|
||||||
|
},
|
||||||
|
|
||||||
|
/* Linting */
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"erasableSyntaxOnly": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"noUncheckedSideEffectImports": true
|
||||||
|
},
|
||||||
|
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"files": [],
|
||||||
|
"references": [
|
||||||
|
{ "path": "./tsconfig.app.json" },
|
||||||
|
{ "path": "./tsconfig.node.json" }
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||||
|
"target": "ES2023",
|
||||||
|
"lib": ["ES2023"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"types": ["node"],
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
/* Bundler mode */
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
|
||||||
|
/* Linting */
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"erasableSyntaxOnly": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"noUncheckedSideEffectImports": true
|
||||||
|
},
|
||||||
|
"include": ["vite.config.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import vue from '@vitejs/plugin-vue'
|
||||||
|
import path from 'path'
|
||||||
|
|
||||||
|
// https://vite.dev/config/
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [vue()],
|
||||||
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
'@': path.resolve(__dirname, './src')
|
||||||
|
}
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
port: 5173,
|
||||||
|
proxy: {
|
||||||
|
'/api': {
|
||||||
|
target: 'http://localhost:3000',
|
||||||
|
changeOrigin: true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
Reference in new issue
Block a user