refactor: streamline Booking module and service by removing unused imports and consolidating space validation logic

This commit is contained in:
faris Aljohari
2025-06-18 01:49:00 -06:00
parent df59e9a4a3
commit 274cdf741f
3 changed files with 55 additions and 75 deletions

View File

@ -1,16 +1,17 @@
import { Global, Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { BookableSpaceController } from './controllers';
import { BookableSpaceService } from './services';
import { BookableSpaceEntityRepository } from '@app/common/modules/booking/repositories';
import { BookableSpaceEntity } from '@app/common/modules/booking/entities';
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
import { SpaceRepository } from '@app/common/modules/space';
@Global()
@Module({
imports: [TypeOrmModule.forFeature([BookableSpaceEntity, SpaceEntity])],
controllers: [BookableSpaceController],
providers: [BookableSpaceService, BookableSpaceEntityRepository],
providers: [
BookableSpaceService,
BookableSpaceEntityRepository,
SpaceRepository,
],
exports: [BookableSpaceService],
})
export class BookingModule {}

View File

@ -1,7 +1,6 @@
// dtos/bookable-space.dto.ts
import { DaysEnum } from '@app/common/constants/days.enum';
import { ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import {
IsArray,
IsEnum,
@ -9,15 +8,26 @@ import {
IsString,
IsUUID,
IsInt,
ValidateNested,
ArrayMinSize,
ArrayMaxSize,
Min,
Max,
Min,
Matches,
} from 'class-validator';
export class BookingSlotDto {
export class CreateBookableSpaceDto {
@ApiProperty({
type: 'string',
isArray: true,
example: [
'3fa85f64-5717-4562-b3fc-2c963f66afa6',
'4fa85f64-5717-4562-b3fc-2c963f66afa7',
],
})
@IsArray()
@ArrayMinSize(1, { message: 'At least one space must be selected' })
@IsUUID('all', { each: true, message: 'Invalid space UUID provided' })
spaceUuids: string[];
@ApiProperty({
enum: DaysEnum,
isArray: true,
@ -25,7 +35,6 @@ export class BookingSlotDto {
})
@IsArray()
@ArrayMinSize(1, { message: 'At least one day must be selected' })
@ArrayMaxSize(7, { message: 'Cannot select more than 7 days' })
@IsEnum(DaysEnum, { each: true, message: 'Invalid day provided' })
daysAvailable: DaysEnum[];
@ -45,31 +54,9 @@ export class BookingSlotDto {
})
endTime: string;
@ApiProperty({ example: 10, minimum: 0 })
@ApiProperty({ example: 10 })
@IsInt()
@Min(0, { message: 'Points cannot be negative' })
@Max(1000, { message: 'Points cannot exceed 1000' })
points: number;
}
export class CreateBookableSpaceDto {
@ApiProperty({
type: 'string',
isArray: true,
example: [
'3fa85f64-5717-4562-b3fc-2c963f66afa6',
'4fa85f64-5717-4562-b3fc-2c963f66afa7',
],
})
@IsArray()
@ArrayMinSize(1, { message: 'At least one space must be selected' })
@IsUUID('all', { each: true, message: 'Invalid space UUID provided' })
spaceUuids: string[];
@ApiProperty({ type: BookingSlotDto, isArray: true })
@IsArray()
@ArrayMinSize(1, { message: 'At least one booking slot must be provided' })
@ValidateNested({ each: true })
@Type(() => BookingSlotDto)
slots: BookingSlotDto[];
}

View File

@ -1,50 +1,46 @@
// services/bookable-space.service.ts
import {
Injectable,
NotFoundException,
ConflictException,
BadRequestException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In } from 'typeorm';
import { BookingSlotDto, CreateBookableSpaceDto } from '../dtos';
import { CreateBookableSpaceDto } from '../dtos';
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
import { BookableSpaceEntity } from '@app/common/modules/booking/entities';
import { SpaceEntity } from '@app/common/modules/space/entities/space.entity';
import { BookableSpaceEntityRepository } from '@app/common/modules/booking/repositories';
import { SpaceRepository } from '@app/common/modules/space/repositories/space.repository';
import { In } from 'typeorm';
import { timeToMinutes } from '@app/common/helper/timeToMinutes';
@Injectable()
export class BookableSpaceService {
constructor(
@InjectRepository(BookableSpaceEntity)
private bookableRepo: Repository<BookableSpaceEntity>,
@InjectRepository(SpaceEntity)
private spaceRepo: Repository<SpaceEntity>,
private readonly bookableSpaceEntityRepository: BookableSpaceEntityRepository,
private readonly spaceRepository: SpaceRepository,
) {}
async create(dto: CreateBookableSpaceDto): Promise<BaseResponseDto> {
// Validate time slots first
this.validateTimeSlots(dto.slots);
this.validateTimeSlot(dto.startTime, dto.endTime);
// Validate spaces exist
const spaces = await this.validateSpacesExist(dto.spaceUuids);
// fetch spaces exist
const spaces = await this.getSpacesOrFindMissing(dto.spaceUuids);
// Validate no duplicate bookable configurations
await this.validateNoDuplicateBookableConfigs(dto.spaceUuids);
// Create and save bookable spaces
return this.createBookableSpaces(spaces, dto.slots);
return this.createBookableSpaces(spaces, dto);
}
/**
* Validate that all specified spaces exist
* Fetch spaces by UUIDs and throw an error if any are missing
*/
private async validateSpacesExist(
private async getSpacesOrFindMissing(
spaceUuids: string[],
): Promise<SpaceEntity[]> {
const spaces = await this.spaceRepo.find({
const spaces = await this.spaceRepository.find({
where: { uuid: In(spaceUuids) },
});
@ -67,7 +63,7 @@ export class BookableSpaceService {
private async validateNoDuplicateBookableConfigs(
spaceUuids: string[],
): Promise<void> {
const existingBookables = await this.bookableRepo.find({
const existingBookables = await this.bookableSpaceEntityRepository.find({
where: { space: { uuid: In(spaceUuids) } },
relations: ['space'],
});
@ -83,19 +79,17 @@ export class BookableSpaceService {
}
/**
* Validate time slots have valid format and logical times
* Ensure the slot start time is before the end time
*/
private validateTimeSlots(slots: BookingSlotDto[]): void {
slots.forEach((slot) => {
const start = timeToMinutes(slot.startTime);
const end = timeToMinutes(slot.endTime);
private validateTimeSlot(startTime: string, endTime: string): void {
const start = timeToMinutes(startTime);
const end = timeToMinutes(endTime);
if (start >= end) {
throw new BadRequestException(
`End time must be after start time for slot: ${slot.startTime}-${slot.endTime}`,
`End time must be after start time for slot: ${startTime}-${endTime}`,
);
}
});
}
/**
@ -103,22 +97,20 @@ export class BookableSpaceService {
*/
private async createBookableSpaces(
spaces: SpaceEntity[],
slots: BookingSlotDto[],
dto: CreateBookableSpaceDto,
): Promise<BaseResponseDto> {
try {
const entries = spaces.flatMap((space) =>
slots.map((slot) =>
this.bookableRepo.create({
const entries = spaces.map((space) =>
this.bookableSpaceEntityRepository.create({
space,
daysAvailable: slot.daysAvailable,
startTime: slot.startTime,
endTime: slot.endTime,
points: slot.points,
daysAvailable: dto.daysAvailable,
startTime: dto.startTime,
endTime: dto.endTime,
points: dto.points,
}),
),
);
const data = await this.bookableRepo.save(entries);
const data = await this.bookableSpaceEntityRepository.save(entries);
return new SuccessResponseDto({
data,
message: 'Successfully added new bookable spaces',