add booking
This commit is contained in:
parent
085605f85c
commit
02cad3dbcd
@ -33,9 +33,53 @@ import {
|
||||
} from './features/user-role/components/user-role-details/user-role-details.component';
|
||||
import { UserRoleTableComponent } from './features/user-role/components/user-role-table/user-role-table.component';
|
||||
import { UserRoleListComponent } from './features/user-role/components/user-role-list/user-role-list.component';
|
||||
import { BookingFormComponent } from "./features/bookings/components/booking-form/booking-form.component";
|
||||
import { BookingDetailsComponent } from "./features/bookings/components/booking-details/booking-details.component";
|
||||
import { BookingTableComponent } from "./features/bookings/components/booking-table/booking-table.component";
|
||||
import { BookingListComponent } from "./features/bookings/components/booking-list/booking-list.component";
|
||||
|
||||
export const routes: Routes = [
|
||||
{
|
||||
{
|
||||
path: 'bookings/new',
|
||||
component: BookingFormComponent,
|
||||
canActivate: [AuthGuard],
|
||||
data: {
|
||||
roles: ['admin'],
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'bookings',
|
||||
component: BookingListComponent,
|
||||
canActivate: [AuthGuard],
|
||||
data: {
|
||||
roles: ['admin'],
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'bookings/table',
|
||||
component: BookingTableComponent,
|
||||
canActivate: [AuthGuard],
|
||||
data: {
|
||||
roles: ['admin'],
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'bookings/:id',
|
||||
component: BookingDetailsComponent,
|
||||
canActivate: [AuthGuard],
|
||||
data: {
|
||||
roles: ['admin'],
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'bookings/:id/edit',
|
||||
component: BookingFormComponent,
|
||||
canActivate: [AuthGuard],
|
||||
data: {
|
||||
roles: ['admin'],
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'user-role/new',
|
||||
component: UserRoleFormComponent,
|
||||
canActivate: [AuthGuard],
|
||||
|
||||
@ -0,0 +1,74 @@
|
||||
<!-- dvbooking-cli/src/templates/angular/details.component.html.tpl -->
|
||||
|
||||
<!-- Generated by the CLI -->
|
||||
<div class="p-4 md:p-8">
|
||||
<ng-container *ngIf="booking$ | async as booking; else loading">
|
||||
<div class="card bg-base-100 shadow-xl max-w-2xl mx-auto">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title text-3xl">Booking Details</h2>
|
||||
|
||||
<div class="overflow-x-auto mt-4">
|
||||
<table class="table w-full">
|
||||
<tbody>
|
||||
<tr>
|
||||
<th>id</th>
|
||||
<td>{{ booking.id }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>event_id</th>
|
||||
<td>{{ booking.event_id }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>occurrence_start_time</th>
|
||||
<td>{{ booking.occurrence_start_time }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>user_id</th>
|
||||
<td>{{ booking.user_id }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>notes</th>
|
||||
<td>{{ booking.notes }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>reserved_seats_count</th>
|
||||
<td>{{ booking.reserved_seats_count }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>created_at</th>
|
||||
<td>{{ booking.created_at }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>updated_at</th>
|
||||
<td>{{ booking.updated_at }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>canceled_at</th>
|
||||
<td>{{ booking.canceled_at }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>canceled_reason</th>
|
||||
<td>{{ booking.canceled_reason }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>canceled_by_user_id</th>
|
||||
<td>{{ booking.canceled_by_user_id }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="card-actions justify-end mt-6">
|
||||
<a routerLink="/bookings" class="btn btn-secondary">Back to List</a>
|
||||
<a routerLink="/bookings/{{ booking.id }}/edit" class="btn btn-primary">Edit</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
|
||||
<ng-template #loading>
|
||||
<div class="text-center p-8">
|
||||
<span class="loading loading-spinner loading-lg"></span>
|
||||
</div>
|
||||
</ng-template>
|
||||
</div>
|
||||
@ -0,0 +1,34 @@
|
||||
// dvbooking-cli/src/templates/angular/details.component.ts.tpl
|
||||
|
||||
// Generated by the CLI
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { ActivatedRoute, RouterModule } from '@angular/router';
|
||||
import { Observable } from 'rxjs';
|
||||
import { switchMap } from 'rxjs/operators';
|
||||
import { Booking } from '../../models/booking.model';
|
||||
import { BookingService } from '../../services/booking.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-booking-details',
|
||||
templateUrl: './booking-details.component.html',
|
||||
standalone: true,
|
||||
imports: [CommonModule, RouterModule],
|
||||
})
|
||||
export class BookingDetailsComponent implements OnInit {
|
||||
booking$!: Observable<Booking>;
|
||||
|
||||
constructor(
|
||||
private route: ActivatedRoute,
|
||||
private bookingService: BookingService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.booking$ = this.route.params.pipe(
|
||||
switchMap(params => {
|
||||
const id = params['id'];
|
||||
return this.bookingService.findOne(id);
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,15 @@
|
||||
<!-- dvbooking-cli/src/templates/angular/filter.component.html.tpl -->
|
||||
<!-- Generated by the CLI -->
|
||||
<form [formGroup]="filterForm" class="p-4 bg-base-200 rounded-lg shadow">
|
||||
<div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
|
||||
<div class="form-control"><label class="label"><span class="label-text">notes</span></label>
|
||||
<input type="text" formControlName="notes" class="input input-bordered w-full" placeholder="Filter by notes" /></div>
|
||||
|
||||
<div class="form-control"><label class="label"><span class="label-text">canceled_reason</span></label>
|
||||
<input type="text" formControlName="canceled_reason" class="input input-bordered w-full" placeholder="Filter by canceled_reason" /></div>
|
||||
|
||||
<div class="form-control">
|
||||
<button type="button" (click)="reset()" class="btn btn-secondary">Reset</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@ -0,0 +1,38 @@
|
||||
// dvbooking-cli/src/templates/angular/filter.component.ts.tpl
|
||||
|
||||
// Generated by the CLI
|
||||
import { Component, EventEmitter, Output } from '@angular/core';
|
||||
import { FormBuilder, FormGroup, ReactiveFormsModule } from '@angular/forms';
|
||||
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
|
||||
|
||||
@Component({
|
||||
selector: 'app-booking-filter',
|
||||
templateUrl: './booking-filter.component.html',
|
||||
standalone: true,
|
||||
imports: [ReactiveFormsModule]
|
||||
})
|
||||
export class BookingFilterComponent {
|
||||
@Output() filterChanged = new EventEmitter<any>();
|
||||
filterForm: FormGroup;
|
||||
|
||||
constructor(private fb: FormBuilder) {
|
||||
this.filterForm = this.fb.group({
|
||||
notes: [''],
|
||||
canceled_reason: ['']
|
||||
});
|
||||
|
||||
this.filterForm.valueChanges.pipe(
|
||||
debounceTime(300),
|
||||
distinctUntilChanged()
|
||||
).subscribe(values => {
|
||||
const cleanFilter = Object.fromEntries(
|
||||
Object.entries(values).filter(([_, v]) => v != null && v !== '')
|
||||
);
|
||||
this.filterChanged.emit(cleanFilter);
|
||||
});
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.filterForm.reset();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,52 @@
|
||||
<!-- dvbooking-cli/src/templates/angular/form.component.html.tpl -->
|
||||
|
||||
<!-- Generated by the CLI -->
|
||||
<div class="p-4 md:p-8">
|
||||
<div class="card bg-base-100 shadow-xl max-w-2xl mx-auto">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title text-3xl">
|
||||
{{ isEditMode ? 'Edit' : 'Create' }} Booking
|
||||
</h2>
|
||||
|
||||
<form [formGroup]="form" (ngSubmit)="onSubmit()" class="space-y-4 mt-4">
|
||||
|
||||
<div class="form-control"><label class="label"><span class="label-text">event_id</span></label>
|
||||
<input type="number" formControlName="event_id" class="input input-bordered w-full" /></div>
|
||||
|
||||
<div class="form-control"><label class="label"><span class="label-text">occurrence_start_time</span></label>
|
||||
<input type="text" formControlName="occurrence_start_time" class="input input-bordered w-full" /></div>
|
||||
|
||||
<div class="form-control"><label class="label"><span class="label-text">user_id</span></label>
|
||||
<input type="number" formControlName="user_id" class="input input-bordered w-full" /></div>
|
||||
|
||||
<div class="form-control"><label class="label"><span class="label-text">notes</span></label>
|
||||
<input type="text" formControlName="notes" class="input input-bordered w-full" /></div>
|
||||
|
||||
<div class="form-control"><label class="label"><span class="label-text">reserved_seats_count</span></label>
|
||||
<input type="number" formControlName="reserved_seats_count" class="input input-bordered w-full" /></div>
|
||||
|
||||
<div class="form-control"><label class="label"><span class="label-text">created_at</span></label>
|
||||
<input type="text" formControlName="created_at" class="input input-bordered w-full" /></div>
|
||||
|
||||
<div class="form-control"><label class="label"><span class="label-text">updated_at</span></label>
|
||||
<input type="text" formControlName="updated_at" class="input input-bordered w-full" /></div>
|
||||
|
||||
<div class="form-control"><label class="label"><span class="label-text">canceled_at</span></label>
|
||||
<input type="text" formControlName="canceled_at" class="input input-bordered w-full" /></div>
|
||||
|
||||
<div class="form-control"><label class="label"><span class="label-text">canceled_reason</span></label>
|
||||
<input type="text" formControlName="canceled_reason" class="input input-bordered w-full" /></div>
|
||||
|
||||
<div class="form-control"><label class="label"><span class="label-text">canceled_by_user_id</span></label>
|
||||
<input type="number" formControlName="canceled_by_user_id" class="input input-bordered w-full" /></div>
|
||||
|
||||
<div class="card-actions justify-end mt-6">
|
||||
<a routerLink="/bookings" class="btn btn-ghost">Cancel</a>
|
||||
<button type="submit" class="btn btn-primary" [disabled]="form.invalid">
|
||||
{{ isEditMode ? 'Update' : 'Create' }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@ -0,0 +1,94 @@
|
||||
// dvbooking-cli/src/templates/angular/form.component.ts.tpl
|
||||
|
||||
// Generated by the CLI
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
|
||||
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { switchMap, tap } from 'rxjs/operators';
|
||||
import { Booking } from '../../models/booking.model';
|
||||
import { BookingService } from '../../services/booking.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-booking-form',
|
||||
templateUrl: './booking-form.component.html',
|
||||
standalone: true,
|
||||
imports: [CommonModule, ReactiveFormsModule, RouterModule],
|
||||
})
|
||||
export class BookingFormComponent implements OnInit {
|
||||
form: FormGroup;
|
||||
isEditMode = false;
|
||||
id: number | null = null;
|
||||
|
||||
private numericFields = ["event_id","user_id","reserved_seats_count","canceled_by_user_id"];
|
||||
|
||||
constructor(
|
||||
private fb: FormBuilder,
|
||||
private route: ActivatedRoute,
|
||||
private router: Router,
|
||||
private bookingService: BookingService
|
||||
) {
|
||||
this.form = this.fb.group({
|
||||
event_id: [null],
|
||||
occurrence_start_time: [null],
|
||||
user_id: [null],
|
||||
notes: [null],
|
||||
reserved_seats_count: [null],
|
||||
created_at: [null],
|
||||
updated_at: [null],
|
||||
canceled_at: [null],
|
||||
canceled_reason: [null],
|
||||
canceled_by_user_id: [null]
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.route.params.pipe(
|
||||
tap(params => {
|
||||
if (params['id']) {
|
||||
this.isEditMode = true;
|
||||
this.id = +params['id'];
|
||||
}
|
||||
}),
|
||||
switchMap(() => {
|
||||
if (this.isEditMode && this.id) {
|
||||
return this.bookingService.findOne(this.id);
|
||||
}
|
||||
return of(null);
|
||||
})
|
||||
).subscribe(booking => {
|
||||
if (booking) {
|
||||
this.form.patchValue(booking);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onSubmit(): void {
|
||||
if (this.form.invalid) {
|
||||
this.form.markAllAsTouched();
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = { ...this.form.value };
|
||||
|
||||
for (const field of this.numericFields) {
|
||||
if (payload[field] != null && payload[field] !== '') {
|
||||
payload[field] = parseFloat(payload[field]);
|
||||
}
|
||||
}
|
||||
|
||||
let action$: Observable<Booking>;
|
||||
|
||||
if (this.isEditMode && this.id) {
|
||||
action$ = this.bookingService.update(this.id, payload);
|
||||
} else {
|
||||
action$ = this.bookingService.create(payload);
|
||||
}
|
||||
|
||||
action$.subscribe({
|
||||
next: () => this.router.navigate(['/bookings']),
|
||||
error: (err) => console.error('Failed to save booking', err)
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,78 @@
|
||||
<!-- dvbooking-cli/src/templates/angular/list.component.html.tpl -->
|
||||
|
||||
<!-- Generated by the CLI -->
|
||||
<div class="p-4 md:p-8 space-y-6">
|
||||
<div class="flex justify-between items-center">
|
||||
<h1 class="text-3xl font-bold">Bookings</h1>
|
||||
<a routerLink="/bookings/new" class="btn btn-primary">Create New</a>
|
||||
</div>
|
||||
|
||||
<app-booking-filter (filterChanged)="onFilterChanged($event)"></app-booking-filter>
|
||||
|
||||
<ng-container *ngIf="paginatedResponse$ | async as response; else loading">
|
||||
<div class="overflow-x-auto bg-base-100 rounded-lg shadow">
|
||||
<table class="table w-full">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>id</th>
|
||||
<th>event_id</th>
|
||||
<th>occurrence_start_time</th>
|
||||
<th>user_id</th>
|
||||
<th>notes</th>
|
||||
<th>reserved_seats_count</th>
|
||||
<th>created_at</th>
|
||||
<th>updated_at</th>
|
||||
<th>canceled_at</th>
|
||||
<th>canceled_reason</th>
|
||||
<th>canceled_by_user_id</th>
|
||||
<th class="text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr *ngFor="let item of response.data" class="hover">
|
||||
<td>{{ item.id }}</td>
|
||||
<td>{{ item.event_id }}</td>
|
||||
<td>{{ item.occurrence_start_time }}</td>
|
||||
<td>{{ item.user_id }}</td>
|
||||
<td>{{ item.notes }}</td>
|
||||
<td>{{ item.reserved_seats_count }}</td>
|
||||
<td>{{ item.created_at }}</td>
|
||||
<td>{{ item.updated_at }}</td>
|
||||
<td>{{ item.canceled_at }}</td>
|
||||
<td>{{ item.canceled_reason }}</td>
|
||||
<td>{{ item.canceled_by_user_id }}</td>
|
||||
<td class="text-right space-x-2">
|
||||
<a [routerLink]="['/bookings', item.id]" class="btn btn-sm btn-ghost">View</a>
|
||||
<a [routerLink]="['/bookings', item.id, 'edit']" class="btn btn-sm btn-ghost">Edit</a>
|
||||
<button (click)="deleteItem(item.id)" class="btn btn-sm btn-error btn-ghost">Delete</button>
|
||||
</td>
|
||||
</tr>
|
||||
<tr *ngIf="response.data.length === 0">
|
||||
<td colspan="12" class="text-center">No bookings found.</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- Pagination Controls -->
|
||||
<div *ngIf="response.meta.totalPages > 1" class="flex justify-center mt-4">
|
||||
<div class="join">
|
||||
<button
|
||||
class="join-item btn"
|
||||
(click)="changePage(response.meta.currentPage - 1)"
|
||||
[disabled]="response.meta.currentPage === 1">«</button>
|
||||
<button class="join-item btn">Page {{ response.meta.currentPage }} of {{ response.meta.totalPages }}</button>
|
||||
<button
|
||||
class="join-item btn"
|
||||
(click)="changePage(response.meta.currentPage + 1)"
|
||||
[disabled]="response.meta.currentPage === response.meta.totalPages">»</button>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
|
||||
<ng-template #loading>
|
||||
<div class="text-center p-8">
|
||||
<span class="loading loading-spinner loading-lg"></span>
|
||||
</div>
|
||||
</ng-template>
|
||||
</div>
|
||||
@ -0,0 +1,70 @@
|
||||
// dvbooking-cli/src/templates/angular/list.component.ts.tpl
|
||||
|
||||
// Generated by the CLI
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { RouterModule } from '@angular/router';
|
||||
import { BehaviorSubject, Observable, combineLatest } from 'rxjs';
|
||||
import { switchMap, startWith } from 'rxjs/operators';
|
||||
import { Booking } from '../../models/booking.model';
|
||||
import { BookingService } from '../../services/booking.service';
|
||||
import { BookingFilterComponent } from '../booking-filter/booking-filter.component';
|
||||
import { PaginatedResponse } from '../../../../../types';
|
||||
|
||||
|
||||
@Component({
|
||||
selector: 'app-booking-list',
|
||||
templateUrl: './booking-list.component.html',
|
||||
standalone: true,
|
||||
imports: [CommonModule,RouterModule, BookingFilterComponent],
|
||||
})
|
||||
export class BookingListComponent implements OnInit {
|
||||
|
||||
private refresh$ = new BehaviorSubject<void>(undefined);
|
||||
private filter$ = new BehaviorSubject<any>({});
|
||||
private page$ = new BehaviorSubject<number>(1);
|
||||
|
||||
paginatedResponse$!: Observable<PaginatedResponse<Booking>>;
|
||||
|
||||
constructor(private bookingService: BookingService) { }
|
||||
|
||||
ngOnInit(): void {
|
||||
this.paginatedResponse$ = combineLatest([
|
||||
this.refresh$,
|
||||
this.filter$.pipe(startWith({})),
|
||||
this.page$.pipe(startWith(1))
|
||||
]).pipe(
|
||||
switchMap(([_, filter, page]) => {
|
||||
const query = { ...filter, page, limit: 10 };
|
||||
return this.bookingService.find(query);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
onFilterChanged(filter: any): void {
|
||||
this.page$.next(1);
|
||||
this.filter$.next(filter);
|
||||
}
|
||||
|
||||
changePage(newPage: number): void {
|
||||
if (newPage > 0) {
|
||||
this.page$.next(newPage);
|
||||
}
|
||||
}
|
||||
|
||||
deleteItem(id: number): void {
|
||||
if (confirm('Are you sure you want to delete this item?')) {
|
||||
this.bookingService.remove(id).subscribe({
|
||||
next: () => {
|
||||
console.log(`Item with ID ${id} deleted successfully.`);
|
||||
this.refresh$.next();
|
||||
},
|
||||
// --- THIS IS THE FIX ---
|
||||
// Explicitly type 'err' to satisfy strict TypeScript rules.
|
||||
error: (err: any) => {
|
||||
console.error(`Error deleting item with ID ${id}:`, err);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,26 @@
|
||||
// dvbooking-cli/src/templates/angular-generic/data-provider.service.ts.tpl
|
||||
|
||||
// Generated by the CLI
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { DataProvider, GetDataOptions, GetDataResponse } from '../../../../components/generic-table/data-provider.interface';
|
||||
import { Booking } from '../../models/booking.model';
|
||||
import { map, Observable } from 'rxjs';
|
||||
import { BookingService } from '../../services/booking.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class BookingDataProvider implements DataProvider<Booking> {
|
||||
private bookingService = inject(BookingService);
|
||||
|
||||
getData(options?: GetDataOptions): Observable<GetDataResponse<Booking>> {
|
||||
const {q,page,limit} = options?.params ?? {};
|
||||
// The generic table's params are compatible with our NestJS Query DTO
|
||||
return this.bookingService.search(q ?? '',page,limit, ).pipe(
|
||||
map((res) => {
|
||||
// Adapt the paginated response to the GetDataResponse format
|
||||
return { data: res };
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,11 @@
|
||||
<!-- dvbooking-cli/src/templates/angular-generic/table.component.html.tpl -->
|
||||
|
||||
<!-- Generated by the CLI -->
|
||||
<div class="p-4 md:p-8 space-y-6">
|
||||
<div class="flex justify-between items-center">
|
||||
<h1 class="text-3xl font-bold">Bookings (Generic Table)</h1>
|
||||
<a routerLink="/bookings/new" class="btn btn-primary">Create New</a>
|
||||
</div>
|
||||
|
||||
<app-generic-table [config]="tableConfig"></app-generic-table>
|
||||
</div>
|
||||
@ -0,0 +1,145 @@
|
||||
// dvbooking-cli/src/templates/angular-generic/table.component.ts.tpl
|
||||
|
||||
// Generated by the CLI
|
||||
import { Component, inject, OnInit } from '@angular/core';
|
||||
import { Router, RouterModule } from '@angular/router';
|
||||
import { Booking } from '../../models/booking.model';
|
||||
import { BookingDataProvider } from './booking-data-provider.service';
|
||||
import { ColumnDefinition } from '../../../../components/generic-table/column-definition.interface';
|
||||
import { GenericTable } from '../../../../components/generic-table/generic-table';
|
||||
import { GenericTableConfig } from '../../../../components/generic-table/generic-table.config';
|
||||
import {
|
||||
ActionDefinition,
|
||||
GenericActionColumn,
|
||||
} from '../../../../components/generic-action-column/generic-action-column';
|
||||
import { BookingService } from '../../services/booking.service';
|
||||
import { BehaviorSubject } from 'rxjs';
|
||||
|
||||
@Component({
|
||||
selector: 'app-booking-table',
|
||||
standalone: true,
|
||||
imports: [GenericTable, RouterModule],
|
||||
templateUrl: './booking-table.component.html',
|
||||
})
|
||||
export class BookingTableComponent implements OnInit {
|
||||
|
||||
private refresh$ = new BehaviorSubject<void>(undefined);
|
||||
private filter$ = new BehaviorSubject<any>({});
|
||||
private page$ = new BehaviorSubject<number>(1);
|
||||
private limit$ = new BehaviorSubject<number>(10);
|
||||
|
||||
router = inject(Router);
|
||||
tableConfig!: GenericTableConfig<Booking>;
|
||||
|
||||
bookingDataProvider = inject(BookingDataProvider);
|
||||
bookingService = inject(BookingService);
|
||||
|
||||
ngOnInit(): void {
|
||||
const actionHandler = (action: ActionDefinition<Booking>, item: Booking) => {
|
||||
switch (action.action) {
|
||||
case 'view':
|
||||
this.router.navigate(['/bookings', item?.id]);
|
||||
break;
|
||||
case 'edit':
|
||||
this.router.navigate(['/bookings', item?.id, 'edit']);
|
||||
break;
|
||||
case 'delete':
|
||||
this.deleteItem(item.id);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
this.tableConfig = {
|
||||
refresh$: this.refresh$,
|
||||
filter$: this.filter$,
|
||||
page$: this.page$,
|
||||
limit$: this.limit$,
|
||||
dataProvider: this.bookingDataProvider,
|
||||
columns: [
|
||||
{
|
||||
attribute: 'event_id',
|
||||
headerCell: true,
|
||||
valueCell: true,
|
||||
},
|
||||
{
|
||||
attribute: 'occurrence_start_time',
|
||||
headerCell: true,
|
||||
valueCell: true,
|
||||
},
|
||||
{
|
||||
attribute: 'user_id',
|
||||
headerCell: true,
|
||||
valueCell: true,
|
||||
},
|
||||
{
|
||||
attribute: 'notes',
|
||||
headerCell: true,
|
||||
valueCell: true,
|
||||
},
|
||||
{
|
||||
attribute: 'reserved_seats_count',
|
||||
headerCell: true,
|
||||
valueCell: true,
|
||||
},
|
||||
{
|
||||
attribute: 'created_at',
|
||||
headerCell: true,
|
||||
valueCell: true,
|
||||
},
|
||||
{
|
||||
attribute: 'updated_at',
|
||||
headerCell: true,
|
||||
valueCell: true,
|
||||
},
|
||||
{
|
||||
attribute: 'canceled_at',
|
||||
headerCell: true,
|
||||
valueCell: true,
|
||||
},
|
||||
{
|
||||
attribute: 'canceled_reason',
|
||||
headerCell: true,
|
||||
valueCell: true,
|
||||
},
|
||||
{
|
||||
attribute: 'canceled_by_user_id',
|
||||
headerCell: true,
|
||||
valueCell: true,
|
||||
},
|
||||
{
|
||||
attribute: 'actions',
|
||||
headerCell: { value: 'Actions' },
|
||||
valueCell: {
|
||||
component: GenericActionColumn,
|
||||
componentInputs: item => ({
|
||||
item: item,
|
||||
actions: [
|
||||
{ action: 'view', handler: actionHandler },
|
||||
{ action: 'edit', handler: actionHandler },
|
||||
{ action: 'delete', handler: actionHandler },
|
||||
] as ActionDefinition<Booking>[],
|
||||
}),
|
||||
},
|
||||
},
|
||||
] as ColumnDefinition<Booking>[],
|
||||
tableCssClass: 'booking-table-container',
|
||||
};
|
||||
}
|
||||
|
||||
deleteItem(id: number): void {
|
||||
if (confirm('Are you sure you want to delete this item?')) {
|
||||
this.bookingService.remove(id).subscribe({
|
||||
next: () => {
|
||||
console.log(`Item with ID ${id} deleted successfully.`);
|
||||
this.refresh$.next();
|
||||
},
|
||||
// --- THIS IS THE FIX ---
|
||||
// Explicitly type 'err' to satisfy strict TypeScript rules.
|
||||
error: (err: any) => {
|
||||
console.error(`Error deleting item with ID ${id}:`, err);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
16
admin/src/app/features/bookings/models/booking.model.ts
Normal file
16
admin/src/app/features/bookings/models/booking.model.ts
Normal file
@ -0,0 +1,16 @@
|
||||
// dvbooking-cli/src/templates/angular/model.ts.tpl
|
||||
|
||||
// Generated by the CLI
|
||||
export interface Booking {
|
||||
id: number;
|
||||
event_id: number;
|
||||
occurrence_start_time: Date;
|
||||
user_id: number;
|
||||
notes: string;
|
||||
reserved_seats_count: number;
|
||||
created_at: Date;
|
||||
updated_at: Date;
|
||||
canceled_at: Date;
|
||||
canceled_reason: string;
|
||||
canceled_by_user_id: number;
|
||||
}
|
||||
85
admin/src/app/features/bookings/services/booking.service.ts
Normal file
85
admin/src/app/features/bookings/services/booking.service.ts
Normal file
@ -0,0 +1,85 @@
|
||||
// dvbooking-cli/src/templates/angular/service.ts.tpl
|
||||
|
||||
// Generated by the CLI
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Booking } from '../models/booking.model';
|
||||
import { ConfigurationService } from '../../../services/configuration.service';
|
||||
import { PaginatedResponse } from '../../../../types';
|
||||
|
||||
|
||||
export interface SearchResponse<T> {
|
||||
data: T[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class BookingService {
|
||||
private readonly apiUrl: string;
|
||||
|
||||
constructor(
|
||||
private http: HttpClient,
|
||||
private configService: ConfigurationService
|
||||
) {
|
||||
this.apiUrl = `${this.configService.getApiUrl()}/bookings`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find records with pagination and filtering.
|
||||
*/
|
||||
public find(filter: Record<string, any>): Observable<PaginatedResponse<Booking>> {
|
||||
// --- THIS IS THE FIX ---
|
||||
// The incorrect line: .filter(([_, v]) for v != null)
|
||||
// is now correctly written with an arrow function.
|
||||
const cleanFilter = Object.fromEntries(
|
||||
Object.entries(filter).filter(([_, v]) => v != null)
|
||||
);
|
||||
// --- END OF FIX ---
|
||||
|
||||
const params = new HttpParams({ fromObject: cleanFilter });
|
||||
return this.http.get<PaginatedResponse<Booking>>(this.apiUrl, { params });
|
||||
}
|
||||
|
||||
/**
|
||||
* Search across multiple fields with a single term.
|
||||
* @param term The search term (q).
|
||||
*/
|
||||
public search(term: string, page: number = 1, limit: number = 10): Observable<PaginatedResponse<Booking>> {
|
||||
const params = new HttpParams()
|
||||
.set('q', term)
|
||||
.set('page', page.toString())
|
||||
.set('limit', limit.toString());
|
||||
return this.http.get<PaginatedResponse<Booking>>(`${this.apiUrl}/search`, { params });
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a single record by its ID.
|
||||
*/
|
||||
public findOne(id: number): Observable<Booking> {
|
||||
return this.http.get<Booking>(`${this.apiUrl}/${id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new record.
|
||||
*/
|
||||
public create(data: Omit<Booking, 'id'>): Observable<Booking> {
|
||||
return this.http.post<Booking>(this.apiUrl, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an existing record.
|
||||
*/
|
||||
public update(id: number, data: Partial<Omit<Booking, 'id'>>): Observable<Booking> {
|
||||
return this.http.patch<Booking>(`${this.apiUrl}/${id}`, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a record by its ID.
|
||||
*/
|
||||
public remove(id: number): Observable<any> {
|
||||
return this.http.delete(`${this.apiUrl}/${id}`);
|
||||
}
|
||||
}
|
||||
@ -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[];
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user