Assist_Design/apps/bff/src/subscriptions/sim-usage-store.service.ts
tema e115a3ab15 Add daily SIM usage tracking and persistence functionality
- Introduced SimUsageDaily model to store daily usage snapshots for SIM accounts.
- Updated SimManagementService to persist daily usage data and clean up previous months' records.
- Enhanced error handling for usage persistence failures.
- Updated SubscriptionsModule to include SimUsageStoreService for managing usage data.
- Improved user interface text for clarity in SIM management pages.
2025-09-06 10:01:52 +09:00

50 lines
1.8 KiB
TypeScript

import { Injectable, Inject } from "@nestjs/common";
import { PrismaService } from "../common/prisma/prisma.service";
import { Logger } from "nestjs-pino";
@Injectable()
export class SimUsageStoreService {
constructor(
private readonly prisma: PrismaService,
@Inject(Logger) private readonly logger: Logger,
) {}
private normalizeDate(date?: Date): Date {
const d = date ? new Date(date) : new Date();
// strip time to YYYY-MM-DD
const iso = d.toISOString().split('T')[0];
return new Date(iso + 'T00:00:00.000Z');
}
async upsertToday(account: string, usageMb: number, date?: Date): Promise<void> {
const day = this.normalizeDate(date);
try {
await (this.prisma as any).simUsageDaily.upsert({
where: { account_date: { account, date: day } as any },
update: { usageMb },
create: { account, date: day, usageMb },
});
} catch (e: any) {
this.logger.error("Failed to upsert daily usage", { account, error: e?.message });
}
}
async getLastNDays(account: string, days = 30): Promise<Array<{ date: string; usageMb: number }>> {
const end = this.normalizeDate();
const start = new Date(end);
start.setUTCDate(end.getUTCDate() - (days - 1));
const rows = await (this.prisma as any).simUsageDaily.findMany({
where: { account, date: { gte: start, lte: end } },
orderBy: { date: 'desc' },
}) as Array<{ date: Date; usageMb: number }>;
return rows.map((r) => ({ date: r.date.toISOString().split('T')[0], usageMb: r.usageMb }));
}
async cleanupPreviousMonths(): Promise<number> {
const now = new Date();
const firstOfMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
const result = await (this.prisma as any).simUsageDaily.deleteMany({ where: { date: { lt: firstOfMonth } } });
return result.count;
}
}