From 176d4dd3c1506e4a0600be791ebb40569e45bac8 Mon Sep 17 00:00:00 2001
From: Hugo <hugo.cubino@estudiantes.uva.es>
Date: Sat, 28 Dec 2024 11:00:06 +0100
Subject: [PATCH] Funcionan las reservas

---
 .../api/bookings/booking-client.service.ts    | 38 ++++---------------
 .../bookings/booking/booking.component.ts     | 34 +++--------------
 .../hotel-list/hotel-list.component.html      |  2 +-
 .../hotels/hotel-list/hotel-list.component.ts |  6 ++-
 .../hotels/controllers/HotelController.java   |  1 +
 .../java/com/uva/api/hotels/models/Hotel.java |  2 +
 .../uva/api/hotels/services/HotelService.java |  1 +
 7 files changed, 24 insertions(+), 60 deletions(-)

diff --git a/angular/RestClient/src/app/core/services/api/bookings/booking-client.service.ts b/angular/RestClient/src/app/core/services/api/bookings/booking-client.service.ts
index 7e88d90..5f20602 100644
--- a/angular/RestClient/src/app/core/services/api/bookings/booking-client.service.ts
+++ b/angular/RestClient/src/app/core/services/api/bookings/booking-client.service.ts
@@ -1,10 +1,8 @@
 import { Injectable } from '@angular/core';
-import { HttpClient } from '@angular/common/http';
-import { Observable, throwError } from 'rxjs';
+import { HttpClient, HttpHeaders } from '@angular/common/http';
+import { Observable } from 'rxjs';
 import { environment } from '../../../../../environments/environment';
 import { Booking } from '@features/bookings';
