Skip to content
Snippets Groups Projects
Commit 176d4dd3 authored by hugcubi's avatar hugcubi
Browse files

Funcionan las reservas

parent 152ca982
No related branches found
No related tags found
1 merge request!36Develop
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[]> {
......
......@@ -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);
......
......@@ -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>
......
......@@ -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() },
......
......@@ -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);
}
......
......@@ -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,
......
......@@ -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());
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment