import { Injectable } from "@nestjs/common"; import { Result } from "src/common/errors/result-error.factory"; import { computeHours } from "src/common/utils/date-utils"; import { PrismaService } from "src/prisma/prisma.service"; @Injectable() export class ShiftsDeleteService { constructor(private readonly prisma: PrismaService) { } //_________________________________________________________________ // DELETE //_________________________________________________________________ //finds shifts using shit_ids //ajust paid-time-off banks //blocs deletion if approved async deleteShift(shift_id: number): Promise> { try { return await this.prisma.$transaction(async (tx) => { const paid_time_off_types: string[] = ['SICK', 'VACATION', 'BANKING', 'WITHDRAW_BANKED']; const shift = await tx.shifts.findUnique({ where: { id: shift_id }, select: { id: true, date: true, start_time: true, end_time: true, timesheet: true, bank_code: { select: { type: true } } }, }); if (!shift) return { success: false, error: `SHIFT_NOT_FOUND` }; const ajusted_hours = computeHours(shift.start_time, shift.end_time); //manage banked types, ensures update of amount of hours in bank is ajusted when a paid_time_off shift is deleted if (paid_time_off_types.includes(shift.bank_code.type)) { switch (shift.bank_code.type) { case 'SICK': await this.prisma.paidTimeOff.update({ where: { employee_id: shift.timesheet.employee_id }, data: { sick_hours: { increment: ajusted_hours }, }, }); break; case 'VACATION': await this.prisma.paidTimeOff.update({ where: { employee_id: shift.timesheet.employee_id }, data: { vacation_hours: { increment: ajusted_hours }, }, }); break; case 'WITHDRAW_BANKED': await this.prisma.paidTimeOff.update({ where: { employee_id: shift.timesheet.employee_id }, data: { banked_hours: { decrement: ajusted_hours }, }, }); case 'BANKING': await this.prisma.paidTimeOff.update({ where: { employee_id: shift.timesheet.employee_id }, data: { banked_hours: { increment: ajusted_hours }, }, }); break; default: break; } } await tx.shifts.delete({ where: { id: shift_id } }); return { success: true, data: shift.id }; }); } catch (error) { return { success: false, error: `SHIFT_NOT_FOUND` } } } }