All files / src/domains/projects/services time-tracking.service.ts

0% Statements 0/26
0% Branches 0/12
0% Functions 0/4
0% Lines 0/22

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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69                                                                                                                                         
import {
  Injectable,
  Logger,
  NotFoundException,
  BadRequestException,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { TimeEntry } from '../schemas/time-entry.schema';
 
@Injectable()
export class TimeTrackingService {
  private readonly logger = new Logger(TimeTrackingService.name);
 
  constructor(
    @InjectModel(TimeEntry.name)
    private readonly timeEntryModel: Model<TimeEntry>,
  ) {}
 
  async startTimer(
    tenantId: string,
    employeeId: string,
    projectId: string,
    taskId?: string,
  ): Promise<any> {
    const activeTimer = await this.timeEntryModel
      .findOne({ tenantId, employeeId, stopwatchStatus: 'active' })
      .exec();
    if (activeTimer) throw new BadRequestException('Timer already active');
 
    const entry = new this.timeEntryModel({
      tenantId,
      employeeId,
      projectId,
      taskId,
      date: new Date(),
      startTime: new Date(),
      stopwatchStatus: 'active',
    });
    return entry.save();
  }
 
  async stopTimer(tenantId: string, entryId: string): Promise<any> {
    const entry = await this.timeEntryModel
      .findOne({ _id: entryId, tenantId })
      .exec();
    if (!entry) throw new NotFoundException('Timer not found');
    if (entry.stopwatchStatus !== 'active')
      throw new BadRequestException('Timer is not active');
 
    entry.endTime = new Date();
    entry.stopwatchStatus = 'completed';
    const ms =
      entry.endTime.getTime() -
      (entry.startTime?.getTime() || entry.endTime.getTime());
    entry.hours = ms / (1000 * 60 * 60);
    return entry.save();
  }
 
  async logManualTime(tenantId: string, data: any): Promise<any> {
    const entry = new this.timeEntryModel({
      ...data,
      tenantId,
      stopwatchStatus: 'completed',
    });
    return entry.save();
  }
}