add event object
This commit is contained in:
@@ -13,6 +13,8 @@ import { EventType } from './entity/event-type.entity';
|
||||
import { EventTypesModule } from './event-type/event-type.module';
|
||||
import { Product } from './entity/product.entity';
|
||||
import { ProductsModule } from './product/products.module';
|
||||
import { Event } from "./entity/event.entity";
|
||||
import { EventsModule } from "./event/events.module";
|
||||
|
||||
const moduleTypeOrm = TypeOrmModule.forRootAsync({
|
||||
imports: [ConfigModule],
|
||||
@@ -25,7 +27,7 @@ const moduleTypeOrm = TypeOrmModule.forRootAsync({
|
||||
username: configService.get<string>('DATABASE_USER'),
|
||||
password: configService.get<string>('DATABASE_PASS'),
|
||||
database: configService.get<string>('DATABASE_NAME'),
|
||||
entities: [User, UserGroup, UserRole, EventType, Product],
|
||||
entities: [User, UserGroup, UserRole, EventType, Product, Event],
|
||||
logging: true,
|
||||
// synchronize: true,
|
||||
};
|
||||
@@ -41,7 +43,8 @@ const moduleTypeOrm = TypeOrmModule.forRootAsync({
|
||||
LoggerModule,
|
||||
EventTypesModule,
|
||||
ProductsModule,
|
||||
],
|
||||
EventsModule
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
})
|
||||
|
||||
54
server/src/entity/event.entity.ts
Normal file
54
server/src/entity/event.entity.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
// dvbooking-cli/src/templates/nestjs/entity.ts.tpl
|
||||
|
||||
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
|
||||
import {
|
||||
IsString,
|
||||
IsNumber,
|
||||
IsBoolean,
|
||||
IsDate,
|
||||
IsOptional,
|
||||
} from 'class-validator';
|
||||
|
||||
@Entity({ name: 'events' })
|
||||
export class Event {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ type: 'bigint', nullable: true })
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
event_type_id: number | null;
|
||||
|
||||
@Column()
|
||||
@IsString()
|
||||
title: string;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description: string | null;
|
||||
|
||||
@Column()
|
||||
@IsDate()
|
||||
start_time: Date;
|
||||
|
||||
@Column()
|
||||
@IsDate()
|
||||
end_time: Date;
|
||||
|
||||
@Column()
|
||||
@IsString()
|
||||
timezone: string;
|
||||
|
||||
@Column({ default: false })
|
||||
@IsBoolean()
|
||||
is_recurring: boolean = false;
|
||||
|
||||
@Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
|
||||
@IsDate()
|
||||
created_at: Date;
|
||||
|
||||
@Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
|
||||
@IsDate()
|
||||
updated_at: Date;
|
||||
}
|
||||
4
server/src/event/dto/create-event.dto.ts
Normal file
4
server/src/event/dto/create-event.dto.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { OmitType } from '@nestjs/mapped-types';
|
||||
import { Event } from '../../entity/event.entity';
|
||||
|
||||
export class CreateEventDto extends OmitType(Event, ['id']) {}
|
||||
9
server/src/event/dto/query-event.dto.ts
Normal file
9
server/src/event/dto/query-event.dto.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { IsOptional, IsString, IsNumber, IsIn, IsBoolean } from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
export class QueryEventDto {
|
||||
@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/event/dto/update-event.dto.ts
Normal file
4
server/src/event/dto/update-event.dto.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/mapped-types';
|
||||
import { CreateEventDto } from './create-event.dto';
|
||||
|
||||
export class UpdateEventDto extends PartialType(CreateEventDto) {}
|
||||
63
server/src/event/events.controller.ts
Normal file
63
server/src/event/events.controller.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Body,
|
||||
Patch,
|
||||
Param,
|
||||
Delete,
|
||||
Query,
|
||||
ParseIntPipe,
|
||||
DefaultValuePipe,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { EventsService } from './events.service';
|
||||
import { CreateEventDto } from './dto/create-event.dto';
|
||||
import { UpdateEventDto } from './dto/update-event.dto';
|
||||
import { QueryEventDto } from './dto/query-event.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('events')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles(Role.Admin)
|
||||
export class EventsController {
|
||||
constructor(private readonly eventsService: EventsService) {}
|
||||
|
||||
@Post()
|
||||
create(@Body() createEventDto: CreateEventDto) {
|
||||
return this.eventsService.create(createEventDto);
|
||||
}
|
||||
|
||||
@Get()
|
||||
findAll(@Query() queryParams: QueryEventDto) {
|
||||
return this.eventsService.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.eventsService.search(term, { page, limit });
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
findOne(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.eventsService.findOne(id);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
update(@Param('id', ParseIntPipe) id: number, @Body() updateEventDto: UpdateEventDto) {
|
||||
return this.eventsService.update(id, updateEventDto);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
remove(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.eventsService.remove(id);
|
||||
}
|
||||
}
|
||||
12
server/src/event/events.module.ts
Normal file
12
server/src/event/events.module.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { EventsService } from './events.service';
|
||||
import { EventsController } from './events.controller';
|
||||
import { Event } from '../entity/event.entity';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Event])],
|
||||
controllers: [EventsController],
|
||||
providers: [EventsService],
|
||||
})
|
||||
export class EventsModule {}
|
||||
103
server/src/event/events.service.ts
Normal file
103
server/src/event/events.service.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository, FindManyOptions, FindOptionsWhere, ILike } from 'typeorm';
|
||||
import { CreateEventDto } from './dto/create-event.dto';
|
||||
import { UpdateEventDto } from './dto/update-event.dto';
|
||||
import { QueryEventDto } from './dto/query-event.dto';
|
||||
import { Event } from '../entity/event.entity';
|
||||
|
||||
type QueryConfigItem = {
|
||||
param: keyof Omit<QueryEventDto, 'page' | 'limit' | 'sortBy' | 'order'>;
|
||||
dbField: keyof Event;
|
||||
operator: 'equals' | 'like';
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class EventsService {
|
||||
constructor(
|
||||
@InjectRepository(Event)
|
||||
private readonly eventRepository: Repository<Event>,
|
||||
) {}
|
||||
|
||||
private readonly searchableFields: (keyof Event)[] = [
|
||||
'title',
|
||||
'description',
|
||||
'timezone'
|
||||
];
|
||||
|
||||
create(createEventDto: CreateEventDto) {
|
||||
const newRecord = this.eventRepository.create(createEventDto);
|
||||
return this.eventRepository.save(newRecord);
|
||||
}
|
||||
|
||||
async findAll(queryParams: QueryEventDto) {
|
||||
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<Event> = { where: whereClause as FindOptionsWhere<Event> };
|
||||
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.eventRepository.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.eventRepository.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.eventRepository.findOneBy({ id: id as any });
|
||||
if (!record) {
|
||||
throw new NotFoundException(`Event with ID ${id} not found`);
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
async update(id: number, updateEventDto: UpdateEventDto) {
|
||||
const record = await this.findOne(id);
|
||||
Object.assign(record, updateEventDto);
|
||||
return this.eventRepository.save(record);
|
||||
}
|
||||
|
||||
async remove(id: number) {
|
||||
const result = await this.eventRepository.delete(id);
|
||||
if (result.affected === 0) {
|
||||
throw new NotFoundException(`Event with ID ${id} not found`);
|
||||
}
|
||||
return { deleted: true, id };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
export class AddEventRelatedTable1763106308122 implements MigrationInterface {
|
||||
name = 'AddEventRelatedTable1763106308122';
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE events (
|
||||
id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
|
||||
event_type_id BIGINT, -- This is the new nullable foreign key column.
|
||||
title VARCHAR(255) NOT NULL,
|
||||
description TEXT,
|
||||
start_time TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
end_time TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
timezone VARCHAR(50) NOT NULL,
|
||||
is_recurring BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
FOREIGN KEY (event_type_id) REFERENCES event_type(id) ON DELETE SET NULL
|
||||
);`,
|
||||
);
|
||||
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE recurrence_rules (
|
||||
id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
|
||||
event_id BIGINT NOT NULL,
|
||||
frequency VARCHAR(10) NOT NULL,
|
||||
interval INTEGER NOT NULL DEFAULT 1,
|
||||
end_date DATE,
|
||||
count INTEGER,
|
||||
by_day VARCHAR(20),
|
||||
by_month_day INTEGER,
|
||||
by_month INTEGER,
|
||||
FOREIGN KEY (event_id) REFERENCES events(id) ON DELETE CASCADE
|
||||
);`,
|
||||
);
|
||||
|
||||
await queryRunner.query(
|
||||
`CREATE TABLE event_exceptions (
|
||||
id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
|
||||
event_id BIGINT NOT NULL,
|
||||
original_start_time TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
is_cancelled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
new_start_time TIMESTAMP WITH TIME ZONE,
|
||||
new_end_time TIMESTAMP WITH TIME ZONE,
|
||||
title VARCHAR(255),
|
||||
description TEXT,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
FOREIGN KEY (event_id) REFERENCES events(id) ON DELETE CASCADE
|
||||
);`,
|
||||
);
|
||||
|
||||
await queryRunner.query(
|
||||
`CREATE INDEX idx_events_event_type_id ON events (event_type_id);`,
|
||||
);
|
||||
|
||||
await queryRunner.query(
|
||||
`CREATE INDEX idx_recurrence_rules_event_id ON recurrence_rules (event_id);`,
|
||||
);
|
||||
|
||||
await queryRunner.query(
|
||||
`CREATE INDEX idx_event_exceptions_event_id ON event_exceptions (event_id);`,
|
||||
);
|
||||
await queryRunner.query(
|
||||
`CREATE INDEX idx_event_exceptions_original_start_time ON event_exceptions (original_start_time);`,
|
||||
);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`DROP TABLE "event_type"`);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user