-import { HotelClientService } from '../hotels/hotel-client.service';
-import { switchMap, map } from 'rxjs/operators';
 
 @Injectable({
   providedIn: 'root',
@@ -12,36 +10,16 @@ import { switchMap, map } from 'rxjs/operators';
 export class BookingClientService {
   private URI = environment.bookingAPI;
 
-  constructor(
-    private http: HttpClient,
-    private hotelClientService: HotelClientService // Inyectamos el servicio HotelClientService
-  ) {}
+  constructor(private http: HttpClient) {}
 
   // Método para crear una nueva reserva
   createBooking(bookingRequest: Booking): Observable<Booking> {
-    const { hotelId, start, end, userId, roomId } = bookingRequest;
-    
-    if (!hotelId) {
-      console.error("hotelId is undefined");
-      return throwError(() => new Error("hotelId is undefined"));
-    }
-  
-    // Llamamos al servicio HotelClientService para obtener el hotel y su managerId
-    return this.hotelClientService.getHotel(hotelId).pipe(
-      map((hotel) => {
-        const managerId = hotel.managerId;
-        console.log("Manager ID:", managerId);  // Verifica que el managerId es correcto
-        
-        // Retornamos el objeto bookingRequest con el managerId actualizado
-        return { ...bookingRequest, managerId };
-      }),
-      switchMap((updatedBookingRequest) => {
-        console.log("Final bookingRequest with managerId:", updatedBookingRequest);  // Verifica el objeto final
-        return this.http.post<Booking>(this.URI, updatedBookingRequest);
-      })
-    );
+    const { start, end } = bookingRequest;
+    const endDate = end.toISOString();
+    console.log({ bookingRequest, end: endDate });
+
+    return this.http.post<Booking>(this.URI, bookingRequest);
   }
-  
 
   // Método para obtener todas las reservas
   getAllBookings(): Observable<Booking[]> {
diff --git a/angular/RestClient/src/app/features/bookings/booking/booking.component.ts b/angular/RestClient/src/app/features/bookings/booking/booking.component.ts
index fba6675..b6a95e8 100644
--- a/angular/RestClient/src/app/features/bookings/booking/booking.component.ts
+++ b/angular/RestClient/src/app/features/bookings/booking/booking.component.ts
@@ -7,7 +7,7 @@ import {
 } from '@angular/forms';
 
 import { ActivatedRoute, Router } from '@angular/router';
-import { Booking } from '@features/bookings';
+import { Booking} from '@features/bookings';
 import { User } from '@features/users';
 import { LocalStorageService } from '../../../core/services/storage/local-storage.service';
 import { BookingClientService } from '../../../core/services/api/bookings/booking-client.service';
@@ -18,6 +18,8 @@ type communication = {
   roomId: number;
   start: Date;
   end: Date;
+  hotelId : number;
+  managerId : number;
 };
 
 @Component({
@@ -30,13 +32,13 @@ type communication = {
 export class BookingComponent {
   user: User = { id: 0, email: '', name: '', rol: 'CLIENT' };
   bookingForm: FormGroup;
-  bookingLocal: { roomId: number; start: Date; end: Date } = {
+  bookingLocal: { roomId: number; start: Date; end: Date, hotelId : number, managerId : number } = {
     roomId: 0,
     end: new Date(),
     start: new Date(),
+    hotelId : 0,
+    managerId : 0
   };
-  roomId: number = 0;
-  hotelId: number = 0;  // Agregamos hotelId
 
   constructor(
     private router: Router,
@@ -53,38 +55,25 @@ export class BookingComponent {
       start: [{ value: '', disabled: true }, Validators.required],
       end: [{ value: '', disabled: true }, Validators.required],
     });
-
     const localBooking = storage.read<communication | null>('booking-data');
     if (localBooking === null) {
       this.router.navigate(['/booking', 'search']);
       return;
     }
     this.bookingLocal = localBooking!;
-
     this.route.queryParams.subscribe((params) => {
       const roomId = Number(params['roomId']);
-      this.hotelId = Number(params['hotelId']);  // Extraemos hotelId de los parámetros de la URL
-      this.roomId = roomId;
-
       if (this.bookingLocal.roomId !== roomId) {
         this.router.navigate(['/bookings', 'search']);
         return;
       }
-
-      if (!this.hotelId) {
-        console.error('No se ha proporcionado hotelId');
-        return;
-      }
-
       this.bookingLocal = {
         ...this.bookingLocal,
         start: new Date(this.bookingLocal.start),
         end: new Date(this.bookingLocal.end),
       };
-
       this.loadBooking();
     });
-
     this.sessionService.getSession().subscribe({
       next: (session) => {
         if (session) this.user = session;
@@ -116,8 +105,6 @@ export class BookingComponent {
     const bookingRequest: any = {
       ...this.bookingLocal,
       userId: id,
-      roomId: this.roomId,
-      hotelId: this.hotelId,  // Aseguramos que hotelId esté incluido
     };
 
     // Llama al servicio para crear una nueva reserva
@@ -126,17 +113,8 @@ export class BookingComponent {
     this.bookingClient.createBooking(bookingRequest).subscribe({
       next: (response) => {
         console.log('Reserva creada con éxito', response);
-        // Llama al servicio para actualizar el estado del usuario
-        this.userClient.alterUserStatus(id, 'WITH_ACTIVE_BOOKINGS').subscribe({
-          next: (response) => {
-            console.log('Estado de usuario actualizado con éxito', response);
             this.storage.remove('booking-data');
             this.router.navigate(['/me', 'bookings']);
-          },
-          error: (error) => {
-            console.error('Error al cambiar el estado del usuario', error);
-          },
-        });
       },
       error: (error) => {
         console.error('Error al crear la reserva', error);
diff --git a/angular/RestClient/src/app/features/hotels/hotel-list/hotel-list.component.html b/angular/RestClient/src/app/features/hotels/hotel-list/hotel-list.component.html
index d0f0b21..029a82f 100644
--- a/angular/RestClient/src/app/features/hotels/hotel-list/hotel-list.component.html
+++ b/angular/RestClient/src/app/features/hotels/hotel-list/hotel-list.component.html
@@ -173,7 +173,7 @@
                   [disabled]="!isAvailable(room)"
                   mat-raised-button
                   class="w-full text-center py-3 rounded-lg shadow-md hover:shadow-lg bg-sky-600 text-slate-200 font-bold"
-                  (click)="bookingRoom(room.id)"
+                  (click)="bookingRoom(room.id, hotel)"
                 >
                   <span class="flex items-center justify-center text-2xl">
                     <mat-icon>booking</mat-icon>
diff --git a/angular/RestClient/src/app/features/hotels/hotel-list/hotel-list.component.ts b/angular/RestClient/src/app/features/hotels/hotel-list/hotel-list.component.ts
index b38638d..fd182a2 100644
--- a/angular/RestClient/src/app/features/hotels/hotel-list/hotel-list.component.ts
+++ b/angular/RestClient/src/app/features/hotels/hotel-list/hotel-list.component.ts
@@ -217,15 +217,19 @@ export class HotelListComponent {
     return (this.isManaging ? base : '/') + 'hotels/' + hotelId;
   }
 
-  bookingRoom(roomId: number) {
+  bookingRoom(roomId: number, hotel: Hotel) {
     const { start, end } = this.dateRangeForm.value.dateRange as {
       start: Date;
       end: Date;
     };
+    const {managerId} = hotel;
+    const hotelId = hotel.id;
     this.storage.save('booking-data', {
       roomId,
       start: start.toString(),
       end: end.toString(),
+      hotelId,
+      managerId
     });
     this.router.navigate(['/me', 'bookings', 'new'], {
       queryParams: { roomId, startDate: start.toLocaleDateString() },
diff --git a/java/services/hotels/src/main/java/com/uva/api/hotels/controllers/HotelController.java b/java/services/hotels/src/main/java/com/uva/api/hotels/controllers/HotelController.java
index ee1e722..a23e501 100644
--- a/java/services/hotels/src/main/java/com/uva/api/hotels/controllers/HotelController.java
+++ b/java/services/hotels/src/main/java/com/uva/api/hotels/controllers/HotelController.java
@@ -32,6 +32,7 @@ public class HotelController {
 
     @PostMapping
     public ResponseEntity<?> addHotel(@RequestBody Hotel hotel) {
+        System.out.println(hotel.toString());
         Hotel savedHotel = hotelService.addHotel(hotel);
         return new ResponseEntity<>(savedHotel, HttpStatus.CREATED);
     }
diff --git a/java/services/hotels/src/main/java/com/uva/api/hotels/models/Hotel.java b/java/services/hotels/src/main/java/com/uva/api/hotels/models/Hotel.java
index 23eff28..a4be310 100644
--- a/java/services/hotels/src/main/java/com/uva/api/hotels/models/Hotel.java
+++ b/java/services/hotels/src/main/java/com/uva/api/hotels/models/Hotel.java
@@ -18,11 +18,13 @@ import lombok.AllArgsConstructor;
 import lombok.Getter;
 import lombok.NoArgsConstructor;
 import lombok.Setter;
+import lombok.ToString;
 
 @Getter
 @Setter
 @AllArgsConstructor
 @NoArgsConstructor
+@ToString
 @Entity
 @Table(name = "hotels")
 // @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
diff --git a/java/services/hotels/src/main/java/com/uva/api/hotels/services/HotelService.java b/java/services/hotels/src/main/java/com/uva/api/hotels/services/HotelService.java
index 2e8ada3..4b736e1 100644
--- a/java/services/hotels/src/main/java/com/uva/api/hotels/services/HotelService.java
+++ b/java/services/hotels/src/main/java/com/uva/api/hotels/services/HotelService.java
@@ -51,6 +51,7 @@ public class HotelService {
 
     public Hotel addHotel(Hotel hotel) {
         boolean exist = managerAPI.existsManagerById(hotel.getManagerId());
+        System.out.println("Id del manager" + hotel.getManagerId());
         if (!exist) {
             throw new InvalidRequestException("No existe el manager con id " + hotel.getManagerId());
         }
-- 
GitLab