feat(schedulePresets): ajusted the create function. added validation of the name and overlaps checking

This commit is contained in:
Matthieu Haineault 2025-11-25 16:32:20 -05:00
parent 35665d49dd
commit c5c96cce22
5 changed files with 291 additions and 300 deletions

View File

@ -1,40 +1,40 @@
// import { Controller, Param, Query, Body, Get, Post, ParseIntPipe, Delete, Patch, Req } from "@nestjs/common";
// import { RolesAllowed } from "src/common/decorators/roles.decorators";
// import { GLOBAL_CONTROLLER_ROLES, MANAGER_ROLES } from "src/common/shared/role-groupes";
// import { SchedulePresetsDto } from "src/time-and-attendance/schedule-presets/dtos/create-schedule-presets.dto";
import { Controller, Param, Query, Body, Get, Post, ParseIntPipe, Delete, Patch, Req } from "@nestjs/common";
import { RolesAllowed } from "src/common/decorators/roles.decorators";
import { GLOBAL_CONTROLLER_ROLES, MANAGER_ROLES } from "src/common/shared/role-groupes";
import { SchedulePresetsDto } from "src/time-and-attendance/schedule-presets/dtos/create-schedule-presets.dto";
// import { SchedulePresetsUpdateDto } from "src/time-and-attendance/schedule-presets/dtos/update-schedule-presets.dto";
// import { SchedulePresetsApplyService } from "src/time-and-attendance/schedule-presets/services/schedule-presets-apply.service";
// import { SchedulePresetsGetService } from "src/time-and-attendance/schedule-presets/services/schedule-presets-get.service";
// import { SchedulePresetsUpsertService } from "src/time-and-attendance/schedule-presets/services/schedule-presets-upsert.service";
import { SchedulePresetsApplyService } from "src/time-and-attendance/schedule-presets/services/schedule-presets-apply.service";
import { SchedulePresetsGetService } from "src/time-and-attendance/schedule-presets/services/schedule-presets-get.service";
import { SchedulePresetsUpsertService } from "src/time-and-attendance/schedule-presets/services/schedule-presets-upsert.service";
// @Controller('schedule-presets')
// @RolesAllowed(...GLOBAL_CONTROLLER_ROLES)
// export class SchedulePresetsController {
// constructor(
// private readonly upsertService: SchedulePresetsUpsertService,
// private readonly getService: SchedulePresetsGetService,
// private readonly applyPresetsService: SchedulePresetsApplyService,
// ) { }
@Controller('schedule-presets')
@RolesAllowed(...GLOBAL_CONTROLLER_ROLES)
export class SchedulePresetsController {
constructor(
private readonly upsertService: SchedulePresetsUpsertService,
private readonly getService: SchedulePresetsGetService,
private readonly applyPresetsService: SchedulePresetsApplyService,
) { }
// //used to create a schedule preset
// @Post('create')
// used to create a schedule preset
@Post('create')
@RolesAllowed(...MANAGER_ROLES)
async createPreset(@Req() req, @Body() dto: SchedulePresetsDto) {
const email = req.user?.email;
return await this.upsertService.createPreset(email, dto);
}
// //used to update an already existing schedule preset
// @Patch('update/:preset_id')
// @RolesAllowed(...MANAGER_ROLES)
// async createPreset(@Req() req, @Body() dto: SchedulePresetsDto) {
// const email = req.user?.email;
// return await this.upsertService.createPreset(email, dto);
// async updatePreset(
// @Param('preset_id', ParseIntPipe) preset_id: number,
// @Body() dto: SchedulePresetsUpdateDto
// ) {
// return await this.upsertService.updatePreset(preset_id, dto);
// }
// // //used to update an already existing schedule preset
// // @Patch('update/:preset_id')
// // @RolesAllowed(...MANAGER_ROLES)
// // async updatePreset(
// // @Param('preset_id', ParseIntPipe) preset_id: number,
// // @Body() dto: SchedulePresetsUpdateDto
// // ) {
// // return await this.upsertService.updatePreset(preset_id, dto);
// // }
// //used to delete a schedule preset
//used to delete a schedule preset
// @Delete('delete/:preset_id')
// @RolesAllowed(...MANAGER_ROLES)
// async deletePreset(
@ -43,22 +43,24 @@
// }
// //used to show the list of available schedule presets
// @Get('find-list')
// @RolesAllowed(...MANAGER_ROLES)
// async findListById(@Req() req) {
// const email = req.user?.email;
// return this.getService.getSchedulePresets(email);
// }
//used to show the list of available schedule presets
@Get('find-list')
@RolesAllowed(...MANAGER_ROLES)
async findListById(
@Req() req
) {
const email = req.user?.email;
return this.getService.getSchedulePresets(email);
}
// //used to apply a preset to a timesheet
// @Post('apply-presets')
// async applyPresets(
// @Req() req,
// @Body('preset') preset_id: number,
// @Body('start') start_date: string
// ) {
// const email = req.user?.email;
// return this.applyPresetsService.applyToTimesheet(email, preset_id, start_date);
// }
// }
//used to apply a preset to a timesheet
@Post('apply-presets')
async applyPresets(
@Req() req,
@Body('preset') preset_id: number,
@Body('start') start_date: string
) {
const email = req.user?.email;
return this.applyPresetsService.applyToTimesheet(email, preset_id, start_date);
}
}

