Files
learn-ai/docs/tasks/06-report-generator.md
hughhuangandClaude Sonnet 4.5 830a17bf46 初始化项目结构和基础模块
完成内容:
- 创建前后端项目目录结构
- 初始化 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>
2026-02-03 12:11:57 +08:00

15 KiB
Raw Permalink Blame History

任务 06:报告生成

任务概述

实现报告生成服务,根据主题配置查询资讯、处理内容、生成报告。

前置条件

  • 任务 01-05 已完成
  • 内容处理服务已实现

任务目标

  • 创建报告生成服务
  • 实现按时间范围查询资讯
  • 集成内容处理
  • 生成报告并保存到数据库

详细步骤

1. 创建报告类型定义

更新 backend/src/types/index.ts:

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:

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:

export * from './collector.service'
export * from './processor.service'
export * from './report.service'

4. 创建测试脚本

创建 backend/src/test-report.ts:

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:

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. 准备测试数据

确保有资讯数据和启用的主题:

# 查看主题
npm run prisma:studio

# 确保:
# 1. topics 表有启用的主题
# 2. topic_sources 表有关联
# 3. articles 表有资讯数据

2. 运行测试

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. 测试手动生成报告

# 为所有主题生成报告
npx tsx src/scripts/generate-report.ts

# 为指定主题生成报告
npx tsx src/scripts/generate-report.ts 1

4. 验证数据库

使用 Prisma Studio 查看:

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:分发器实现。