Skip to content
Snippets Groups Projects
Commit 9af8156d authored by hugcubi's avatar hugcubi
Browse files

En teoría la parte funcional está y funciona el build y run

parent 9d42c2b2
No related branches found
No related tags found
2 merge requests!26Revert "Funciona register",!18Dev/microservicio booking
Showing
with 175 additions and 709 deletions
......@@ -9,10 +9,10 @@
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.uva</groupId>
<artifactId>roomBooking</artifactId>
<artifactId>bookingService</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>roomBooking</name>
<description>Room Booking rest</description>
<name>bookingService</name>
<description>Booking Microservice</description>
<url/>
<licenses>
<license/>
......
// BookingController.java
package com.uva.roomBooking.Controllers;
package com.uva.bookings.Controllers;
import com.uva.roomBooking.Models.Booking;
import com.uva.roomBooking.Models.Room;
import com.uva.roomBooking.Models.User;
import com.uva.roomBooking.Repositories.BookingRepository;
import com.uva.roomBooking.Repositories.RoomRepository;
import com.uva.roomBooking.Repositories.UserRepository;
import com.uva.bookings.Models.Booking;
import com.uva.bookings.Repositories.BookingRepository;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.List;
......@@ -22,39 +19,66 @@ import java.util.List;
@CrossOrigin(origins = "*")
public class BookingController {
private final BookingRepository bookingRepository;
private final UserRepository userRepository;
private final RoomRepository roomRepository;
@Autowired
private BookingRepository bookingRepository;
public BookingController(BookingRepository bookingRepository, UserRepository userRepository,
RoomRepository roomRepository) {
this.bookingRepository = bookingRepository;
this.userRepository = userRepository;
this.roomRepository = roomRepository;
}
@Autowired
private RestTemplate restTemplate;
@GetMapping
public List<Booking> getAllBookings() {
return bookingRepository.findAll();
public ResponseEntity<List<Booking>> getBookings(
@RequestParam(required = false) String startDate,
@RequestParam(required = false) String endDate,
@RequestParam(required = false) Integer roomId) {
// Si no se proporcionan filtros, devolver todas las reservas
if (startDate == null && endDate == null && roomId == null) {
return ResponseEntity.ok(bookingRepository.findAll());
}
// Obtener reservas filtradas por los parámetros dados
List<Booking> bookings = bookingRepository.findByFilters(startDate, endDate, roomId);
if (bookings.isEmpty()) {
return ResponseEntity.noContent().build();
}
return ResponseEntity.ok(bookings);
}
@PostMapping
public Booking createBooking(@RequestBody Booking booking) {
User user = userRepository.findById(booking.getUserId().getId())
.orElseThrow(() -> new RuntimeException("User not found"));
Room room = roomRepository.findById(booking.getRoomId().getId())
.orElseThrow(() -> new RuntimeException("Room not found"));
// Llamada al microservicio de usuarios para validar al usuario
ResponseEntity<Void> userResponse = restTemplate.exchange(
"http://user-service/users/{userId}",
HttpMethod.GET,
null,
Void.class,
booking.getUserId()
);
if (!userResponse.getStatusCode().is2xxSuccessful()) {
throw new RuntimeException("User not found");
}
// Llamada al microservicio de habitaciones para validar la habitación
ResponseEntity<Void> roomResponse = restTemplate.exchange(
"http://room-service/rooms/{roomId}",
HttpMethod.GET,
null,
Void.class,
booking.getRoomId()
);
if (!roomResponse.getStatusCode().is2xxSuccessful()) {
throw new RuntimeException("Room not found");
}
// Verificar disponibilidad
List<Booking> existingBookings = bookingRepository.findByRoomIdAndDateRange(
room.getId(), booking.getStartDate(), booking.getEndDate());
booking.getRoomId(), booking.getStartDate(), booking.getEndDate());
if (!existingBookings.isEmpty()) {
throw new RuntimeException("Room is not available for the selected dates");
}
booking.setUserId(user);
booking.setRoomId(room);
return bookingRepository.save(booking);
}
......@@ -64,6 +88,28 @@ public class BookingController {
.orElseThrow(() -> new RuntimeException("Booking not found"));
}
@GetMapping(params = "userId")
public ResponseEntity<List<Booking>> getBookingsByUserId(@RequestParam Integer userId) {
// Llamada al microservicio de usuarios para validar la existencia del usuario
ResponseEntity<Void> userResponse = restTemplate.exchange(
"http://user-service/users/{userId}",
HttpMethod.GET,
null,
Void.class,
userId
);
if (!userResponse.getStatusCode().is2xxSuccessful()) {
return ResponseEntity.noContent().build();
}
List<Booking> bookings = bookingRepository.findByUserId(userId);
if (bookings.isEmpty()) {
return ResponseEntity.noContent().build();
}
return ResponseEntity.ok(bookings);
}
@DeleteMapping("/{id}")
@Transactional
public ResponseEntity<Void> deleteBooking(@PathVariable Integer id) {
......
package com.uva.roomBooking.Exceptions;
package com.uva.bookings.Exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
......
package com.uva.roomBooking.Exceptions;
package com.uva.bookings.Exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
......
package com.uva.roomBooking.Exceptions;
package com.uva.bookings.Exceptions;
public class InvalidDateRangeException extends RuntimeException {
public InvalidDateRangeException(String message) {
......
package com.uva.roomBooking.Exceptions;
package com.uva.bookings.Exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
......
package com.uva.roomBooking.Models;
package com.uva.bookings.Models;
import jakarta.persistence.Basic;
import jakarta.persistence.CascadeType;
......@@ -20,12 +20,10 @@ public class Booking {
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
private int id;
@JoinColumn(name = "user_id", referencedColumnName = "id")
@ManyToOne(optional = false, fetch = FetchType.EAGER, cascade = CascadeType.MERGE)
private User userId;
@JoinColumn(name = "room_id", referencedColumnName = "id")
@ManyToOne(optional = false, fetch = FetchType.EAGER, cascade = CascadeType.MERGE)
private Room roomId;
@Column(name = "user_id", nullable = false)
private int userId;
@Column(name = "room_id", nullable = false)
private int roomId;
@Column(name = "start_date", nullable = false)
private LocalDate startDate;
@Column(name = "end_date", nullable = false)
......@@ -34,7 +32,7 @@ public class Booking {
public Booking() {
}
public Booking(int id, User userId, Room roomID, LocalDate startDate, LocalDate endDate) {
public Booking(int id, int userId, int roomID, LocalDate startDate, LocalDate endDate) {
this.id = id;
this.userId = userId;
this.roomId = roomID;
......@@ -50,19 +48,19 @@ public class Booking {
return this.id;
}
public void setUserId(User userId) {
public void setUserId(int userId) {
this.userId = userId;
}
public User getUserId() {
public int getUserId() {
return this.userId;
}
public void setRoomId(Room roomID) {
public void setRoomId(int roomID) {
this.roomId = roomID;
}
public Room getRoomId() {
public int getRoomId() {
return this.roomId;
}
......
// BookingRepository.java
package com.uva.roomBooking.Repositories;
package com.uva.bookings.Repositories;
import com.uva.roomBooking.Models.Booking;
import com.uva.bookings.Models.Booking;
import jakarta.transaction.Transactional;
......@@ -15,7 +15,7 @@ import org.springframework.data.repository.query.Param;
public interface BookingRepository extends JpaRepository<Booking, Integer> {
@Query("SELECT b FROM Booking b WHERE b.roomId.id = ?1 AND b.startDate < ?2 AND b.endDate > ?3")
@Query("SELECT b FROM Booking b WHERE b.roomId = ?1 AND b.startDate < ?2 AND b.endDate > ?3")
List<Booking> findByRoomIdAndDateRange(@Param("roomId") int roomId, @Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
......@@ -24,9 +24,17 @@ public interface BookingRepository extends JpaRepository<Booking, Integer> {
@Query("DELETE FROM Booking b WHERE b.id = ?1")
void deleteBookingById(@Param("id") Integer id);
@Transactional
@Modifying
@Query("DELETE FROM Booking b WHERE b.roomId.hotel.id = ?1")
void deleteAllByHotelId(int hotelId);
List<Booking> findByUserId(Integer userId);
@Query("SELECT b FROM Booking b WHERE "
+ "(:roomId IS NULL OR b.roomId = :roomId) AND "
+ "(:startDate IS NULL OR b.startDate >= :startDate) AND "
+ "(:endDate IS NULL OR b.endDate <= :endDate)")
List<Booking> findByFilters(@Param("startDate") String startDate,
@Param("endDate") String endDate,
@Param("roomId") Integer roomId);
}
package com.uva.roomBooking;
package com.uva.bookings;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RoomBookingApplication {
public class bookingServiceApplication {
public static void main(String[] args) {
SpringApplication.run(RoomBookingApplication.class, args);
SpringApplication.run(bookingServiceApplication.class, args);
}
}
package com.uva.bookings.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
package com.uva.roomBooking.Controllers;
import java.util.List;
import java.util.Map;
import java.time.LocalDate;
import com.uva.roomBooking.Exceptions.HotelNotFoundException;
import com.uva.roomBooking.Exceptions.InvalidDateRangeException;
import com.uva.roomBooking.Exceptions.InvalidRequestException;
import com.uva.roomBooking.Models.Booking;
import com.uva.roomBooking.Models.Hotel;
import com.uva.roomBooking.Models.Room;
import com.uva.roomBooking.Repositories.BookingRepository;
import com.uva.roomBooking.Repositories.HotelRepository;
import com.uva.roomBooking.Repositories.RoomRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("hotels")
@CrossOrigin(origins = "*")
public class HotelController {
private final HotelRepository hotelRepository;
private final RoomRepository roomRepository;
private final BookingRepository bookingRepository;
public HotelController(HotelRepository hotelRepository, RoomRepository roomRepository,
BookingRepository bookingRepository) {
this.hotelRepository = hotelRepository;
this.roomRepository = roomRepository;
this.bookingRepository = bookingRepository;
}
// Obtener todos los hoteles
@GetMapping
public List<Hotel> getAllHotels() {
return hotelRepository.findAll();
}
// Añadir un hotel con sus habitaciones
@PostMapping
public ResponseEntity<Hotel> addHotel(@RequestBody Hotel hotel) {
Hotel savedHotel = hotelRepository.save(hotel);
return new ResponseEntity<>(savedHotel, HttpStatus.CREATED);
}
// Obtener un hotel por su ID
@GetMapping("/{id}")
public Hotel getHotelById(@PathVariable int id) {
return hotelRepository.findById(id)
.orElseThrow(() -> new HotelNotFoundException(id));
}
// Borrar un hotel junto con sus habitaciones (borrado en cascada)
@DeleteMapping("/{id}")
@Transactional
public ResponseEntity<Void> deleteHotel(@PathVariable Integer id) {
Hotel target = hotelRepository.findById(id)
.orElseThrow(() -> new HotelNotFoundException(id));
bookingRepository.deleteAllByHotelId(id);
hotelRepository.delete(target);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
// Obtener habitaciones de un hotel según disponibilidad y fechas
@GetMapping("/{hotelId}/rooms")
public ResponseEntity<List<Room>> getRoomsFromHotel(
@PathVariable int hotelId,
@RequestParam(required = false) LocalDate start,
@RequestParam(required = false) LocalDate end) {
List<Room> rooms;
if (start != null && end != null) {
if (!start.isBefore(end)) {
throw new InvalidDateRangeException("La fecha de inicio debe ser anterior a la fecha de fin");
}
rooms = roomRepository.findAvailableRoomsByHotelAndDates(hotelId, start, end);
} else {
rooms = roomRepository.findAllByHotelId(hotelId);
}
return new ResponseEntity<>(rooms, 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 Map<String, Boolean> body) {
if (!body.containsKey("available")) {
throw new InvalidRequestException("El campo 'available' es obligatorio");
}
Room targetRoom = roomRepository.findByIdAndHotelId(roomId, hotelId)
.orElseThrow(() -> new IllegalArgumentException("Habitación no encontrada"));
targetRoom.setAvailable(body.get("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}")
public Room getRoomByIdFromHotel(
@PathVariable int hotelId, @PathVariable int roomId) {
return roomRepository.findByIdAndHotelId(roomId, hotelId)
.orElseThrow(() -> new HotelNotFoundException(hotelId));
}
}
package com.uva.roomBooking.Controllers;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.uva.roomBooking.Models.UserStatus;
import com.uva.roomBooking.Models.Booking;
import com.uva.roomBooking.Models.User;
import com.uva.roomBooking.Repositories.UserRepository;
@RestController
@RequestMapping("users")
@CrossOrigin(origins = "*")
public class UserController {
private final UserRepository userRepository;
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@GetMapping
public List<User> getAllUsers() {
return userRepository.findAll();
}
@PostMapping
public User addUser(@RequestBody User user) {
// TODO revisar como se desea manejar estado por defecto
user.setStatus(UserStatus.NO_BOOKINGS);
// Aunque se asegure a lo mejor no es la forma de manejo esperada
return userRepository.save(user);
}
@GetMapping("/{id}")
public User getUserById(@PathVariable int id) {
return userRepository.findById(id).orElseThrow();
}
@PutMapping("/{id}")
public User updateUserData(@PathVariable int id, @RequestBody Map<String, String> json) {
User target = userRepository.findById(id).orElseThrow();
if (!json.containsKey("name") || !json.containsKey("email")) {
// TODO cambiar manejo
throw new RuntimeException("Missing required fields");
}
target.setName(json.get("name"));
target.setEmail(json.get("email"));
return userRepository.save(target);
}
@PatchMapping("/{id}")
public User updateUserState(@PathVariable int id, @RequestBody Map<String, String> json) {
User target = userRepository.findById(id).orElseThrow();
String strStatus = json.get("status");
if (strStatus == null) {
// TODO cambiar manejo
throw new RuntimeException("Missing required fields");
}
UserStatus userStatus = UserStatus.valueOf(strStatus);
boolean activeBookings = target.getBookings().stream()
.anyMatch(booking -> !booking.getEndDate().isBefore(LocalDate.now())); // reserva >= ahora
boolean inactiveBookings = target.getBookings().stream()
.anyMatch(booking -> booking.getStartDate().isBefore(LocalDate.now())); // reserva < ahora
switch (userStatus) {
// TODO Buscar como validar las (in)active bookings
case NO_BOOKINGS:
if (!target.getBookings().isEmpty())
throw new IllegalArgumentException("Invalid State: The user has at least one booking");
break;
case WITH_ACTIVE_BOOKINGS:
if (target.getBookings().isEmpty())
throw new IllegalArgumentException("Invalid State: The user don't has bookings");
if (!activeBookings)
throw new IllegalArgumentException("Invalid State: The user don't has active bookings");
break;
case WITH_INACTIVE_BOOKINGS:
if (target.getBookings().isEmpty())
throw new IllegalArgumentException("Invalid State: The user don't has bookings");
if (!inactiveBookings)
throw new IllegalArgumentException("Invalid State: The user don't has inactive bookings");
break;
default:
break;
}
target.setStatus(userStatus);
return userRepository.save(target);
}
@DeleteMapping("/{id}")
public User deleteUser(@PathVariable Integer id) {
User target;
if ((target = userRepository.findById(id).orElseThrow()) != null) {
userRepository.deleteById(id);
}
return target;
}
@GetMapping("/{id}/bookings")
public List<Booking> getUserBookingsById(@PathVariable int id) {
User user = userRepository.findById(id).orElseThrow();
return user.getBookings();
}
}
package com.uva.roomBooking.Models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.Basic;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "addresses")
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
private int id;
@Basic(optional = false)
@Column(name = "street_kind")
private String streetKind;
@Basic(optional = false)
@Column(name = "street_name")
private String streetName;
@Basic(optional = false)
private int number;
@Basic(optional = false)
@Column(name = "post_code")
private String postCode;
@Basic(optional = true)
@Column(name = "other_info")
private String otherInfo;
@JsonIgnore
@OneToOne(mappedBy = "address", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Hotel hotel;
public Address() {
}
public Address(String streetKind, String streetName, int number, String postCode, String otherInfo, Hotel hotel) {
setStreetKind(streetKind);
setStreetName(streetName);
setNumber(number);
setPostCode(postCode);
setOtherInfo(otherInfo);
setHotel(hotel);
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getStreetKind() {
return this.streetKind;
}
public void setStreetKind(String streetKind) {
this.streetKind = streetKind;
}
public String getStreetName() {
return this.streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public int getNumber() {
return this.number;
}
public void setNumber(int number) {
this.number = number;
}
public String getPostCode() {
return this.postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
public String getOtherInfo() {
return this.otherInfo;
}
public void setOtherInfo(String otherInfo) {
this.otherInfo = otherInfo;
}
public Hotel getHotel() {
return this.hotel;
}
public void setHotel(Hotel hotel) {
this.hotel = hotel;
}
}
package com.uva.roomBooking.Models;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import jakarta.persistence.Basic;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OneToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "hotels")
// @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
// property = "id")
public class Hotel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
private int id;
@Basic(optional = false)
private String name;
@JoinColumn(name = "address_id", referencedColumnName = "id")
@OneToOne(optional = false, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Address address;
@OneToMany(mappedBy = "hotel", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Room> rooms;
public Hotel() {
}
public Hotel(int id, String name, Address address, List<Room> rooms) {
setId(id);
setName(name);
setAddress(address);
setRooms(rooms);
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return this.address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<Room> getRooms() {
return this.rooms;
}
public void setRooms(List<Room> rooms) {
this.rooms = rooms;
rooms.forEach(room -> room.setHotel(this));
}
}
package com.uva.roomBooking.Models;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import jakarta.persistence.Basic;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
@Entity
@Table(name = "rooms")
// @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
// property = "id")
public class Room {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
private int id;
@ManyToOne
@JoinColumn(name = "hotel_id", referencedColumnName = "id")
@JsonIgnore
private Hotel hotel;
@Column(name = "room_number", nullable = false)
private String roomNumber;
@Column(name = "type", nullable = false)
private Tipo type;
@Column(name = "available", nullable = false)
private boolean available;
@JsonIgnore
@OneToMany(mappedBy = "roomId", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Booking> bookings;
public Room() {
}
public Room(int id, Hotel hotelId, String roomNumber, Tipo type, boolean available, List<Booking> bookings) {
this.id = id;
this.hotel = hotelId;
this.roomNumber = roomNumber;
this.type = type;
this.available = available;
this.bookings = bookings;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public void setHotel(Hotel hotelId) {
this.hotel = hotelId;
}
public Hotel getHotel() {
return this.hotel;
}
public void setRoomNumber(String roomNumber) {
this.roomNumber = roomNumber;
}
public String getRoomNumber() {
return this.roomNumber;
}
public void setType(Tipo type) {
this.type = type;
}
public Tipo getType() {
return this.type;
}
public void setAvailable(boolean available) {
this.available = available;
}
public boolean isAvailable() {
return this.available;
}
public List<Booking> getBookings() {
return this.bookings;
}
public void setBookings(List<Booking> bookings) {
this.bookings = bookings;
}
}
package com.uva.roomBooking.Models;
public enum Tipo {
SINGLE,
DOUBLE,
SUITE
}
package com.uva.roomBooking.Models;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.Basic;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
private int id;
@Basic(optional = false)
private String name;
@Basic(optional = false)
private String email;
@Basic(optional = false)
@Enumerated(EnumType.STRING)
private UserStatus status = UserStatus.NO_BOOKINGS;
@JsonIgnore
@OneToMany(mappedBy = "userId", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Booking> bookings;
public User() {
}
public User(int id, String name, String email, UserStatus status, List<Booking> bookings) {
setId(id);
setEmail(email);
setStatus(status);
setBookings(bookings);
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public UserStatus getStatus() {
return this.status;
}
public void setStatus(UserStatus status) {
this.status = status;
}
public List<Booking> getBookings() {
return this.bookings;
}
public void setBookings(List<Booking> bookings) {
this.bookings = bookings;
}
}
package com.uva.roomBooking.Models;
public enum UserStatus {
NO_BOOKINGS, WITH_ACTIVE_BOOKINGS, WITH_INACTIVE_BOOKINGS;
}
package com.uva.roomBooking.Repositories;
import com.uva.roomBooking.Models.Hotel;
import org.springframework.data.jpa.repository.JpaRepository;
public interface HotelRepository extends JpaRepository<Hotel, Integer> {
}
package com.uva.roomBooking.Repositories;
import com.uva.roomBooking.Models.Room;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
public interface RoomRepository extends JpaRepository<Room, Integer> {
Optional<Room> findByIdAndHotelId(int id, int hotelId);
// Encontrar todas las habitaciones de un hotel
List<Room> findAllByHotelId(int hotelId);
// Encontrar habitaciones disponibles de un hotel en un rango de fechas
@Query("""
SELECT r FROM Room r
WHERE r.hotel.id = ?1
AND r.available = true
AND NOT EXISTS (
SELECT b FROM Booking b
WHERE b.roomId.id = r.id
AND (
b.endDate > ?2
OR
b.startDate > ?3
)
)
""")
List<Room> findAvailableRoomsByHotelAndDates(
int hotelId, LocalDate startDate, LocalDate endDate);
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment