|
| 1 | +import { AnalyticsRepository } from '../../interfaces/analytics-repository'; |
| 2 | +import { AnalyticsAggregator } from '../aggregator'; |
| 3 | +import { AnalyticsFormatter, TimeTranslations } from '../formatter'; |
| 4 | + |
| 5 | +export interface DashboardReportResult { |
| 6 | + raw: { |
| 7 | + todayMs: number; |
| 8 | + yesterdayMs: number; |
| 9 | + todaySessions: number; |
| 10 | + }; |
| 11 | + formatted: { |
| 12 | + todayReadable: string; |
| 13 | + trendText: string; |
| 14 | + isImproving: boolean; |
| 15 | + }; |
| 16 | +} |
| 17 | + |
| 18 | +export class DashboardReportGenerator { |
| 19 | + constructor(private repo: AnalyticsRepository) {} |
| 20 | + |
| 21 | + private async getUsageForDay(platformId: string, startOfDayMs: number) { |
| 22 | + const endOfDayMs = startOfDayMs + 24 * 60 * 60 * 1000 - 1; |
| 23 | + const records = await this.repo.queryRecords({ |
| 24 | + platformId: platformId, |
| 25 | + fromTime: startOfDayMs, |
| 26 | + toTime: endOfDayMs, |
| 27 | + }); |
| 28 | + |
| 29 | + return { |
| 30 | + duration: AnalyticsAggregator.calculateTotalDuration(records), |
| 31 | + sessions: AnalyticsAggregator.calculateSessionCount(records), |
| 32 | + }; |
| 33 | + } |
| 34 | + |
| 35 | + public async generate( |
| 36 | + platformId: string, |
| 37 | + translations: TimeTranslations, |
| 38 | + ): Promise<DashboardReportResult> { |
| 39 | + const now = new Date(); |
| 40 | + const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime(); |
| 41 | + const yesterdayStart = todayStart - 24 * 60 * 60 * 1000; |
| 42 | + |
| 43 | + const todayData = await this.getUsageForDay(platformId, todayStart); |
| 44 | + const yesterdayData = await this.getUsageForDay(platformId, yesterdayStart); |
| 45 | + |
| 46 | + const trendPercent = AnalyticsFormatter.calculateTrendPercent( |
| 47 | + yesterdayData.duration, |
| 48 | + todayData.duration, |
| 49 | + ); |
| 50 | + |
| 51 | + return { |
| 52 | + raw: { |
| 53 | + todayMs: todayData.duration, |
| 54 | + yesterdayMs: yesterdayData.duration, |
| 55 | + todaySessions: todayData.sessions, |
| 56 | + }, |
| 57 | + formatted: { |
| 58 | + todayReadable: AnalyticsFormatter.msToReadable(todayData.duration, translations), |
| 59 | + trendText: AnalyticsFormatter.formatTrend(trendPercent), |
| 60 | + isImproving: trendPercent <= 0, |
| 61 | + }, |
| 62 | + }; |
| 63 | + } |
| 64 | +} |
0 commit comments