From 14eaad53c365d39f11ae98423b2d4aaa2499fd90 Mon Sep 17 00:00:00 2001 From: WangDL Date: Sun, 24 May 2026 11:13:02 +0800 Subject: [PATCH] fix: auto-aggregate AI costs hourly instead of manual-only Co-Authored-By: Claude Opus 4.7 --- .../admin-costs/cost-aggregation.service.ts | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/modules/admin-costs/cost-aggregation.service.ts b/src/modules/admin-costs/cost-aggregation.service.ts index 53485da..0ce7428 100644 --- a/src/modules/admin-costs/cost-aggregation.service.ts +++ b/src/modules/admin-costs/cost-aggregation.service.ts @@ -1,12 +1,24 @@ -import { Injectable, Logger } from '@nestjs/common'; +import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common'; import { PrismaService } from '../../infrastructure/database/prisma.service'; +const AGGREGATE_INTERVAL_MS = 60 * 60 * 1000; // hourly + @Injectable() -export class CostAggregationService { +export class CostAggregationService implements OnModuleInit, OnModuleDestroy { private readonly logger = new Logger(CostAggregationService.name); + private timer: ReturnType | null = null; constructor(private readonly prisma: PrismaService) {} + async onModuleInit() { + await this.aggregateToday(); + this.timer = setInterval(() => this.aggregateToday(), AGGREGATE_INTERVAL_MS); + } + + onModuleDestroy() { + if (this.timer) clearInterval(this.timer); + } + /** Aggregate today's AiUsageLog into CostDailySummary */ async aggregateToday(): Promise { const today = new Date(); today.setHours(0, 0, 0, 0);