All files / main/services statsService.ts

100% Statements 16/16
100% Branches 2/2
100% Functions 6/6
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49            1x 6x 6x 6x 6x     1x       3x       2x 2x 2x       1x 1x 1x                 1x 1x                  
import { aggregateMonthStats, aggregateStats } from '@core/stats/statsAggregator'
import type { MonthStatsRequest } from '@shared/contracts'
import type { FocusStats, MonthStats } from '@shared/types'
import type { ClockPort } from '@main/ports/desktop'
import type { TaskRepository, TimerSessionRepository } from '@main/ports/repositories'
 
const localDateKey = (date: Date): string => {
  const year = date.getFullYear()
  const month = `${date.getMonth() + 1}`.padStart(2, '0')
  const day = `${date.getDate()}`.padStart(2, '0')
  return `${year}-${month}-${day}`
}
 
const countCompletedTasksForLocalDay = (
  tasks: Awaited<ReturnType<TaskRepository['list']>>,
  now: Date
): number =>
  tasks.filter((task) => task.completedAt && localDateKey(new Date(task.completedAt)) === localDateKey(now)).length
 
export class StatsService {
  constructor(
    private readonly sessions: TimerSessionRepository,
    private readonly tasks: TaskRepository,
    private readonly clock: ClockPort
  ) {}
 
  async get(): Promise<FocusStats> {
    const now = new Date(this.clock.now())
    const tasks = await this.tasks.list()
    return aggregateStats({
      now,
      tasks,
      sessions: await this.sessions.list(),
      completedTasks: countCompletedTasksForLocalDay(tasks, now)
    })
  }
 
  async getMonth(request: MonthStatsRequest): Promise<MonthStats> {
    const tasks = await this.tasks.list()
    return aggregateMonthStats({
      now: new Date(this.clock.now()),
      year: request.year,
      month: request.month,
      tasks,
      sessions: await this.sessions.list()
    })
  }
}