Skip to content
Snippets Groups Projects
Commit 313efef8 authored by hugcubi's avatar hugcubi
Browse files

Actualización de controlador de hotel y algún ajuste

parent 163a22cf
Branches
Tags
2 merge requests!10Add ts types and json mocks, remove poblate scripts and fix the cascade...,!3Hotel controller mas o menos terminado, añadidas request a repositorios y...
......@@ -4,6 +4,7 @@ import java.util.List;
import java.time.LocalDate;
import com.uva.roomBooking.Exceptions.HotelNotFoundException;
import com.uva.roomBooking.Exceptions.InvalidDateRangeException;
import com.uva.roomBooking.Models.Hotel;
import com.uva.roomBooking.Models.Room;
import com.uva.roomBooking.Repositories.HotelRepository;
......@@ -48,7 +49,8 @@ public class HotelController {
// Borrar un hotel junto con sus habitaciones (borrado en cascada)
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteHotel(@PathVariable Integer id) {
Hotel target = hotelRepository.findById(id).orElseThrow(() -> new HotelNotFoundException(id));
Hotel target = hotelRepository.findById(id)
.orElseThrow(() -> new HotelNotFoundException(id));
hotelRepository.delete(target);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
......@@ -56,15 +58,14 @@ public class HotelController {
// Obtener habitaciones de un hotel según disponibilidad y fechas
@GetMapping("/{hotelId}/rooms")
public ResponseEntity<List<Room>> getRoomsFromHotel(
@PathVariable(required = true) int hotelId,
@PathVariable int hotelId,
@RequestParam(required = false) LocalDate date1,
@RequestParam(required = false) LocalDate date2) {
List<Room> rooms;
if (date1 != null && date2 != null) {
if (!date1.isBefore(date2)) {
// TODO cambiar por una excepción adecuada
throw new IllegalArgumentException("date1 should be before than date2");
throw new InvalidDateRangeException("La fecha de inicio debe ser anterior a la fecha de fin");
}
rooms = roomRepository.findAvailableRoomsByHotelAndDates(hotelId, date1, date2);
} else {
......@@ -73,39 +74,21 @@ public class HotelController {
return new ResponseEntity<>(rooms, HttpStatus.OK);
}
// Actualizar disponibilidad de habitaciones de un hotel
@PatchMapping("/{hotelId}/rooms/")
// TODO incluir tratamiento por id de habitación
public ResponseEntity<List<Room>> updateRoomAvailabilityFromHotel(
@PathVariable int hotelId, @RequestBody List<Room> updatedRooms) {
List<Room> existingRooms = roomRepository.findAllByHotelId(hotelId);
for (Room updatedRoom : updatedRooms) {
existingRooms.stream()
.filter(room -> room.getId() == updatedRoom.getId()) // Conversión a Integer
.findFirst()
.ifPresent(room -> room.setAvailable(updatedRoom.isAvailable()));
}
roomRepository.saveAll(existingRooms);
return new ResponseEntity<>(existingRooms, HttpStatus.OK);
}
// Actualizar disponibilidad de una habitación específica en un hotel
@PatchMapping("/{hotelId}/rooms/{roomId}")
public ResponseEntity<Room> updateRoomAvailability(
@PathVariable int hotelId,
@PathVariable int roomId,
@RequestBody boolean available) {
// Mi propuesta para el anterior
// // Actualizar disponibilidad de habitaciones de un hotel
// @PatchMapping("/{hotelId}/rooms/{roomId}")
// // TODO incluir tratamiento por id de habitación
// public ResponseEntity<Room> updateRoomAvailabilityFromHotel(
// @PathVariable int hotelId, @PathVariable int roomId, @RequestBody Map<String,
// Boolean> roomPatch) {
// Room target = roomRepository.findByIdAndHotelId(roomId, hotelId)
// .orElseThrow(() -> new IllegalArgumentException("No founds"));
// if (roomPatch.containsKey("available")) {
// throw new InvalidRequestException("no available field in body request");
// }
// target.setAvailable(roomPatch.get("available"));
// roomRepository.save(target);
// return new ResponseEntity<>(target, HttpStatus.OK);
// }
Room targetRoom = roomRepository.findByIdAndHotelId(roomId, hotelId)
.orElseThrow(() -> new IllegalArgumentException("Habitación no encontrada"));
targetRoom.setAvailable(available);
roomRepository.save(targetRoom);
return new ResponseEntity<>(targetRoom, HttpStatus.OK);
}
// Obtener los detalles de una habitación específica en un hotel
@GetMapping("/{hotelId}/rooms/{roomId}")
......
......
......@@ -30,6 +30,15 @@ public class GlobalExceptionHandler {
return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(InvalidDateRangeException.class)
public ResponseEntity<Map<String, Object>> handleInvalidDateRange(InvalidDateRangeException ex) {
Map<String, Object> body = new HashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("message", ex.getMessage());
return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleGeneralException(Exception ex) {
Map<String, Object> body = new HashMap<>();
......
......
package com.uva.roomBooking.Exceptions;
public class InvalidDateRangeException extends RuntimeException {
public InvalidDateRangeException(String message) {
super(message);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment