Skip to content
Snippets Groups Projects
Commit 51911ceb authored by migudel's avatar migudel :speech_balloon:
Browse files

Refinamiento en búsqueda de habitaciones y comprobación de creación de reserva a través de web

parent acf0f6b0
No related branches found
No related tags found
1 merge request!10Add ts types and json mocks, remove poblate scripts and fix the cascade...
......@@ -2,7 +2,7 @@
<h2>Crear Reserva</h2>
<form [formGroup]="bookingForm" (ngSubmit)="submitBooking()">
<div class="form-group">
<label for="userId">Usuario:</label>
<label for="userId">ID del Usuario:</label>
<input
type="number"
id="userId"
......@@ -11,6 +11,16 @@
/>
</div>
<div class="form-group">
<label for="roomId">ID del Hotel:</label>
<input
type="number"
id="roomId"
formControlName="roomId"
class="form-control"
/>
</div>
<div class="form-group">
<label for="roomType">Tipo de Habitación:</label>
<select id="roomType" formControlName="roomType" class="form-control">
......
......@@ -5,15 +5,10 @@ import {
FormBuilder,
Validators,
} from '@angular/forms';
interface BookingRequest {
userId: number; // ID del usuario que realiza la reserva
hotelId: number; // ID del hotel en el que se realiza la reserva
roomType: string; // Tipo de habitación (single, double, suite)
startDate: string; // Fecha de inicio de la reserva
endDate: string; // Fecha de fin de la reserva// Asegúrate de ajustar la ruta
}
import { BookingService } from '../shared/booking.service'; // Asegúrate de que el servicio exista
import { ActivatedRoute } from '@angular/router';
import { Booking } from '../../types';
@Component({
standalone: true,
......@@ -34,7 +29,7 @@ export class BookingComponent implements OnInit {
// Inicialización del formulario con validaciones
this.bookingForm = this.fb.group({
userId: ['', Validators.required],
hotelId: ['', Validators.required],
roomId: ['', Validators.required],
roomType: ['', Validators.required],
startDate: ['', Validators.required],
endDate: ['', Validators.required],
......@@ -49,7 +44,13 @@ export class BookingComponent implements OnInit {
submitBooking() {
if (this.bookingForm.valid) {
const bookingRequest: BookingRequest = this.bookingForm.value;
const formValue = this.bookingForm.value;
const bookingRequest: Booking = {
...formValue,
userId: { id: formValue.userId },
roomId: { id: formValue.roomId },
};
console.warn(bookingRequest);
// Llama al servicio para crear una nueva reserva
this.bookingService.createBooking(bookingRequest).subscribe(
......
......@@ -2,25 +2,19 @@
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
interface BookingRequest {
userId: number; // ID del usuario que realiza la reserva
hotelId: number; // ID del hotel en el que se realiza la reserva
roomType: string; // Tipo de habitación (single, double, suite)
startDate: string; // Fecha de inicio de la reserva
endDate: string; // Fecha de fin de la reserva
}
import { Booking } from '../../types/Booking'; // Ajusta la ruta a tu modelo Booking
@Injectable({
providedIn: 'root', // Esto hace que el servicio esté disponible en toda la aplicación
})
export class BookingService {
private apiUrl = 'http://localhost:8080/api/bookings';
private apiUrl = 'http://localhost:8080/bookings';
constructor(private http: HttpClient) {}
// Método para crear una nueva reserva
createBooking(bookingRequest: BookingRequest): Observable<Booking> {
createBooking(bookingRequest: Booking): Observable<Booking> {
return this.http.post<Booking>(this.apiUrl, bookingRequest, {
headers: new HttpHeaders({
'Content-Type': 'application/json',
......
......@@ -59,9 +59,9 @@ export class ClienteApiRestService {
getRoomsAvailableInDateRange(hotelId: number, start: Date, end: Date) {
const startStr = start.toISOString().split('T')[0];
const endStr = end.toISOString().split('T')[0];
return this.http.get<Room[]>(
`${ClienteApiRestService.HOTEL_URI}/${hotelId}/rooms?start=${startStr}&end=${endStr}`
);
const url = `${ClienteApiRestService.HOTEL_URI}/${hotelId}/rooms?start=${startStr}&end=${endStr}`;
console.warn(url);
return this.http.get<Room[]>(url);
}
getAllUsers() {
......
......@@ -40,11 +40,6 @@ public class BookingController {
Room room = roomRepository.findById(booking.getRoomId().getId())
.orElseThrow(() -> new RuntimeException("Room not found"));
// Validar el tipo de habitación
if (!room.getType().equals(booking.getRoomId().getType())) {
throw new RuntimeException("Room type does not match the requested type");
}
// Verificar disponibilidad
List<Booking> existingBookings = bookingRepository.findByRoomIdAndDateRange(
room.getId(), booking.getStartDate(), booking.getEndDate());
......@@ -63,5 +58,4 @@ public class BookingController {
bookingRepository.deleteById(id);
}
}
......@@ -20,7 +20,6 @@ import java.time.LocalDate;
public class Booking {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
private int id;
// TODO revisar si lo de cascade es estrictamente necesario
@JoinColumn(name = "user_id", referencedColumnName = "id")
......
......@@ -16,7 +16,6 @@ public interface RoomRepository extends JpaRepository<Room, Integer> {
List<Room> findAllByHotelId(int hotelId);
// Encontrar habitaciones disponibles de un hotel en un rango de fechas
// TODO revisar los límites en las fechas
@Query("""
SELECT r FROM Room r
WHERE r.hotel.id = ?1
......@@ -24,7 +23,11 @@ public interface RoomRepository extends JpaRepository<Room, Integer> {
AND NOT EXISTS (
SELECT b FROM Booking b
WHERE b.roomId.id = r.id
AND (b.startDate < ?3 AND b.endDate > ?2)
AND (
b.endDate > ?2
OR
b.startDate > ?3
)
)
""")
List<Room> findAvailableRoomsByHotelAndDates(
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment