All files / src/domains/hr/attendance/lock lock.service.ts

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

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 70 71 72                                                                                                                                               
import {
  Injectable,
  NotFoundException,
  BadRequestException,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { AttendanceLock, AttendanceDailyRecord } from '../schemas';
import { CreateLockDto, UnlockDto } from './dto/lock.dto';
 
@Injectable()
export class LockService {
  constructor(
    @InjectModel(AttendanceLock.name) private lockModel: Model<AttendanceLock>,
    @InjectModel(AttendanceDailyRecord.name)
    private dailyRecordModel: Model<AttendanceDailyRecord>,
  ) {}
 
  async createLock(tenantId: string, createDto: CreateLockDto, userId: string) {
    const created = new this.lockModel({
      ...createDto,
      tenantId,
      lockedBy: userId,
      lockedAt: new Date(),
    });
 
    await created.save();
 
    // Apply lock to daily records
    const filter: any = {
      tenantId,
      attendanceDate: { $gte: createDto.startDate, $lte: createDto.endDate },
    };
 
    if (createDto.targetEmployeeIds && createDto.targetEmployeeIds.length > 0) {
      filter.employeeId = { $in: createDto.targetEmployeeIds };
    }
 
    await this.dailyRecordModel.updateMany(filter, { $set: { locked: true } });
 
    return created;
  }
 
  async getLocks(tenantId: string) {
    return this.lockModel.find({ tenantId }).sort({ startDate: -1 }).exec();
  }
 
  async unlock(tenantId: string, lockId: string, unlockDto: UnlockDto) {
    const lock = await this.lockModel.findOne({ _id: lockId, tenantId }).exec();
    if (!lock) throw new NotFoundException('Lock not found');
 
    lock.status = 'unlocked';
    if (unlockDto.unlockReason) lock.unlockReason = unlockDto.unlockReason;
    if (unlockDto.unlockedUntil) lock.unlockedUntil = unlockDto.unlockedUntil;
    await lock.save();
 
    // Remove lock from daily records
    const filter: any = {
      tenantId,
      attendanceDate: { $gte: lock.startDate, $lte: lock.endDate },
    };
 
    if (lock.targetEmployeeIds && lock.targetEmployeeIds.length > 0) {
      filter.employeeId = { $in: lock.targetEmployeeIds };
    }
 
    await this.dailyRecordModel.updateMany(filter, { $set: { locked: false } });
 
    return lock;
  }
}