add booking
This commit is contained in:
@@ -23,6 +23,7 @@ import { EventException } from './entity/event-exception.entity';
|
||||
import { EventExceptionsModule } from './event-exception/event-exceptions.module';
|
||||
import { CalendarModule } from './calendar/calendar.module';
|
||||
import { Booking } from './entity/booking.entity';
|
||||
import { BookingsModule } from './booking/bookings.module';
|
||||
|
||||
const moduleTypeOrm = TypeOrmModule.forRootAsync({
|
||||
imports: [ConfigModule],
|
||||
@@ -44,7 +45,7 @@ const moduleTypeOrm = TypeOrmModule.forRootAsync({
|
||||
Event,
|
||||
RecurrenceRule,
|
||||
EventException,
|
||||
Booking
|
||||
Booking,
|
||||
],
|
||||
logging: true,
|
||||
// synchronize: true,
|
||||
@@ -67,6 +68,7 @@ const moduleTypeOrm = TypeOrmModule.forRootAsync({
|
||||
RecurrenceRulesModule,
|
||||
EventExceptionsModule,
|
||||
CalendarModule,
|
||||
BookingsModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
|
||||
63
server/src/booking/bookings.controller.ts
Normal file
63
server/src/booking/bookings.controller.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Body,
|
||||
Patch,
|
||||
Param,
|
||||
Delete,
|
||||
Query,
|
||||
ParseIntPipe,
|
||||
DefaultValuePipe,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { BookingsService } from './bookings.service';
|
||||
import { CreateBookingDto } from './dto/create-booking.dto';
|
||||
import { UpdateBookingDto } from './dto/update-booking.dto';
|
||||
import { QueryBookingDto } from './dto/query-booking.dto';
|
||||
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { Roles } from '../auth/roles.decorator';
|
||||
import { Role } from '../auth/role.enum';
|
||||
import { RolesGuard } from '../auth/roles.guard';
|
||||
|
||||
@Controller('bookings')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(Role.Admin)
|
||||
export class BookingsController {
|
||||
constructor(private readonly bookingsService: BookingsService) {}
|
||||
|
||||
@Post()
|
||||
create(@Body() createBookingDto: CreateBookingDto) {
|
||||
return this.bookingsService.create(createBookingDto);
|
||||
}
|
||||
|
||||
@Get()
|
||||
findAll(@Query() queryParams: QueryBookingDto) {
|
||||
return this.bookingsService.findAll(queryParams);
|
||||
}
|
||||
|
||||
@Get('search')
|
||||
search(
|
||||
@Query('q') term: string,
|
||||
@Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,
|
||||
@Query('limit', new DefaultValuePipe(10), ParseIntPipe) limit: number,
|
||||
) {
|
||||
return this.bookingsService.search(term, { page, limit });
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
findOne(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.bookingsService.findOne(id);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
update(@Param('id', ParseIntPipe) id: number, @Body() updateBookingDto: UpdateBookingDto) {
|
||||
return this.bookingsService.update(id, updateBookingDto);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
remove(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.bookingsService.remove(id);
|
||||
}
|
||||
}
|
||||
12
server/src/booking/bookings.module.ts
Normal file
12
server/src/booking/bookings.module.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { BookingsService } from './bookings.service';
|
||||
import { BookingsController } from './bookings.controller';
|
||||
import { Booking } from '../entity/booking.entity';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Booking])],
|
||||
controllers: [BookingsController],
|
||||
providers: [BookingsService],
|
||||
})
|
||||
export class BookingsModule {}
|
||||
128
server/src/booking/bookings.service.ts
Normal file
128
server/src/booking/bookings.service.ts
Normal file
@@ -0,0 +1,128 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository, FindManyOptions, FindOptionsWhere, ILike } from 'typeorm';
|
||||
import { CreateBookingDto } from './dto/create-booking.dto';
|
||||
import { UpdateBookingDto } from './dto/update-booking.dto';
|
||||
import { QueryBookingDto } from './dto/query-booking.dto';
|
||||
import { Booking } from '../entity/booking.entity';
|
||||
|
||||
type QueryConfigItem = {
|
||||
param: keyof Omit<QueryBookingDto, 'page' | 'limit' | 'sortBy' | 'order'>;
|
||||
dbField: keyof Booking;
|
||||
operator: 'equals' | 'like';
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class BookingsService {
|
||||
constructor(
|
||||
@InjectRepository(Booking)
|
||||
private readonly bookingRepository: Repository<Booking>,
|
||||
) {}
|
||||
|
||||
private readonly searchableFields: (keyof Booking)[] = [
|
||||
'notes',
|
||||
'canceledReason',
|
||||
];
|
||||
|
||||
create(createBookingDto: CreateBookingDto) {
|
||||
const newRecord = this.bookingRepository.create(createBookingDto);
|
||||
return this.bookingRepository.save(newRecord);
|
||||
}
|
||||
|
||||
async findAll(queryParams: QueryBookingDto) {
|
||||
const { page = 1, limit = 0, sortBy, order, ...filters } = queryParams;
|
||||
const queryConfig: QueryConfigItem[] = [];
|
||||
const whereClause: { [key: string]: any } = {};
|
||||
for (const config of queryConfig) {
|
||||
if (filters[config.param] !== undefined) {
|
||||
if (config.operator === 'like') {
|
||||
whereClause[config.dbField] = ILike(`%${filters[config.param]}%`);
|
||||
} else {
|
||||
whereClause[config.dbField] = filters[config.param];
|
||||
}
|
||||
}
|
||||
}
|
||||
const findOptions: FindManyOptions<Booking> = {
|
||||
where: whereClause as FindOptionsWhere<Booking>,
|
||||
};
|
||||
const paginated = limit > 0;
|
||||
if (paginated) {
|
||||
findOptions.skip = (page - 1) * limit;
|
||||
findOptions.take = limit;
|
||||
}
|
||||
if (sortBy && order) {
|
||||
findOptions.order = { [sortBy]: order };
|
||||
}
|
||||
const [data, totalItems] =
|
||||
await this.bookingRepository.findAndCount(findOptions);
|
||||
if (!paginated) {
|
||||
return { data, total: data.length };
|
||||
}
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
totalItems,
|
||||
itemCount: data.length,
|
||||
itemsPerPage: limit,
|
||||
totalPages: Math.ceil(totalItems / limit),
|
||||
currentPage: page,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async search(term: string, options: { page: number; limit: number }) {
|
||||
if (this.searchableFields.length === 0) {
|
||||
console.warn('Search is not configured for this entity.');
|
||||
return {
|
||||
data: [],
|
||||
meta: {
|
||||
totalItems: 0,
|
||||
itemCount: 0,
|
||||
itemsPerPage: options.limit,
|
||||
totalPages: 0,
|
||||
currentPage: options.page,
|
||||
},
|
||||
};
|
||||
}
|
||||
const whereConditions = this.searchableFields.map((field) => ({
|
||||
[field]: ILike(`%${term}%`),
|
||||
}));
|
||||
const [data, totalItems] = await this.bookingRepository.findAndCount({
|
||||
where: whereConditions,
|
||||
skip: (options.page - 1) * options.limit,
|
||||
take: options.limit,
|
||||
});
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
totalItems,
|
||||
itemCount: data.length,
|
||||
itemsPerPage: options.limit,
|
||||
totalPages: Math.ceil(totalItems / options.limit),
|
||||
currentPage: options.page,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async findOne(id: number) {
|
||||
const record = await this.bookingRepository.findOneBy({ id: id });
|
||||
if (!record) {
|
||||
throw new NotFoundException(`Booking with ID ${id} not found`);
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
async update(id: number, updateBookingDto: UpdateBookingDto) {
|
||||
const record = await this.findOne(id);
|
||||
Object.assign(record, updateBookingDto);
|
||||
return this.bookingRepository.save(record);
|
||||
}
|
||||
|
||||
async remove(id: number) {
|
||||
const result = await this.bookingRepository.delete(id);
|
||||
if (result.affected === 0) {
|
||||
throw new NotFoundException(`Booking with ID ${id} not found`);
|
||||
}
|
||||
return { deleted: true, id };
|
||||
}
|
||||
}
|
||||
4
server/src/booking/dto/create-booking.dto.ts
Normal file
4
server/src/booking/dto/create-booking.dto.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { OmitType } from '@nestjs/mapped-types';
|
||||
import { Booking } from '../../entity/booking.entity';
|
||||
|
||||
export class CreateBookingDto extends OmitType(Booking, ['id']) {}
|
||||
9
server/src/booking/dto/query-booking.dto.ts
Normal file
9
server/src/booking/dto/query-booking.dto.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { IsOptional, IsString, IsNumber, IsIn, IsBoolean } from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
export class QueryBookingDto {
|
||||
@IsOptional() @Type(() => Number) @IsNumber() page?: number;
|
||||
@IsOptional() @Type(() => Number) @IsNumber() limit?: number;
|
||||
@IsOptional() @IsString() sortBy?: string;
|
||||
@IsOptional() @IsIn(['ASC', 'DESC']) order?: 'ASC' | 'DESC';
|
||||
}
|
||||
4
server/src/booking/dto/update-booking.dto.ts
Normal file
4
server/src/booking/dto/update-booking.dto.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/mapped-types';
|
||||
import { CreateBookingDto } from './create-booking.dto';
|
||||
|
||||
export class UpdateBookingDto extends PartialType(CreateBookingDto) {}
|
||||
@@ -18,6 +18,8 @@ import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from '../auth/roles.guard';
|
||||
import { Roles } from '../auth/roles.decorator';
|
||||
import { Role } from '../auth/role.enum';
|
||||
import { CreateBookingDto } from './dto/create-booking.dto';
|
||||
import { CancelBookingDto } from './dto/cancel-booking.dto';
|
||||
|
||||
@Controller('calendar')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@@ -83,4 +85,22 @@ export class CalendarController {
|
||||
) {
|
||||
return this.calendarService.createException(eventId, createExceptionDto);
|
||||
}
|
||||
|
||||
// Create a booking for a specific event occurrence
|
||||
@Post('events/:id/bookings')
|
||||
createBooking(
|
||||
@Param('id', ParseIntPipe) eventId: number,
|
||||
@Body() createBookingDto: CreateBookingDto,
|
||||
) {
|
||||
return this.calendarService.createBooking(eventId, createBookingDto);
|
||||
}
|
||||
|
||||
// Cancel a specific booking (soft delete)
|
||||
@Patch('bookings/:bookingId/cancel')
|
||||
cancelBooking(
|
||||
@Param('bookingId', ParseIntPipe) bookingId: number,
|
||||
@Body() cancelBookingDto: CancelBookingDto,
|
||||
) {
|
||||
return this.calendarService.cancelBooking(bookingId, cancelBookingDto);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,9 +5,12 @@ import { CalendarController } from './calendar.controller';
|
||||
import { RecurrenceRule } from '../entity/recurrence-rule.entity';
|
||||
import { EventException } from '../entity/event-exception.entity';
|
||||
import { Event } from '../entity/event.entity';
|
||||
import { Booking } from '../entity/booking.entity';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([RecurrenceRule, EventException, Event])],
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([RecurrenceRule, EventException, Event, Booking]),
|
||||
],
|
||||
controllers: [CalendarController],
|
||||
providers: [CalendarService],
|
||||
})
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository, Between } from 'typeorm';
|
||||
import { RRule, Weekday } from 'rrule'; // Corrected import
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectDataSource, InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository, Between, IsNull, DataSource, In } from 'typeorm';
|
||||
import { RRule } from 'rrule'; // Corrected import
|
||||
|
||||
import { Event } from '../entity/event.entity';
|
||||
import { EventException } from '../entity/event-exception.entity';
|
||||
import { RecurrenceRule } from '../entity/recurrence-rule.entity';
|
||||
import { CreateEventDto } from './dto/create-event.dto';
|
||||
import { CreateExceptionDto } from './dto/create-exception.dto';
|
||||
|
||||
type CalendarEventDto = Event & {
|
||||
isModified?: boolean;
|
||||
};
|
||||
import { Booking } from '../entity/booking.entity';
|
||||
import { CancelBookingDto } from './dto/cancel-booking.dto';
|
||||
import { CreateBookingDto } from './dto/create-booking.dto';
|
||||
|
||||
// --- Type-Safe Maps ---
|
||||
const frequencyMap: Record<string, RRule.Frequency> = {
|
||||
@@ -31,60 +34,123 @@ const weekdayMap: Record<string, RRule.Weekday> = {
|
||||
SA: RRule.SA,
|
||||
};
|
||||
|
||||
// This is a minimal representation of the User entity for the DTO
|
||||
type BookingUserDto = {
|
||||
id: number;
|
||||
name: string; // Assuming user has a 'name' property
|
||||
email: string; // Assuming user has a 'name' property
|
||||
};
|
||||
|
||||
// This represents a booking with nested user info
|
||||
type BookingWithUserDto = {
|
||||
user: BookingUserDto | null;
|
||||
id: number;
|
||||
};
|
||||
|
||||
// The final shape of a calendar event occurrence
|
||||
export type CalendarEventDto = Omit<Event, 'bookings'> & {
|
||||
isModified?: boolean;
|
||||
eventBookings: BookingWithUserDto[];
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class CalendarService {
|
||||
constructor(
|
||||
@InjectDataSource()
|
||||
private readonly dataSource: DataSource,
|
||||
@InjectRepository(Event)
|
||||
private readonly eventRepository: Repository<Event>,
|
||||
@InjectRepository(RecurrenceRule)
|
||||
private readonly recurrenceRuleRepository: Repository<RecurrenceRule>,
|
||||
@InjectRepository(EventException)
|
||||
private readonly eventExceptionRepository: Repository<EventException>,
|
||||
@InjectRepository(Booking)
|
||||
private readonly bookingRepository: Repository<Booking>,
|
||||
) {}
|
||||
|
||||
async getEventsInRange(startDate: Date, endDate: Date): Promise<any[]> {
|
||||
// 1. Fetch single events
|
||||
async getEventsInRange(
|
||||
startDate: Date,
|
||||
endDate: Date,
|
||||
): Promise<CalendarEventDto[]> {
|
||||
// 1. Fetch active single events
|
||||
const singleEvents = await this.eventRepository.find({
|
||||
where: {
|
||||
isRecurring: false,
|
||||
startTime: Between(startDate, endDate),
|
||||
// status: EventStatus.ACTIVE,
|
||||
},
|
||||
relations: ['eventType'],
|
||||
});
|
||||
|
||||
// 2. Fetch recurring event templates
|
||||
// 2. Fetch active recurring event templates
|
||||
const recurringTemplates = await this.eventRepository.find({
|
||||
where: { isRecurring: true },
|
||||
where: {
|
||||
isRecurring: true,
|
||||
// status: EventStatus.ACTIVE,
|
||||
},
|
||||
relations: ['recurrenceRule', 'exceptions', 'eventType'],
|
||||
});
|
||||
|
||||
const recurringOccurrences: CalendarEventDto[] = [];
|
||||
if (recurringTemplates.length === 0 && singleEvents.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// 3. Expand recurring events
|
||||
// 3. Fetch all ACTIVE bookings for the relevant events and date range in a single query
|
||||
const eventIds = [
|
||||
...singleEvents.map((e) => e.id),
|
||||
...recurringTemplates.map((e) => e.id),
|
||||
];
|
||||
const allBookings = await this.bookingRepository.find({
|
||||
where: {
|
||||
eventId: In(eventIds),
|
||||
occurrenceStartTime: Between(startDate, endDate),
|
||||
canceledAt: IsNull(), // CRITICAL: Only fetch active bookings
|
||||
},
|
||||
relations: ['user'], // Eagerly load the related user data
|
||||
});
|
||||
|
||||
// 4. Create a Map for efficient lookup of bookings
|
||||
const bookingMap = new Map<string, BookingWithUserDto[]>();
|
||||
for (const booking of allBookings) {
|
||||
const key = `${booking.eventId}-${booking.occurrenceStartTime.getTime()}`;
|
||||
if (!bookingMap.has(key)) {
|
||||
bookingMap.set(key, []);
|
||||
}
|
||||
// Assuming user entity has name/email. Adjust as needed.
|
||||
const userDto: BookingUserDto | null = booking.user
|
||||
? { id: booking.user.id, name: 'User Name', email: 'user@email.com' }
|
||||
: null;
|
||||
bookingMap.get(key)!.push({ ...booking, user: userDto });
|
||||
}
|
||||
|
||||
// 5. Process single events and attach their bookings
|
||||
const singleOccurrences: CalendarEventDto[] = singleEvents.map((event) => {
|
||||
const key = `${event.id}-${event.startTime.getTime()}`;
|
||||
return {
|
||||
...event,
|
||||
eventBookings: bookingMap.get(key) || [],
|
||||
};
|
||||
});
|
||||
|
||||
// 6. Expand recurring events and attach their bookings
|
||||
const recurringOccurrences: CalendarEventDto[] = [];
|
||||
for (const event of recurringTemplates) {
|
||||
if (!event.recurrenceRule) continue;
|
||||
|
||||
const duration = event.endTime.getTime() - event.startTime.getTime();
|
||||
|
||||
const freq = frequencyMap[event.recurrenceRule.frequency];
|
||||
const byweekday = event.recurrenceRule.byDay
|
||||
?.split(',')
|
||||
.map((day) => weekdayMap[day])
|
||||
.filter((day): day is Weekday => !!day);
|
||||
.filter(Boolean);
|
||||
|
||||
if (freq === undefined) {
|
||||
console.error(
|
||||
`Invalid frequency for event ID ${event.id}: ${event.recurrenceRule.frequency}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (!freq) continue;
|
||||
|
||||
const rrule = new RRule({
|
||||
freq: freq,
|
||||
interval: event.recurrenceRule.interval,
|
||||
freq,
|
||||
dtstart: event.startTime,
|
||||
until: event.recurrenceRule.endDate,
|
||||
count: event.recurrenceRule.count,
|
||||
interval: event.recurrenceRule.interval,
|
||||
byweekday: byweekday?.length > 0 ? byweekday : undefined,
|
||||
});
|
||||
|
||||
@@ -96,29 +162,32 @@ export class CalendarService {
|
||||
);
|
||||
|
||||
if (exception) {
|
||||
if (exception.isCancelled) {
|
||||
continue;
|
||||
}
|
||||
if (exception.isCancelled) continue;
|
||||
|
||||
// This is a MODIFIED occurrence
|
||||
const key = `${event.id}-${exception.newStartTime.getTime()}`;
|
||||
recurringOccurrences.push({
|
||||
...event,
|
||||
id: event.id,
|
||||
title: exception.title || event.title,
|
||||
description: exception.description || event.description,
|
||||
startTime: exception.newStartTime,
|
||||
endTime: exception.newEndTime,
|
||||
isModified: true,
|
||||
eventBookings: bookingMap.get(key) || [],
|
||||
});
|
||||
} else {
|
||||
// This is a REGULAR occurrence
|
||||
const key = `${event.id}-${occurrenceDate.getTime()}`;
|
||||
recurringOccurrences.push({
|
||||
...event,
|
||||
startTime: occurrenceDate,
|
||||
endTime: new Date(occurrenceDate.getTime() + duration),
|
||||
eventBookings: bookingMap.get(key) || [],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const allEvents = [...singleEvents, ...recurringOccurrences];
|
||||
// 7. Combine and sort all results
|
||||
const allEvents = [...singleOccurrences, ...recurringOccurrences];
|
||||
return allEvents.sort(
|
||||
(a, b) => a.startTime.getTime() - b.startTime.getTime(),
|
||||
);
|
||||
@@ -147,17 +216,52 @@ export class CalendarService {
|
||||
eventId: number,
|
||||
createExceptionDto: CreateExceptionDto,
|
||||
): Promise<EventException> {
|
||||
const { originalStartTime, newStartTime } = createExceptionDto;
|
||||
|
||||
const event = await this.eventRepository.findOneBy({ id: eventId });
|
||||
if (!event) {
|
||||
throw new NotFoundException(`Event with ID ${eventId} not found`);
|
||||
}
|
||||
|
||||
const exception = this.eventExceptionRepository.create({
|
||||
...createExceptionDto,
|
||||
event: event,
|
||||
});
|
||||
// This logic now requires a transaction
|
||||
return this.dataSource.manager.transaction(
|
||||
async (transactionalEntityManager) => {
|
||||
// Step 1: Create and save the new exception
|
||||
const exception = transactionalEntityManager.create(EventException, {
|
||||
...createExceptionDto,
|
||||
event: event,
|
||||
});
|
||||
const savedException = await transactionalEntityManager.save(exception);
|
||||
|
||||
return this.eventExceptionRepository.save(exception);
|
||||
// Step 2: Check if this is a RESCHEDULE operation
|
||||
// A reschedule happens when there is a new start time.
|
||||
if (newStartTime) {
|
||||
// Step 3: Find all existing bookings for the ORIGINAL time
|
||||
const bookingsToMigrate = await transactionalEntityManager.find(
|
||||
Booking,
|
||||
{
|
||||
where: {
|
||||
eventId: eventId,
|
||||
occurrenceStartTime: originalStartTime,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
// Step 4: If we found any bookings, update their start time to the NEW time
|
||||
if (bookingsToMigrate.length > 0) {
|
||||
const bookingIds = bookingsToMigrate.map((b) => b.id);
|
||||
|
||||
await transactionalEntityManager.update(
|
||||
Booking,
|
||||
bookingIds, // Update these specific bookings
|
||||
{ occurrenceStartTime: newStartTime }, // Set their time to the new value
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return savedException;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async getEventById(id: number): Promise<Event> {
|
||||
@@ -185,4 +289,109 @@ export class CalendarService {
|
||||
throw new NotFoundException(`Event with ID ${id} not found.`);
|
||||
}
|
||||
}
|
||||
|
||||
async createBooking(
|
||||
eventId: number,
|
||||
createBookingDto: CreateBookingDto,
|
||||
): Promise<Booking> {
|
||||
const { occurrenceStartTime, userId } = createBookingDto;
|
||||
|
||||
const event = await this.eventRepository.findOneBy({ id: eventId });
|
||||
if (!event)
|
||||
throw new NotFoundException(`Event with ID ${eventId} not found.`);
|
||||
|
||||
// Business Rule: Prevent user from double-booking an active slot
|
||||
const existingBooking = await this.bookingRepository.findOne({
|
||||
where: {
|
||||
eventId,
|
||||
occurrenceStartTime,
|
||||
userId,
|
||||
canceledAt: IsNull(), // Only check for active bookings
|
||||
},
|
||||
});
|
||||
|
||||
if (existingBooking) {
|
||||
throw new BadRequestException(
|
||||
'This user already has an active booking for this time slot.',
|
||||
);
|
||||
}
|
||||
|
||||
// Validate that the occurrence is valid (same logic as before)
|
||||
const isOccurrenceValid = this.isValidOccurrence(
|
||||
event,
|
||||
occurrenceStartTime,
|
||||
);
|
||||
if (!isOccurrenceValid) {
|
||||
throw new BadRequestException(
|
||||
`The provided time is not a valid occurrence for this event.`,
|
||||
);
|
||||
}
|
||||
|
||||
// Create and save the new booking entity
|
||||
const newBooking = this.bookingRepository.create({
|
||||
...createBookingDto,
|
||||
eventId: event.id,
|
||||
});
|
||||
|
||||
return this.bookingRepository.save(newBooking);
|
||||
}
|
||||
|
||||
async cancelBooking(
|
||||
bookingId: number,
|
||||
cancelBookingDto: CancelBookingDto,
|
||||
): Promise<Booking> {
|
||||
const booking = await this.bookingRepository.findOneBy({ id: bookingId });
|
||||
if (!booking) {
|
||||
throw new NotFoundException(`Booking with ID ${bookingId} not found.`);
|
||||
}
|
||||
if (booking.canceledAt) {
|
||||
throw new BadRequestException('This booking has already been cancelled.');
|
||||
}
|
||||
|
||||
// Update the booking with cancellation details
|
||||
booking.canceledAt = new Date();
|
||||
booking.canceledReason = cancelBookingDto.canceledReason || null;
|
||||
booking.canceledByUserId = cancelBookingDto.canceledByUserId;
|
||||
|
||||
return this.bookingRepository.save(booking);
|
||||
}
|
||||
|
||||
private isValidOccurrence(event: Event, occurrenceTime: Date): boolean {
|
||||
// Check if the occurrence has been explicitly cancelled
|
||||
const exception = event.exceptions.find(
|
||||
(ex) => ex.originalStartTime.getTime() === occurrenceTime.getTime(),
|
||||
);
|
||||
if (exception && exception.isCancelled) {
|
||||
return false; // It was cancelled
|
||||
}
|
||||
|
||||
// If it's a single, non-recurring event
|
||||
if (!event.isRecurring) {
|
||||
return event.startTime.getTime() === occurrenceTime.getTime();
|
||||
}
|
||||
|
||||
// If it's a recurring event
|
||||
if (!event.recurrenceRule) return false; // Should not happen with good data
|
||||
|
||||
const freq = frequencyMap[event.recurrenceRule.frequency];
|
||||
// ... (weekdayMap logic from previous discussion)
|
||||
const byweekday = event.recurrenceRule.byDay
|
||||
?.split(',')
|
||||
.map((day) => weekdayMap[day])
|
||||
.filter(Boolean);
|
||||
|
||||
const rule = new RRule({
|
||||
freq,
|
||||
interval: event.recurrenceRule.interval,
|
||||
dtstart: event.startTime,
|
||||
until: event.recurrenceRule.endDate,
|
||||
count: event.recurrenceRule.count,
|
||||
byweekday: byweekday?.length > 0 ? byweekday : undefined,
|
||||
});
|
||||
|
||||
// Generate occurrences ONLY around the specific time to be efficient
|
||||
const nextOccurrence = rule.after(occurrenceTime, true); // `true` includes the date if it matches
|
||||
|
||||
return nextOccurrence?.getTime() === occurrenceTime.getTime();
|
||||
}
|
||||
}
|
||||
|
||||
18
server/src/calendar/dto/cancel-booking.dto.ts
Normal file
18
server/src/calendar/dto/cancel-booking.dto.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import {
|
||||
IsInt,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MaxLength,
|
||||
} from 'class-validator';
|
||||
|
||||
export class CancelBookingDto {
|
||||
@IsNotEmpty()
|
||||
@IsInt()
|
||||
canceledByUserId: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(50)
|
||||
canceledReason?: string;
|
||||
}
|
||||
29
server/src/calendar/dto/create-booking.dto.ts
Normal file
29
server/src/calendar/dto/create-booking.dto.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import {
|
||||
IsDate,
|
||||
IsInt,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
export class CreateBookingDto {
|
||||
@IsNotEmpty()
|
||||
@Type(() => Date)
|
||||
@IsDate()
|
||||
occurrenceStartTime: Date;
|
||||
|
||||
@IsNotEmpty()
|
||||
@IsInt()
|
||||
userId: number; // Replaces userName/userEmail
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
reservedSeatsCount?: number = 1;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
import { EventType } from './event-type.entity';
|
||||
import { RecurrenceRule } from './recurrence-rule.entity';
|
||||
import { EventException } from './event-exception.entity';
|
||||
import { Booking } from './booking.entity';
|
||||
|
||||
@Entity('events')
|
||||
export class Event {
|
||||
@@ -63,4 +64,9 @@ export class Event {
|
||||
cascade: true, // Automatically save/update exceptions when event is saved
|
||||
})
|
||||
exceptions: EventException[];
|
||||
}
|
||||
|
||||
@OneToMany(() => Booking, (booking) => booking.event, {
|
||||
cascade: true, // Automatically save/update exceptions when event is saved
|
||||
})
|
||||
bookings: Booking[];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user