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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 | import { Injectable, Logger } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { CalendarEvent, CalendarEventParticipant, WorkingCalendar, SharedHoliday } from './schemas'; export interface TimeSlot { startAt: Date; endAt: Date; } @Injectable() export class AvailabilityEngine { private readonly logger = new Logger(AvailabilityEngine.name); constructor( @InjectModel(CalendarEvent.name) private readonly eventModel: Model<CalendarEvent>, @InjectModel(CalendarEventParticipant.name) private readonly participantModel: Model<CalendarEventParticipant>, @InjectModel(WorkingCalendar.name) private readonly workingCalendarModel: Model<WorkingCalendar>, @InjectModel(SharedHoliday.name) private readonly holidayModel: Model<SharedHoliday> ) {} /** * Find busy times for a list of participants and resources within a range. */ async findBusyIntervals( tenantId: string, participantIds: string[], resourceIds: string[], startAt: Date, endAt: Date, privacyMask = true ): Promise<Array<{ startAt: Date; endAt: Date; title?: string }>> { const busySlots: Array<{ startAt: Date; endAt: Date; title?: string }> = []; // 1. Gather all events where participants are involved if (participantIds.length > 0) { const participantInvites = await this.participantModel.find({ tenantId, participantId: { $in: participantIds }, responseStatus: { $ne: 'declined' } }).exec(); const eventIds = participantInvites.map(i => i.eventId); if (eventIds.length > 0) { const events = await this.eventModel.find({ tenantId, eventId: { $in: eventIds }, startAt: { $lt: endAt }, endAt: { $gt: startAt }, status: { $nin: ['cancelled', 'declined'] } }).exec(); for (const event of events) { busySlots.push({ startAt: event.startAt, endAt: event.endAt, title: privacyMask && event.privacy === 'private' ? 'Busy' : event.title }); } } } // 2. Gather resource bookings if (resourceIds.length > 0) { const resourceEvents = await this.eventModel.find({ tenantId, startAt: { $lt: endAt }, endAt: { $gt: startAt }, status: { $nin: ['cancelled', 'declined'] }, $or: [ { calendarId: { $in: resourceIds } }, { 'metadata.resourceId': { $in: resourceIds } } ] }).exec(); for (const event of resourceEvents) { busySlots.push({ startAt: event.startAt, endAt: event.endAt, title: 'Resource Booked' }); } } // 3. Gather holidays in the range const holidays = await this.holidayModel.find({ tenantId, date: { $gte: startAt, $lte: endAt } }).exec(); for (const hol of holidays) { const holStart = new Date(hol.date); holStart.setUTCHours(0, 0, 0, 0); const holEnd = new Date(hol.date); holEnd.setUTCHours(23, 59, 59, 999); busySlots.push({ startAt: holStart, endAt: holEnd, title: hol.holidayName }); } return busySlots; } /** * Calculates free availability slots for a target duration, honoring working hours. */ async findAvailableSlots( tenantId: string, participantIds: string[], resourceIds: string[], startAt: Date, endAt: Date, durationMinutes: number, bufferMinutes = 0 ): Promise<TimeSlot[]> { const busy = await this.findBusyIntervals(tenantId, participantIds, resourceIds, startAt, endAt, true); // Sort busy slots busy.sort((a, b) => a.startAt.getTime() - b.startAt.getTime()); // Fetch working calendar to limit to working hours const workingCalendar = await this.workingCalendarModel.findOne({ tenantId, status: 'active' }).exec(); const freeSlots: TimeSlot[] = []; const stepMs = 15 * 60000; // Increment step const durationMs = durationMinutes * 60000; const bufferMs = bufferMinutes * 60000; let scanTime = new Date(startAt.getTime()); while (scanTime.getTime() + durationMs <= endAt.getTime()) { const slotStart = new Date(scanTime.getTime()); const slotEnd = new Date(scanTime.getTime() + durationMs); // Check if slot falls within working hours let isWorking = true; if (workingCalendar) { const dayOfWeek = slotStart.getUTCDay(); const rule = workingCalendar.workingDays.find(d => d.dayOfWeek === dayOfWeek); if (!rule || !rule.isWorkingDay) { isWorking = false; } else { // Check shifts/hours const timeStr = `${String(slotStart.getUTCHours()).padStart(2, '0')}:${String(slotStart.getUTCMinutes()).padStart(2, '0')}`; const inShift = rule.shifts.some(s => timeStr >= s.startTime && timeStr <= s.endTime); if (!inShift) isWorking = false; } } if (isWorking) { // Check conflicts with busy slots const hasConflict = busy.some(b => { const bStartWithBuffer = b.startAt.getTime() - bufferMs; const bEndWithBuffer = b.endAt.getTime() + bufferMs; return slotStart.getTime() < bEndWithBuffer && slotEnd.getTime() > bStartWithBuffer; }); if (!hasConflict) { freeSlots.push({ startAt: slotStart, endAt: slotEnd }); } } scanTime = new Date(scanTime.getTime() + stepMs); } return freeSlots; } } |