View File

@ -3,28 +3,11 @@ import { HH_MM_REGEX } from "src/common/utils/constants.utils";
import { Weekday } from "@prisma/client";
export class SchedulePresetShiftsDto {
@IsEnum(Weekday)
week_day!: Weekday;
@IsInt()
preset_id!: number;
@IsInt()
@Min(1)
sort_order!: number;
@IsString()
type!: string;
@IsString()
@Matches(HH_MM_REGEX)
start_time!: string;
@IsString()
@Matches(HH_MM_REGEX)
end_time!: string;
@IsOptional()
@IsBoolean()
is_remote?: boolean;
@IsInt() preset_id!: number;
@IsEnum(Weekday) week_day!: Weekday;
@IsInt() @Min(1) sort_order!: number;
@IsString() type!: string;
@IsString() @Matches(HH_MM_REGEX) start_time!: string;
@IsString() @Matches(HH_MM_REGEX) end_time!: string;
@IsOptional() @IsBoolean() is_remote?: boolean;
}

View File

@ -2,18 +2,8 @@ import { ArrayMinSize, IsArray, IsBoolean, IsInt, IsOptional, IsString } from "c
import { SchedulePresetShiftsDto } from "src/time-and-attendance/schedule-presets/dtos/create-schedule-preset-shifts.dto";
export class SchedulePresetsDto {
@IsInt()
id!: number;
@IsString()
name!: string;
@IsBoolean()
@IsOptional()
is_default: boolean;
@IsArray()
@ArrayMinSize(1)
preset_shifts: SchedulePresetShiftsDto[];
@IsInt() id!: number;
@IsString() name!: string;
@IsBoolean() @IsOptional() is_default: boolean;
@IsArray() @ArrayMinSize(1) preset_shifts: SchedulePresetShiftsDto[];
}

View File

