import { InjectRepository } from '@nestjs/typeorm' ; import { Repository } from 'typeorm' ; import { ILeaveRequestRepository } from 'src/Domain/HumanResource/Leave/Repository/ILeaveRequestRepository' ; import { MAX_ITEMS_PER_PAGE } from 'src/Application/Common/Pagination' ; import { LeaveRequest , Status } from 'src/Domain/HumanResource/Leave/LeaveRequest.entity' ; import { User } from 'src/Domain/HumanResource/User/User.entity' ; export class LeaveRequestRepository implements ILeaveRequestRepository { constructor ( @ InjectRepository ( LeaveRequest ) private readonly repository ) { } public save ( leaveRequest ) { return this . repository . save ( leaveRequest ) ; } public remove ( leaveRequest ) { this . repository . delete ( leaveRequest . getId ( ) ) ; } public findOneById ( id ) { return this . repository . createQueryBuilder ( 'leaveRequest' ) . select ( [ 'leaveRequest.id' , 'leaveRequest.type' , 'leaveRequest.status' , 'leaveRequest.startDate' , 'leaveRequest.startsAllDay' , 'leaveRequest.endDate' , 'leaveRequest.endsAllDay' , 'leaveRequest.comment' , 'leaveRequest.moderationComment' , 'user.id' , 'user.firstName' , 'user.lastName' , 'moderator.id' , 'moderator.firstName' , 'moderator.lastName' ] ) . where ( 'leaveRequest.id = :id' , { id } ) . innerJoin ( 'leaveRequest.user' , 'user' ) . leftJoin ( 'leaveRequest.moderator' , 'moderator' ) . getOne ( ) ; } public findExistingLeaveRequestsByUserAndPeriod ( user , startDate , endDate ) { return this . repository . createQueryBuilder ( 'leaveRequest' ) . select ( 'leaveRequest.id' ) . where ( 'leaveRequest.user = :id' , { id : user . getId ( ) } ) . andWhere ( '(leaveRequest.startDate BETWEEN :startDate AND :endDate OR leaveRequest.endDate BETWEEN :startDate AND :endDate)' , { startDate , endDate } ) . andWhere ( '(leaveRequest.status = :accepted OR leaveRequest.status = :pending)' , { accepted : Status . ACCEPTED , pending : Status . PENDING } ) . getOne ( ) ; } public findLeaveRequests ( page , status ? ) { const query = this . repository . createQueryBuilder ( 'leaveRequest' ) . select ( [ 'leaveRequest.id' , 'leaveRequest.type' , 'leaveRequest.status' , 'leaveRequest.startDate' , 'leaveRequest.startsAllDay' , 'leaveRequest.endDate' , 'leaveRequest.endsAllDay' , 'user.id' , 'user.firstName' , 'user.lastName' ] ) . innerJoin ( 'leaveRequest.user' , 'user' ) . orderBy ( 'leaveRequest.status' , 'DESC' ) . addOrderBy ( 'leaveRequest.startDate' , 'DESC' ) . limit ( MAX_ITEMS_PER_PAGE ) . offset ( ( page - 1 ) * MAX_ITEMS_PER_PAGE ) ; if ( status ) { query . where ( 'leaveRequest.status = :status' , { status } ) ; } else { query . where ( 'leaveRequest.status != :status' , { status : Status . ACCEPTED } ) ; } return query . getManyAndCount ( ) ; } }