diff --git a/backend/src/services/report.service.ts b/backend/src/services/report.service.ts new file mode 100644 index 0000000..88887b7 --- /dev/null +++ b/backend/src/services/report.service.ts @@ -0,0 +1,316 @@ +import prisma from '../config/database'; +import { ProcessorService } from './processor.service'; +import { ProcessMode, ReportGenerationOptions } from '../types'; +import { Article } from '@prisma/client'; +import logger from '../utils/logger'; + +export class ReportService { + private processorService: ProcessorService; + + constructor() { + this.processorService = new ProcessorService(); + } + + /** + * 生成报告 + */ + async generateReport(options: ReportGenerationOptions): Promise { + 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 sourceIds = topic.topicSources.map((ts) => ts.sourceId); + const articles = await this.queryArticles(sourceIds, 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 = this.processorService.deduplicateArticles(articles); + const sorted = this.processorService.sortArticlesByDate(deduplicated); + + logger.info(`去重后 ${sorted.length} 条资讯`); + + // 处理内容 + let processedContent: string; + + if (!topic.llmConfig || !topic.llmConfig.enabled) { + logger.warn('没有启用的 LLM 配置,使用简单聚合模式'); + const result = await this.processorService.processArticles(sorted, 'aggregate'); + 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 { + 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 { + return `# ${title} + +**主题**: ${topicName} +**时间范围**: ${this.formatDate(periodStart)} - ${this.formatDate(periodEnd)} +**资讯数量**: ${articleCount} 条 +**生成时间**: ${this.formatDate(new Date())} + +--- + +${processedContent} + +--- + +*本报告由 News Aggregator 自动生成*`; + } + + /** + * 格式化日期范围 + */ + private formatDateRange(start: Date, end: Date): string { + const startStr = this.formatDate(start); + const endStr = this.formatDate(end); + return startStr === endStr ? startStr : `${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; + const start = new Date(now.getTime() - lookback * 60 * 60 * 1000); + return { start, end: now }; + } + + /** + * 为主题生成报告 + */ + async generateReportForTopic(topicId: number): Promise { + const topic = await prisma.topic.findUnique({ where: { id: topicId } }); + + if (!topic) { + throw new Error(`Topic ${topicId} not found`); + } + + const { start, end } = this.calculatePeriod(topic.scheduleConfig); + + return this.generateReport({ + topicId, + periodStart: start, + periodEnd: end, + }); + } + + /** + * 为所有启用的主题生成报告 + */ + async generateReportsForAllTopics(): Promise { + 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), + }; + } +}