From 03cf3f48a707674fd4a5e348c4e62a8123719af5 Mon Sep 17 00:00:00 2001 From: Ly Tuan Kiet Date: Fri, 17 Jan 2025 23:23:10 +0700 Subject: [PATCH] fix: refine schedule overlap validation in ScheduleSchema - Updated the logic for checking overlapping schedules by querying existing schedule dates for the same user, improving accuracy in overlap detection. - Simplified the overlap validation process by consolidating checks into a single function, enhancing code clarity and maintainability. - This change aims to strengthen the integrity of scheduling operations and provide clearer error messages for users regarding scheduling conflicts. --- src/Schedule/schedule.schema.ts | 53 ++++++++++----------------------- 1 file changed, 15 insertions(+), 38 deletions(-) diff --git a/src/Schedule/schedule.schema.ts b/src/Schedule/schedule.schema.ts index 058affe..7d436b1 100644 --- a/src/Schedule/schedule.schema.ts +++ b/src/Schedule/schedule.schema.ts @@ -492,51 +492,28 @@ d72a864e-2f41-45ab-9c9b-bf0512a31883,e9be51fd-2382-4e43-9988-74e76fde4b56,2024-1 throw new Error("Overlapping schedule"); } - // check if scheduleDate have overlap with other scheduleDate of same user - const existingUserScheduleDates = + // check if scheduleDate have overlap with other scheduleDate of same user by query all scheduleDate of same user + const existingScheduleDatesOfSameUser = await this.prisma.scheduleDate.findMany({ where: { - AND: [ - { - participantIds: { - has: ctx.me?.id ?? "", - }, + schedule: { + managedService: { + mentorId: ctx.me.id, }, - { - status: { - notIn: [ - ScheduleDateStatus.COMPLETED, - ScheduleDateStatus.EXPIRED, - ], - }, - }, - { - end: { - gte: DateTimeUtils.now().toJSDate(), - }, - }, - ], + }, }, }); - // First, generate the preview schedule dates - const previewScheduleDates = previewSchedule.slots.map((slot) => ({ - start: DateTimeUtils.fromIsoString(slot.start), - end: DateTimeUtils.fromIsoString(slot.end), - })); - - // Check if new schedule overlaps with any existing schedule dates for the user - const hasOverlap = existingUserScheduleDates.some((existingDate) => - previewScheduleDates.some((newScheduleDate) => - DateTimeUtils.isOverlap( - DateTimeUtils.fromDate(existingDate.start), - DateTimeUtils.fromDate(existingDate.end), - newScheduleDate.start, - newScheduleDate.end - ) - ) + const hasOverlap = DateTimeUtils.isOverlaps( + previewSchedule.slots.map((slot) => ({ + start: DateTimeUtils.fromIsoString(slot.start), + end: DateTimeUtils.fromIsoString(slot.end), + })), + existingScheduleDatesOfSameUser.map((date) => ({ + start: DateTimeUtils.fromDate(date.start), + end: DateTimeUtils.fromDate(date.end), + })) ); - if (hasOverlap) { throw new Error( "Schedule date has overlap with existing schedule dates"