初始化项目结构和基础模块
完成内容: - 创建前后端项目目录结构 - 初始化 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
@@ -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 文档
|
||||
Reference in new issue
Block a user