@ -9,7 +9,10 @@ import { Result } from "src/common/errors/result-error.factory";
@Injectable()
export class SchedulePresetsApplyService {
constructor(private readonly prisma: PrismaService, private readonly emailResolver: EmailToIdResolver) { }
constructor(
private readonly prisma: PrismaService,
private readonly emailResolver: EmailToIdResolver
) { }
async applyToTimesheet(email: string, id: number, start_date_iso: string): Promise<Result<ApplyResult, string>> {
if (!DATE_ISO_FORMAT.test(start_date_iso)) return { success: false, error: 'start_date must be of format :YYYY-MM-DD' };

View File

@ -1,53 +1,97 @@
// import { Injectable, BadRequestException, NotFoundException, ConflictException } from "@nestjs/common";
// import { Prisma, Weekday } from "@prisma/client";
// import { PrismaService } from "src/prisma/prisma.service";
// import { BankCodesResolver } from "src/common/mappers/bank-type-id.mapper";
// import { EmailToIdResolver } from "src/common/mappers/email-id.mapper";
// import { Result } from "src/common/errors/result-error.factory";
// import { toHHmmFromDate, toDateFromString } from "src/common/utils/date-utils";
// import { SchedulePresetsDto } from "src/time-and-attendance/schedule-presets/dtos/create-schedule-presets.dto";
import { Injectable } from "@nestjs/common";
import { Weekday } from "@prisma/client";
import { PrismaService } from "src/prisma/prisma.service";
import { BankCodesResolver } from "src/common/mappers/bank-type-id.mapper";
import { EmailToIdResolver } from "src/common/mappers/email-id.mapper";
import { Result } from "src/common/errors/result-error.factory";
import { overlaps, toDateFromHHmm } from "src/common/utils/date-utils";
import { SchedulePresetsDto } from "src/time-and-attendance/schedule-presets/dtos/create-schedule-presets.dto";
// @Injectable()
// export class SchedulePresetsUpsertService {
// constructor(
// private readonly prisma: PrismaService,
// private readonly typeResolver: BankCodesResolver,
// private readonly emailResolver: EmailToIdResolver,
// ) { }
// //_________________________________________________________________
// // CREATE
// //_________________________________________________________________
// async createPreset(email: string, dto: SchedulePresetsDto): Promise<Result<SchedulePresetsDto, string>> {
// try {
// const shifts_data = await this.normalizePresetShifts(dto);
// if (!shifts_data.success) return { success: false, error: `Employee with email: ${email} or dto not found` };
@Injectable()
export class SchedulePresetsUpsertService {
constructor(
private readonly prisma: PrismaService,
private readonly typeResolver: BankCodesResolver,
private readonly emailResolver: EmailToIdResolver,
) { }
//_________________________________________________________________
// CREATE
//_________________________________________________________________
async createPreset(email: string, dto: SchedulePresetsDto): Promise<Result<boolean, string>> {
//validate email and fetch employee_id
const employee_id = await this.emailResolver.findIdByEmail(email);
if (!employee_id.success) return { success: false, error: employee_id.error };
// const employee_id = await this.emailResolver.findIdByEmail(email);
// if (!employee_id.success) return { success: false, error: employee_id.error };
//validate new unique name
const existing = await this.prisma.schedulePresets.findFirst({
where: { name: dto.name, employee_id: employee_id.data },
select: { name: true },
});
if (!existing) return { success: false, error: 'INVALID_SCHEDULE_PRESET' };
// const created = await this.prisma.$transaction(async (tx) => {
// if (dto.is_default) {
// await tx.schedulePresets.updateMany({
// where: { is_default: true, employee_id: employee_id.data },
// data: { is_default: false },
// });
// await tx.schedulePresets.create({
// data: {
// id: dto.id,
// employee_id: employee_id.data,
// name: dto.name,
// is_default: !!dto.is_default,
// shifts: { create: shifts_data.data },
// },
// });
// return { success: true, data: created }
// }
// });
// return { success: true, data: created }
// } catch (error) {
// return { success: false, error: ' An error occured during create. Invalid Schedule data' };
// }
// }
const normalized_shifts = dto.preset_shifts.map((shift) => ({
...shift,
start: toDateFromHHmm(shift.start_time),
end: toDateFromHHmm(shift.end_time),
}));
for (const preset_shifts of normalized_shifts) {
for (const other_shifts of normalized_shifts) {
//skip if same object or id week_day is not the same
if (preset_shifts === other_shifts) continue;
if (preset_shifts.week_day !== other_shifts.week_day) continue;
//check overlaping possibilities
const has_overlap = overlaps(
{ start: preset_shifts.start, end: preset_shifts.end },
{ start: other_shifts.start, end: other_shifts.end },
)
if (has_overlap) return { success: false, error: 'SCHEDULE_PRESET_OVERLAP' };
}
}
//validate bank_code_id/type and map them
const bank_code_results = await Promise.all(dto.preset_shifts.map((shift) =>
this.typeResolver.findBankCodeIDByType(shift.type),
));
for (const result of bank_code_results) {
if (!result.success) return { success: false, error: 'INVALID_SCHEDULE_PRESET' }
}
await this.prisma.$transaction(async (tx) => {
//check if employee chose this preset has a default preset and ensure all others are false
if (dto.is_default) {
await tx.schedulePresets.updateMany({
where: { employee_id: employee_id.data, is_default: true },
data: { is_default: false },
});
}
await tx.schedulePresets.create({
data: {
employee_id: employee_id.data,
name: dto.name,
is_default: dto.is_default ?? false,
shifts: {
create: dto.preset_shifts.map((shift, index) => {
//validated bank_codes sent as a Result Array to access its data
const result = bank_code_results[index] as { success: true, data: number };
return {
week_day: shift.week_day,
sort_order: shift.sort_order,
start_time: toDateFromHHmm(shift.start_time),
end_time: toDateFromHHmm(shift.end_time),
is_remote: shift.is_remote ?? false,
bank_code: {
//connect uses the FK links to set the bank_code_id
connect: { id: result.data },
},
}
}),
},
},
});
});
return { success: true, data: true }
}
// //_________________________________________________________________
// // UPDATE
@ -173,55 +217,24 @@
// //PRIVATE HELPERS
// //resolve bank_code_id using type and convert hours to TIME and valid shifts end/start
// private async normalizePresetShifts(
// dto: SchedulePresetsDto
// ): Promise<Result<Prisma.SchedulePresetShiftsCreateWithoutPresetInput[], string>> {
// if (!dto.preset_shifts?.length) return { success: false, error: `Empty or preset shifts not found` }
//resolve bank_code_id using type and convert hours to TIME and valid shifts end/start
// private async normalizePresetShifts(preset_shift: SchedulePresetShiftsDto, schedul_preset: SchedulePresetsDto): Promise<Result<Normalized, string>> {
// const types = Array.from(new Set(dto.preset_shifts.map((shift) => shift.type)));
// const bank_code_set = new Map<string, number>();
// const bank_code = await this.typeResolver.findIdAndModifierByType(preset_shift.type);
// if (!bank_code.success) return { success: false, error: 'INVALID_SCHEDULE_PRESET_SHIFT' };
// for (const type of types) {
// const bank_code = await this.typeResolver.findIdAndModifierByType(type);
// if (!bank_code.success) return { success: false, error: 'Bank_code not found' }
// bank_code_set.set(type, bank_code.data.id);
// }
// const start = await toDateFromHHmm(preset_shift.start_time);
// const end = await toDateFromHHmm(preset_shift.end_time);
// const pair_set = new Set<string>();
// for (const shift of dto.preset_shifts) {
// const key = `${shift.week_day}:${shift.sort_order}`;
// if (pair_set.has(key)) {
// return { success: false, error: `Duplicate shift for day/order (${shift.week_day}, ${shift.sort_order})` }
// }
// pair_set.add(key);
// }
// //TODO: add a way to fetch
// const items = await dto.preset_shifts.map((shift) => {
// try {
// const bank_code_id = bank_code_set.get(shift.type);
// if (!bank_code_id) return { success: false, error: `Bank code not found for type ${shift.type}` }
// if (!shift.start_time || !shift.end_time) {
// return { success: false, error: `start_time and end_time are required for (${shift.week_day}, ${shift.sort_order})` }
// }
// const start = toDateFromString(shift.start_time);
// const end = toDateFromString(shift.end_time);
// if (end.getTime() <= start.getTime()) {
// return { success: false, error: `end_time must be > start_time ( day: ${shift.week_day}, order: ${shift.sort_order})` }
// }
// return {
// sort_order: shift.sort_order,
// const normalized_preset_shift:Normalized = {
// date: ,
// start_time : start,
// end_time: end,
// is_remote: !!shift.is_remote,
// week_day: shift.week_day as Weekday,
// bank_code: { connect: { id: bank_code_id } },
// }
// } catch (error) {
// return { success: false, error: '' }
// }
// });
// return { success: true, data: items};
// bank_code_id: bank_code.data.id,
// }
// return { success: true data: normalized_preset_shift }
// }
}