Ignore:
Timestamp:
04/28/25 14:21:17 (3 weeks ago)
Author:
Aleksandar Panovski <apano77@…>
Branches:
main
Children:
e15e8d9
Parents:
f5b256e
Message:

Big change done fully handle_reservation_update() trigger works

Location:
src/main/java/com/example/rezevirajmasa/demo
Files:
21 edited

Legend:

Unmodified
Added
Removed
  • src/main/java/com/example/rezevirajmasa/demo/component/ReservationScheduler.java

    rf5b256e rdeea3c4  
    1 package com.example.rezevirajmasa.demo.component;public class ReservationScheduler {
     1package com.example.rezevirajmasa.demo.component;
     2
     3import com.example.rezevirajmasa.demo.service.ReservationService;
     4import jakarta.annotation.PostConstruct;
     5import org.springframework.scheduling.annotation.Scheduled;
     6import org.springframework.stereotype.Component;
     7
     8@Component
     9public class ReservationScheduler {
     10    private final ReservationService reservationService;
     11
     12    public ReservationScheduler(ReservationService reservationService) {
     13        this.reservationService = reservationService;
     14    }
     15
     16    @PostConstruct
     17    void runOnStartup() {
     18        reservationService.findReservationsToMove();
     19    }
    220}
  • src/main/java/com/example/rezevirajmasa/demo/config/ModelMapperConfig.java

    rf5b256e rdeea3c4  
    1 package com.example.rezevirajmasa.demo.config;public class ModelMapperConfig {
     1package com.example.rezevirajmasa.demo.config;
     2
     3import com.example.rezevirajmasa.demo.dto.ReservationDTO;
     4import com.example.rezevirajmasa.demo.dto.RestaurantDTO;
     5import com.example.rezevirajmasa.demo.dto.TableDTO;
     6import com.example.rezevirajmasa.demo.model.Reservation;
     7import com.example.rezevirajmasa.demo.model.Restaurant;
     8import com.example.rezevirajmasa.demo.model.TableEntity;
     9import org.modelmapper.ModelMapper;
     10import org.springframework.context.annotation.Bean;
     11import org.springframework.context.annotation.Configuration;
     12
     13@Configuration
     14public class ModelMapperConfig {
     15    @Bean
     16    public ModelMapper modelMapper() {
     17        ModelMapper modelMapper = new ModelMapper();
     18
     19        // Map Restaurant to RestaurantDTO
     20        modelMapper.typeMap(Restaurant.class, RestaurantDTO.class).addMappings(mapper -> {
     21            mapper.map(Restaurant::getTablesList, RestaurantDTO::setTablesList);
     22        });
     23
     24        // Map TableEntity to TableDTO
     25        modelMapper.typeMap(TableEntity.class, TableDTO.class).addMappings(mapper -> {
     26            mapper.map(TableEntity::getReservations, TableDTO::setReservations);
     27        });
     28
     29        // Map Reservation to ReservationDTO
     30        modelMapper.typeMap(Reservation.class, ReservationDTO.class);
     31
     32        return modelMapper;
     33    }
    234}
  • src/main/java/com/example/rezevirajmasa/demo/config/RestExceptionHandler.java

    rf5b256e rdeea3c4  
    33import com.example.rezevirajmasa.demo.dto.ErrorDto;
    44import com.example.rezevirajmasa.demo.model.exceptions.AppException;
     5import org.springframework.http.HttpStatus;
    56import org.springframework.http.ResponseEntity;
     7import org.springframework.http.converter.HttpMessageNotWritableException;
    68import org.springframework.web.bind.annotation.ControllerAdvice;
    79import org.springframework.web.bind.annotation.ExceptionHandler;
     
    1618                .body(ErrorDto.builder().message(ex.getMessage()).build());
    1719    }
     20
     21    @ExceptionHandler(HttpMessageNotWritableException.class)
     22    public ResponseEntity<String> handleHttpMessageNotWritableException(HttpMessageNotWritableException ex) {
     23        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred while processing the response.");
     24    }
    1825}
  • src/main/java/com/example/rezevirajmasa/demo/config/SecurityConfig.java

    rf5b256e rdeea3c4  
    1919import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
    2020import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
     21import org.springframework.web.cors.CorsConfiguration;
    2122import org.springframework.web.servlet.config.annotation.CorsRegistry;
    2223import org.springframework.context.annotation.Bean;
     
    2627import org.springframework.security.web.SecurityFilterChain;
    2728import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
     29
     30import java.util.List;
    2831
    2932@Configuration
     
    5558    }
    5659
    57 //    @Bean
    58 //    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    59 //        http
    60 //                .exceptionHandling(exception -> exception.authenticationEntryPoint(customerAuthenticationEntryPoint))
    61 //                .addFilterBefore(new JwtAuthFilter(userAuthProvider), BasicAuthenticationFilter.class)
    62 //                .csrf(AbstractHttpConfigurer::disable)
    63 //                .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
    64 //                .authorizeHttpRequests(requests -> requests
    65 //                        .requestMatchers(HttpMethod.POST, "/api/login", "/api/register").permitAll()
    66 //                        .requestMatchers("/", "/home").authenticated()  // Restrict `/` to authenticated users
    67 //                        .anyRequest().authenticated()
    68 //                )
    69 //                .logout(logout -> logout
    70 //                        .logoutUrl("/logout")
    71 //                        .clearAuthentication(true)
    72 //                        .invalidateHttpSession(true)
    73 //                        .deleteCookies("JSESSIONID")
    74 //                        .logoutSuccessUrl("/api/login")  // Redirect to login page after logout
    75 //                );
    76 //
    77 //        return http.build();
    78 //    }
    79 
    8060    @Bean
    8161    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    8262        http
    83                 .exceptionHandling((exception) -> exception.authenticationEntryPoint(customerAuthenticationEntryPoint))
    84                 .addFilterBefore(new JwtAuthFilter(userAuthProvider), BasicAuthenticationFilter.class)
    8563                .csrf(AbstractHttpConfigurer::disable)
    86                 .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
    87                 .authorizeHttpRequests((requests) -> requests
    88                         .requestMatchers(HttpMethod.POST, "/api/login", "/api/register").permitAll()
    89                         .anyRequest().authenticated());
     64                .authorizeHttpRequests(auth -> auth
     65                        .requestMatchers("/api/auth/**").permitAll()
     66                        .requestMatchers("/api/user/**", "/api/cuisineTypes", "/api/restaurants").authenticated()
     67                )
     68                .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
     69
    9070        return http.build();
    9171    }
  • src/main/java/com/example/rezevirajmasa/demo/dto/ReservationDTO.java

    rf5b256e rdeea3c4  
    1 package com.example.rezevirajmasa.demo.dto;public class ReservationDTO {
     1package com.example.rezevirajmasa.demo.dto;
     2
     3import com.example.rezevirajmasa.demo.model.Reservation;
     4import com.example.rezevirajmasa.demo.model.Restaurant;
     5
     6import java.math.BigDecimal;
     7import java.time.LocalDateTime;
     8
     9public class ReservationDTO {
     10    private Long reservationID;
     11    private String userEmail;
     12    private BigDecimal rating;
     13    private Long tableNumber;
     14    private LocalDateTime reservationDateTime;
     15    private LocalDateTime checkInTime;
     16    private Restaurant restaurant;
     17    private int partySize;
     18    private String status;
     19    private String specialRequests;
     20    private String paymentStatus;
     21
     22    public ReservationDTO() {
     23    }
     24
     25    public ReservationDTO(Long reservationID, String userEmail, BigDecimal rating, Long tableNumber, LocalDateTime reservationDateTime, LocalDateTime checkInTime, Restaurant restaurant, int partySize, String status, String specialRequests, String paymentStatus) {
     26        this.reservationID = reservationID;
     27        this.userEmail = userEmail;
     28        this.rating = rating;
     29        this.tableNumber = tableNumber;
     30        this.reservationDateTime = reservationDateTime;
     31        this.checkInTime = checkInTime;
     32        this.restaurant = restaurant;
     33        this.partySize = partySize;
     34        this.status = status;
     35        this.specialRequests = specialRequests;
     36        this.paymentStatus = paymentStatus;
     37    }
     38
     39    public ReservationDTO(Reservation reservation) {
     40        this.reservationID = reservation.getReservationID();
     41        this.userEmail = reservation.getUser().getEmail();
     42        this.rating = reservation.getRestaurant().getRating();
     43        this.tableNumber = reservation.getTable().getId();
     44        this.reservationDateTime = reservation.getReservationDateTime();
     45        this.checkInTime = reservation.getCheckInTime();
     46        this.restaurant = reservation.getRestaurant();
     47        this.partySize = reservation.getPartySize();
     48        this.status = reservation.getStatus();
     49        this.specialRequests = reservation.getSpecialRequests();
     50        this.paymentStatus = reservation.getPaymentStatus();
     51    }
     52
     53    public Long getReservationID() {
     54        return reservationID;
     55    }
     56
     57    public void setReservationID(Long reservationID) {
     58        this.reservationID = reservationID;
     59    }
     60
     61    public String getUserEmail() {
     62        return userEmail;
     63    }
     64
     65    public void setUserEmail(String userEmail) {
     66        this.userEmail = userEmail;
     67    }
     68
     69    public BigDecimal getRating() {
     70        return rating;
     71    }
     72
     73    public void setRating(BigDecimal rating) {
     74        this.rating = rating;
     75    }
     76
     77    public Long getTableNumber() {
     78        return tableNumber;
     79    }
     80
     81    public void setTableNumber(Long tableNumber) {
     82        this.tableNumber = tableNumber;
     83    }
     84
     85    public LocalDateTime getReservationDateTime() {
     86        return reservationDateTime;
     87    }
     88
     89    public void setReservationDateTime(LocalDateTime reservationDateTime) {
     90        this.reservationDateTime = reservationDateTime;
     91    }
     92
     93    public LocalDateTime getCheckInTime() {
     94        return checkInTime;
     95    }
     96
     97    public void setCheckInTime(LocalDateTime checkInTime) {
     98        this.checkInTime = checkInTime;
     99    }
     100
     101    public Restaurant getRestaurant() {
     102        return restaurant;
     103    }
     104
     105    public void setRestaurant(Restaurant restaurant) {
     106        this.restaurant = restaurant;
     107    }
     108
     109    public int getPartySize() {
     110        return partySize;
     111    }
     112
     113    public void setPartySize(int partySize) {
     114        this.partySize = partySize;
     115    }
     116
     117    public String getStatus() {
     118        return status;
     119    }
     120
     121    public void setStatus(String status) {
     122        this.status = status;
     123    }
     124
     125    public String getSpecialRequests() {
     126        return specialRequests;
     127    }
     128
     129    public void setSpecialRequests(String specialRequests) {
     130        this.specialRequests = specialRequests;
     131    }
     132
     133    public String getPaymentStatus() {
     134        return paymentStatus;
     135    }
     136
     137    public void setPaymentStatus(String paymentStatus) {
     138        this.paymentStatus = paymentStatus;
     139    }
    2140}
  • src/main/java/com/example/rezevirajmasa/demo/dto/RestaurantDTO.java

    rf5b256e rdeea3c4  
    1 package com.example.rezevirajmasa.demo.dto;public class RestaurantDTO {
     1package com.example.rezevirajmasa.demo.dto;
     2
     3import com.example.rezevirajmasa.demo.model.Restaurant;
     4
     5import java.util.List;
     6
     7public class RestaurantDTO {
     8    private Long restaurantId;
     9    private String name;
     10    private String cuisineType;
     11    private String address;
     12    private String phone;
     13    private String operatingHours;
     14    private String website;
     15    private String socialMediaLinks;
     16    private Double rating;
     17    private List<TableDTO> tablesList;
     18
     19    public RestaurantDTO() {
     20    }
     21
     22    public RestaurantDTO(Long restaurantId, String name, String cuisineType, String address, String phone, String operatingHours, String website, String socialMediaLinks, Double rating, List<TableDTO> tablesList) {
     23        this.restaurantId = restaurantId;
     24        this.name = name;
     25        this.cuisineType = cuisineType;
     26        this.address = address;
     27        this.phone = phone;
     28        this.operatingHours = operatingHours;
     29        this.website = website;
     30        this.socialMediaLinks = socialMediaLinks;
     31        this.rating = rating;
     32        this.tablesList = tablesList;
     33    }
     34
     35//    public RestaurantDTO(Restaurant restaurant) {
     36//        this.restaurantId = restaurant.getRestaurantId();
     37//        this.name = restaurant.getName();
     38//        this.cuisineType = restaurant.getCuisineType();
     39//        this.address = restaurant.getAddress();
     40//        this.phone = restaurant.getPhone();
     41//        this.operatingHours = restaurant.getOperatingHours();
     42//        this.website = restaurant.getWebsite();
     43//        this.socialMediaLinks = restaurant.getSocialMediaLinks();
     44//        this.rating = restaurant.getRating().doubleValue();
     45//        this.tablesList = restaurant.getTablesList();
     46//    }
     47
     48    public Long getRestaurantId() {
     49        return restaurantId;
     50    }
     51
     52    public void setRestaurantId(Long restaurantId) {
     53        this.restaurantId = restaurantId;
     54    }
     55
     56    public String getName() {
     57        return name;
     58    }
     59
     60    public void setName(String name) {
     61        this.name = name;
     62    }
     63
     64    public String getCuisineType() {
     65        return cuisineType;
     66    }
     67
     68    public void setCuisineType(String cuisineType) {
     69        this.cuisineType = cuisineType;
     70    }
     71
     72    public String getAddress() {
     73        return address;
     74    }
     75
     76    public void setAddress(String address) {
     77        this.address = address;
     78    }
     79
     80    public String getPhone() {
     81        return phone;
     82    }
     83
     84    public void setPhone(String phone) {
     85        this.phone = phone;
     86    }
     87
     88    public String getOperatingHours() {
     89        return operatingHours;
     90    }
     91
     92    public void setOperatingHours(String operatingHours) {
     93        this.operatingHours = operatingHours;
     94    }
     95
     96    public String getWebsite() {
     97        return website;
     98    }
     99
     100    public void setWebsite(String website) {
     101        this.website = website;
     102    }
     103
     104    public String getSocialMediaLinks() {
     105        return socialMediaLinks;
     106    }
     107
     108    public void setSocialMediaLinks(String socialMediaLinks) {
     109        this.socialMediaLinks = socialMediaLinks;
     110    }
     111
     112    public Double getRating() {
     113        return rating;
     114    }
     115
     116    public void setRating(Double rating) {
     117        this.rating = rating;
     118    }
     119
     120    public List<TableDTO> getTablesList() {
     121        return tablesList;
     122    }
     123
     124    public void setTablesList(List<TableDTO> tablesList) {
     125        this.tablesList = tablesList;
     126    }
    2127}
  • src/main/java/com/example/rezevirajmasa/demo/dto/TableDTO.java

    rf5b256e rdeea3c4  
    1 package com.example.rezevirajmasa.demo.dto;public class TableDTO {
     1package com.example.rezevirajmasa.demo.dto;
     2
     3import lombok.NoArgsConstructor;
     4
     5import java.util.List;
     6
     7@NoArgsConstructor
     8    public class TableDTO {
     9        private Long id;
     10        private Integer capacity;
     11        private String location;
     12        private String description;
     13        private Integer reservationDurationHours;
     14        private List<ReservationDTO> reservations;
     15
     16    public TableDTO(Long id, Integer capacity, String location, String description, Integer reservationDurationHours, List<ReservationDTO> reservations) {
     17        this.id = id;
     18        this.capacity = capacity;
     19        this.location = location;
     20        this.description = description;
     21        this.reservationDurationHours = reservationDurationHours;
     22        this.reservations = reservations;
     23    }
     24
     25    // Getters and setters
     26    public Long getId() {
     27        return id;
     28    }
     29
     30    public void setId(Long id) {
     31        this.id = id;
     32    }
     33
     34    public Integer getCapacity() {
     35        return capacity;
     36    }
     37
     38    public void setCapacity(Integer capacity) {
     39        this.capacity = capacity;
     40    }
     41
     42    public String getLocation() {
     43        return location;
     44    }
     45
     46    public void setLocation(String location) {
     47        this.location = location;
     48    }
     49
     50    public String getDescription() {
     51        return description;
     52    }
     53
     54    public void setDescription(String description) {
     55        this.description = description;
     56    }
     57
     58    public Integer getReservationDurationHours() {
     59        return reservationDurationHours;
     60    }
     61
     62    public void setReservationDurationHours(Integer reservationDurationHours) {
     63        this.reservationDurationHours = reservationDurationHours;
     64    }
     65
     66    public List<ReservationDTO> getReservations() {
     67        return reservations;
     68    }
     69
     70    public void setReservations(List<ReservationDTO> reservations) {
     71        this.reservations = reservations;
     72    }
    273}
     74
  • src/main/java/com/example/rezevirajmasa/demo/model/Reservation.java

    rf5b256e rdeea3c4  
    11package com.example.rezevirajmasa.demo.model;
    22
     3import com.fasterxml.jackson.annotation.JsonBackReference;
     4import com.fasterxml.jackson.annotation.JsonManagedReference;
    35import jakarta.persistence.*;
    46
     7import java.math.BigDecimal;
    58import java.time.LocalDateTime;
    69import java.time.LocalTime;
     
    1720    @ManyToOne
    1821    @JoinColumn(name = "UserID")
     22    @JsonManagedReference
    1923    private User user;
    2024
    2125    @ManyToOne
    2226    @JoinColumn(name = "TableNumber", nullable = false)
     27    @JsonBackReference
    2328    private TableEntity table;
    2429
     
    3641    private String specialRequests;
    3742
    38     @Column(name = "Status", length = 20, nullable = false, columnDefinition = "VARCHAR default 'Pending'")
     43    @Column(name = "Status", length = 20, nullable = false)
    3944    private String status;
    4045
     
    4651
    4752//    @Column(name = "TotalAmount", precision = 8, scale = 2)
    48 //    private BigDecimal totalAmount;//rezervacija so depozit ako e
     53//    private BigDecimal totalAmount;
    4954
    5055    @Column(name = "PaymentStatus", length = 20, nullable = false, columnDefinition = "VARCHAR default 'Unpaid'")
     
    5560    }
    5661
    57     // Constructors, getters, setters, and other methods...
    58 
    5962    @PrePersist
    6063    private void prePersist() {
    61         // Set default values or perform any pre-persistence logic if needed
    6264        if (status == null) {
    6365            status = "Pending";
  • src/main/java/com/example/rezevirajmasa/demo/model/Restaurant.java

    rf5b256e rdeea3c4  
    1212@Table(name = "restaurants")
    1313public class Restaurant {
    14 
    1514    @Id
    1615    @GeneratedValue(strategy = GenerationType.IDENTITY)
     
    4241    private BigDecimal rating;
    4342
    44     @JsonManagedReference
    45     @OneToMany(mappedBy = "restaurant", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
     43    @JsonIgnore
     44    @OneToMany(mappedBy = "restaurant", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    4645    private List<TableEntity> tablesList;
    4746
  • src/main/java/com/example/rezevirajmasa/demo/model/TableEntity.java

    rf5b256e rdeea3c4  
    22
    33import com.fasterxml.jackson.annotation.JsonBackReference;
     4import com.fasterxml.jackson.annotation.JsonIgnore;
     5import com.fasterxml.jackson.annotation.JsonManagedReference;
    46import jakarta.persistence.*;
     7import lombok.Getter;
     8import lombok.Setter;
    59import org.springframework.web.bind.annotation.ModelAttribute;
    610
     
    1519
    1620@Entity
     21@Getter
     22@Setter
    1723@Table(name = "tables")
    1824public class TableEntity {
     
    3945    private String description;
    4046
    41     @ElementCollection(fetch = FetchType.EAGER)
    42     @CollectionTable(name = "table_time_slots", joinColumns = @JoinColumn(name = "table_id"))
    43     @Column(name = "time_slot", columnDefinition = "timestamp without time zone")
    44     @OrderBy("time_slot ASC")
    45     private List<LocalDateTime> timeSlots = new ArrayList<>();
    46 
    4747    @Column(name = "reservation_duration_hours", nullable = true)
    4848    private int reservationDurationHours = 2;
     49
     50    @OneToMany(mappedBy = "table", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
     51    @JsonIgnore
     52    private List<Reservation> reservations = new ArrayList<>(); // Store reservations, not time slots
     53
    4954    public void cleanUnusedTimeSlots(LocalDate threeDaysAgo) {
    50         // Iterate over the time slots and remove those that are in the past
    51         timeSlots.removeIf(timeSlot -> timeSlot.isBefore(threeDaysAgo.atStartOfDay()));
     55        reservations.removeIf(reservation -> reservation.getReservationDateTime().toLocalDate().isBefore(threeDaysAgo));
    5256    }
    5357
    54     public void addTimeSlot(LocalDateTime timeSlot) {
    55         this.timeSlots.add(timeSlot);
    56     }
    57 
    58 
    59     @Transient
    60     public boolean isAvailable(LocalDateTime desiredTimeSlot) {
    61         if (timeSlots == null || timeSlots.isEmpty()) {
    62             return true;
     58    public boolean isAvailable(LocalDateTime desiredTimeSlot, int partySize) {
     59        if (this.capacity < partySize) {
     60            return false;
    6361        }
    6462
    65         for (LocalDateTime reservedTimeSlot : timeSlots) {
    66             LocalDateTime endTime = reservedTimeSlot.plusHours(reservationDurationHours);
     63        for (Reservation reservation : reservations) {
     64            LocalDateTime startTime = reservation.getReservationDateTime();
     65            LocalDateTime endTime = startTime.plusHours(reservation.getTable().getReservationDurationHours());
    6766
    68             // Check if the desired time slot overlaps with any existing reservation
    69             if ((desiredTimeSlot.equals(reservedTimeSlot) || desiredTimeSlot.isAfter(reservedTimeSlot))
     67            if ((desiredTimeSlot.isEqual(startTime) || desiredTimeSlot.isAfter(startTime))
    7068                    && desiredTimeSlot.isBefore(endTime)) {
    71                 return false; // Table is reserved for the desired time slot
     69                return false;
    7270            }
    7371        }
    7472
    75         return true; // No conflicting reservations, table is available
     73        return true;
    7674    }
    7775
    78     public boolean hasTimeSlot(LocalDateTime dateTime) {
    79         // Check if the given dateTime exists in the list of time slots
    80         return timeSlots.contains(dateTime);
     76    public void addReservation(Reservation reservation) {
     77        LocalDateTime startTime = reservation.getReservationDateTime();
     78        LocalDateTime endTime = startTime.plusHours(reservation.getTable().getReservationDurationHours());
     79        for (LocalDateTime timeSlot = startTime; timeSlot.isBefore(endTime); timeSlot = timeSlot.plusMinutes(15)) {
     80
     81        }
     82        this.reservations.add(reservation);
    8183    }
    8284
    83     public List<LocalDateTime> initializeTimeSlots(LocalTime startTime, LocalTime endTime, List<LocalDate> dates, List<LocalDateTime> listOfUsedCheckIns) {
    84         // Check if time slots are already initialized and cover all provided dates
    85         List<LocalDate> generatedDates = timeSlots.stream()
    86                 .map(LocalDateTime::toLocalDate)
    87                 .distinct()
    88                 .toList();
     85    public void removeReservation(Reservation reservation) {
     86        LocalDateTime startTime = reservation.getReservationDateTime();
     87        LocalDateTime endTime = startTime.plusHours(reservation.getTable().getReservationDurationHours());
     88        for (LocalDateTime timeSlot = startTime; timeSlot.isBefore(endTime); timeSlot = timeSlot.plusMinutes(15)) {
    8989
    90         if (generatedDates.containsAll(dates) && dates.containsAll(generatedDates)) {
    91             System.out.println("Time slots already cover all provided dates.");
    92             return timeSlots;
    9390        }
    94 
    95         // Generate time slots for the remaining dates
    96         for (LocalDate date : dates) {
    97             if (!generatedDates.contains(date)) {
    98                 LocalTime currentTime = startTime;
    99                 while (currentTime.isBefore(LocalTime.of(23, 0))) {
    100                     LocalDateTime currentDateTime = LocalDateTime.of(date, currentTime);
    101                     boolean isUsed = false;
    102                     if (listOfUsedCheckIns != null) {
    103                         for (LocalDateTime checkIns : listOfUsedCheckIns) {
    104                             if (checkIns.isEqual(currentDateTime)) {
    105                                 isUsed = true;
    106                                 break;
    107                             }
    108                         }
    109                     }
    110                     if (!isUsed) {
    111                         timeSlots.add(currentDateTime);
    112                         System.out.println("Added time slot: " + currentDateTime); // Debug output
    113                     } else {
    114                         // Remove conflicting time slots
    115                         timeSlots.removeIf(x -> x.isAfter(currentDateTime.minusHours(2)) && x.isBefore(currentDateTime.plusHours(2)));
    116                     }
    117                     // Increment currentTime
    118                     currentTime = currentTime.plusMinutes(15);
    119                 }
    120             }
    121         }
    122 
    123         return timeSlots;
     91        this.reservations.remove(reservation);
    12492    }
    12593
    126 
    127 
    128     public TableEntity(Restaurant restaurant, int capacity, String location, boolean isSmokingArea, String description, List<LocalDateTime> timeSlots, int reservationDurationHours) {
     94    public TableEntity(Restaurant restaurant, int capacity, String location, boolean isSmokingArea, String description, int reservationDurationHours) {
    12995        this.restaurant = restaurant;
    13096        this.capacity = capacity;
     
    13298        this.isSmokingArea = isSmokingArea;
    13399        this.description = description;
    134         this.timeSlots = timeSlots;
    135100        this.reservationDurationHours = reservationDurationHours;
    136101    }
     
    138103    public TableEntity() {
    139104    }
    140 
    141     public Long getId() {
    142         return id;
    143     }
    144 
    145     public void setId(Long id) {
    146         this.id = id;
    147     }
    148 
    149     public Restaurant getRestaurant() {
    150         return restaurant;
    151     }
    152 
    153     public void setRestaurant(Restaurant restaurant) {
    154         this.restaurant = restaurant;
    155     }
    156 
    157     public int getCapacity() {
    158         return capacity;
    159     }
    160 
    161     public void setCapacity(int capacity) {
    162         this.capacity = capacity;
    163     }
    164 
    165     public String getLocation() {
    166         return location;
    167     }
    168 
    169     public void setLocation(String location) {
    170         this.location = location;
    171     }
    172 
    173     public void setSmokingArea(Boolean isSmokingArea) {
    174         this.isSmokingArea = isSmokingArea;
    175     }
    176 
    177     public void setSmokingArea(boolean smokingArea) {
    178         isSmokingArea = smokingArea;
    179     }
    180 
    181     public String getDescription() {
    182         return description;
    183     }
    184 
    185     public void setDescription(String description) {
    186         this.description = description;
    187     }
    188 
    189     public List<LocalDateTime> getTimeSlots() {
    190         return timeSlots;
    191     }
    192 
    193     public void setTimeSlots(List<LocalDateTime> timeSlots) {
    194         this.timeSlots = timeSlots;
    195     }
    196 
    197     public int getReservationDurationHours() {
    198         return reservationDurationHours;
    199     }
    200 
    201     public void setReservationDurationHours(int reservationDurationHours) {
    202         this.reservationDurationHours = reservationDurationHours;
    203     }
    204105}
  • src/main/java/com/example/rezevirajmasa/demo/model/User.java

    rf5b256e rdeea3c4  
    11package com.example.rezevirajmasa.demo.model;
    22
     3import com.fasterxml.jackson.annotation.JsonBackReference;
    34import jakarta.persistence.*;
    45import lombok.AllArgsConstructor;
     
    4849
    4950    @Column(name = "RegistrationDate", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
    50     @Temporal(TemporalType.TIMESTAMP)
    5151    private Date registrationDate;
    5252}
  • src/main/java/com/example/rezevirajmasa/demo/repository/ReservationRepository.java

    rf5b256e rdeea3c4  
    1515    List<Reservation> findByCheckInTimeAfterAndCheckInTimeBefore(LocalDateTime startTime, LocalDateTime endTime);
    1616    List<Reservation> findALlByUserAndCheckInTimeBefore(User user, LocalDateTime now);
     17    List<Reservation> findAllByUser(User user);
     18
     19    List<Reservation> findAllByUserAndCheckInTimeAfter(User user, LocalDateTime now);
     20
     21    List<Reservation> findAllByUserAndCheckInTimeBefore(User user, LocalDateTime now);
     22    List<Reservation> findAllByTableAndCheckInTime(TableEntity table, LocalDateTime now);
     23    List<Reservation> findAllByRestaurantAndCheckInTimeAfter(Restaurant restaurant, LocalDateTime now);
    1724}
  • src/main/java/com/example/rezevirajmasa/demo/repository/TableRepository.java

    rf5b256e rdeea3c4  
    1212public interface TableRepository extends JpaRepository<TableEntity, Long> {
    1313    List<TableEntity> findByRestaurant(Restaurant restaurant);
    14 //    @Query("SELECT t FROM TableEntity t JOIN FETCH t.restaurant WHERE t.id = :id")
    15 //    TableEntity findTableEntityByIdWithRestaurant(@Param("id") Long id);
    16     List<TableEntity> findAllByTimeSlotsContainingAndCapacityGreaterThanEqual(LocalDateTime timeSlot, Integer partySize);
     14    List<TableEntity> findAllByCapacityGreaterThanEqual(int capacity);
     15    @Query("SELECT t FROM TableEntity t WHERE t.capacity >= :capacity AND NOT EXISTS (" +
     16            "SELECT r FROM t.reservations r WHERE r.checkInTime <= :checkOutTime AND r.checkOutTime >= :checkInTime)")
     17    List<TableEntity> findAvailableTables(@Param("checkInTime") LocalDateTime checkInTime,
     18                                          @Param("checkOutTime") LocalDateTime checkOutTime,
     19                                          @Param("capacity") int capacity);
    1720}
  • src/main/java/com/example/rezevirajmasa/demo/service/ReservationHistoryService.java

    rf5b256e rdeea3c4  
    1111public interface ReservationHistoryService {
    1212    public void moveReservationToHistory(Reservation reservation, String status, String cancellationReason);
     13//    public void moveReservationToCancelled(Reservation reservation, String status, String cancellationReason);
    1314    public void moveReservationsToPast(List<Restaurant.ReservationHistory> reservationsToMove);
    1415    List<Restaurant.ReservationHistory> findByUser(User user);
  • src/main/java/com/example/rezevirajmasa/demo/service/ReservationService.java

    rf5b256e rdeea3c4  
    11package com.example.rezevirajmasa.demo.service;
    22
     3import com.example.rezevirajmasa.demo.dto.ReservationDTO;
     4import com.example.rezevirajmasa.demo.dto.RestaurantDTO;
    35import com.example.rezevirajmasa.demo.model.*;
     6import org.springframework.scheduling.annotation.Scheduled;
    47import org.springframework.security.core.userdetails.UserDetails;
    58
     
    811
    912public interface ReservationService {
    10     public void makeReservation(User user, TableEntity table, Restaurant restaurant, LocalDateTime localDateTime, LocalDateTime checkInTime, int partySize, String specialRequests);
    11     public Reservation makeReservationRest(Reservation reservation, User user);
     13    public Reservation makeReservationRest(ReservationDTO reservation, User user);
    1214    public List<Reservation> listAll();
     15    public Reservation updateReservation(Long reservationId, ReservationDTO reservationDTO, User user);
     16    public List<Reservation> reservationsForTable(TableEntity table);
    1317    public Reservation findById(Long id);
    1418    public Reservation getReservationById(Long reservationId);
    1519    public boolean cancelReservation(Long reservationId);
    1620    public List<Reservation> findReservationByUser(User user);
     21    public List<Reservation> findAllByUser(User user);
    1722    public List<Reservation> findReservationsByUserPast(User user);
    1823    public List<Reservation> findReservationsByTableAndDateRange(TableEntity table, LocalDateTime startDateTime, LocalDateTime endDateTime);
    19     List<Reservation> findReservationsToMove(LocalDateTime currentTime);
     24    @Scheduled(cron = "0 0 0 * * ?")
     25    void findReservationsToMove();
    2026    void deleteReservation(Long reservationID);
     27
     28    List<Reservation> findAllByRestaurant(Restaurant restaurant);
    2129}
  • src/main/java/com/example/rezevirajmasa/demo/service/RestaurantService.java

    rf5b256e rdeea3c4  
    11package com.example.rezevirajmasa.demo.service;
    22
     3import com.example.rezevirajmasa.demo.dto.RestaurantDTO;
    34import com.example.rezevirajmasa.demo.model.Restaurant;
    45import com.example.rezevirajmasa.demo.model.TableEntity;
     
    1011
    1112public interface RestaurantService {
    12     List<Restaurant> listall();
    13 //    void save(String name, String cuisineType, String address, String phone, String operatingHours, String website, String socialMediaLinks, BigDecimal rating, List<Long> tablesList);
     13    List<RestaurantDTO> listall();
     14    List<Restaurant> listAll();
     15    //    void save(String name, String cuisineType, String address, String phone, String operatingHours, String website, String socialMediaLinks, BigDecimal rating, List<Long> tablesList);
    1416//    void save(String name, String cuisineType, String address, String phone, String operatingHours, String website, String socialMediaLinks, BigDecimal rating, int numberOfTables, int tableCapacity, String location, Boolean isSmokingArea, String description);
    1517    void save(Restaurant restaurant, int numberOfTables, List<Integer> tableCapacities, List<String> tableLocations, List<String> tableSmokingAreas, List<String> tableDescriptions);
    1618    Restaurant updateRestaurant(Long restaurantId, String name, String cuisineType, String address, String phone, String operatingHours, String website, String socialMediaLinks, BigDecimal rating, List<Long> tablesList);
    1719    Restaurant deleteRestaurant(Long restaurantId);
    18     Restaurant findById(Long restaurantId);
     20    RestaurantDTO findById(Long restaurantId);
     21    Restaurant findByIdRestaurant(Long restaurantId);
    1922    List<Restaurant> listRestaurantBy(String search);
    2023    List<Restaurant> getRestaurantsWithAvailableTimeSlotsForToday();
    2124    public List<Restaurant> findRestaurantsByDateTimeAndPartySize(LocalDateTime dateTime, int partySize, String search);
    22     public List<Restaurant> findRestaurantsBySearchParams(LocalDateTime dateTime, int partySize, String search);
     25//    public List<Restaurant> findRestaurantsBySearchParams(LocalDateTime dateTime, int partySize, String search);
    2326    public List<String> findALlCuisineTypes();
    24     List<Restaurant> findRestaurantsByCuisineType(String param);
     27    List<RestaurantDTO> findRestaurantsByCuisineType(String param);
     28    public List<RestaurantDTO> findRestaurantsBySearchParams(LocalDateTime dateTime, int partySize, String search);
    2529}
  • src/main/java/com/example/rezevirajmasa/demo/service/TableService.java

    rf5b256e rdeea3c4  
    11package com.example.rezevirajmasa.demo.service;
    22
     3import com.example.rezevirajmasa.demo.dto.TableDTO;
    34import com.example.rezevirajmasa.demo.model.Restaurant;
    45import com.example.rezevirajmasa.demo.model.TableEntity;
     
    1213public interface TableService {
    1314    List<TableEntity> listall();
    14     TableEntity findById(Long id);
    15 //    void save(int numberOfTables, List<Integer> tableCapacities, List<String> tableLocations, List<String> tableSmokingAreas, List<String> tableDescriptions, Restaurant restaurant);
     15    TableDTO findById(Long id);
     16    TableEntity findByIdTable(Long id);
     17    void save(int numberOfTables, List<Integer> tableCapacities, List<String> tableLocations, List<String> tableSmokingAreas, List<String> tableDescriptions, Restaurant restaurant);
    1618    void deleteTimeSlotsForReservation(Long tableId, LocalDateTime reservationTime);
    1719    void canceledTimeSlots(Long tableId, LocalDateTime reservationTime);
  • src/main/java/com/example/rezevirajmasa/demo/service/impl/ReservationImpl.java

    rf5b256e rdeea3c4  
    11package com.example.rezevirajmasa.demo.service.impl;
    22
     3import com.example.rezevirajmasa.demo.dto.ReservationDTO;
     4import com.example.rezevirajmasa.demo.dto.RestaurantDTO;
    35import com.example.rezevirajmasa.demo.dto.UserDto;
    46import com.example.rezevirajmasa.demo.mappers.UserMapper;
     
    1214import com.example.rezevirajmasa.demo.service.ReservationHistoryService;
    1315import com.example.rezevirajmasa.demo.service.ReservationService;
     16import com.example.rezevirajmasa.demo.service.RestaurantService;
    1417import com.example.rezevirajmasa.demo.service.UserService;
    1518import org.springframework.beans.factory.annotation.Autowired;
     
    3134@Service
    3235public class ReservationImpl implements ReservationService {
     36
    3337    @Autowired
    3438    private TableRepository tableRepository;
     
    5155
    5256    @Override
    53     public void makeReservation(User user, TableEntity table, Restaurant restaurant, LocalDateTime localDateTime, LocalDateTime checkInTime, int partySize, String specialRequests) {
    54         if (!table.isAvailable(checkInTime)) {
    55             // Handle unavailability (throw an exception, return a specific response, etc.)
    56             throw new RuntimeException("Table not available for the specified time slot");
    57         }
    58 
    59         Reservation reservation =
    60                 new Reservation(user, table, restaurant, LocalDateTime.now(), partySize, specialRequests, "Reserved", checkInTime, checkInTime.plusHours(2), null);
    61 
    62 //        // Update table status or perform additional logic if needed
    63 //        tableRepository.save(table);
    64 
    65         // Save the reservation
    66         reservationRepository.save(reservation);
    67     }
    68 
    69     @Override
    70     public Reservation makeReservationRest(Reservation reservation, User user) {
    71         Optional<TableEntity> optionalTable = tableRepository.findById(reservation.getTable().getId());
     57    public Reservation makeReservationRest(ReservationDTO reservationDTO, User user) {
     58        Reservation reservation = new Reservation();
     59
     60        Optional<TableEntity> optionalTable = tableRepository.findById(reservationDTO.getTableNumber());
     61
    7262        if (optionalTable.isPresent()) {
    7363            TableEntity table = optionalTable.get();
    7464
     65            LocalDateTime reservationTime = reservationDTO.getReservationDateTime();
     66            LocalDateTime startTime = reservationTime.minusHours(2);
     67            LocalDateTime endTime = reservationTime.plusHours(2);
     68
     69            boolean hasConflict = table.getReservations().stream()
     70                    .anyMatch(existingReservation -> {
     71                        LocalDateTime existingStartTime = existingReservation.getCheckInTime();
     72                        LocalDateTime existingEndTime = existingReservation.getCheckOutTime();
     73
     74                        boolean scenario1 = existingStartTime.isBefore(startTime) && existingEndTime.isAfter(startTime);
     75
     76                        boolean scenario2 = existingStartTime.isBefore(endTime) && existingEndTime.isAfter(startTime);
     77
     78                        boolean scenario3 = existingStartTime.isAfter(startTime) && existingEndTime.isBefore(endTime);
     79
     80                        boolean scenario4 = existingStartTime.isBefore(startTime) && existingEndTime.isAfter(endTime);
     81
     82                        return scenario1 || scenario2 || scenario3 || scenario4;
     83                    });
     84            if (hasConflict) {
     85                throw new InvalidReservationException("Unsuccessful reservation -> time slot not available");
     86            }
     87
     88            reservation.setTable(table);
     89            reservation.setReservationDateTime(LocalDateTime.now());
     90            reservation.setSpecialRequests(reservationDTO.getSpecialRequests());
     91            reservation.setPartySize(reservationDTO.getPartySize());
     92            reservation.setStatus(reservationDTO.getStatus() != null ? reservationDTO.getStatus() : "Pending");
     93            reservation.setPaymentStatus(reservationDTO.getPaymentStatus() != null ? reservationDTO.getPaymentStatus() : "Unpaid");
    7594            reservation.setUser(user);
    76 
    77             LocalDateTime startTime = reservation.getCheckInTime().minusHours(2);
    78             LocalDateTime endTime = reservation.getCheckInTime().plusHours(2);
    79 
    80             table.getTimeSlots().removeIf(
    81                     x -> x.isAfter(startTime) && x.isBefore(endTime)
    82             );
     95            reservation.setRestaurant(reservationDTO.getRestaurant());
     96            reservation.setCheckInTime(reservationTime);
    8397            reservation.setReservationDateTime(LocalDateTime.now());
     98            reservation.setCheckOutTime(reservationTime.plusHours(2));
     99            reservation.setRestaurant(reservationDTO.getRestaurant());
     100
    84101            return reservationRepository.save(reservation);
    85102        } else {
    86             throw new InvalidReservationException("Unsuccessful reservation -> time slot not available");
    87         }
    88     }
    89 
     103            throw new InvalidReservationException("Invalid table number -> table not found");
     104        }
     105    }
     106
     107    @Override
     108    public Reservation updateReservation(Long reservationId, ReservationDTO reservationDTO, User user) {
     109        Reservation existingReservation = findById(reservationId);
     110
     111        if (!existingReservation.getCheckInTime().equals(reservationDTO.getReservationDateTime())) {
     112            TableEntity table = existingReservation.getTable();
     113            table.removeReservation(existingReservation);
     114
     115            LocalDateTime newStartTime = reservationDTO.getReservationDateTime().minusHours(2);
     116            LocalDateTime newEndTime = reservationDTO.getReservationDateTime().plusHours(2);
     117            boolean hasConflict = table.getReservations().stream()
     118                    .anyMatch(r -> r.getCheckInTime().isAfter(newStartTime) && r.getCheckInTime().isBefore(newEndTime));
     119
     120            if (hasConflict) {
     121                throw new InvalidReservationException("New time slot is not available.");
     122            }
     123
     124            table.addReservation(existingReservation);
     125        }
     126
     127        existingReservation.setCheckInTime(reservationDTO.getReservationDateTime());
     128        existingReservation.setCheckOutTime(reservationDTO.getReservationDateTime().plusHours(2));
     129        existingReservation.setReservationDateTime(LocalDateTime.now());
     130        existingReservation.setPartySize(reservationDTO.getPartySize());
     131        existingReservation.setSpecialRequests(reservationDTO.getSpecialRequests());
     132        existingReservation.setStatus(reservationDTO.getStatus() != null ? reservationDTO.getStatus() : existingReservation.getStatus());
     133        existingReservation.setPaymentStatus(reservationDTO.getPaymentStatus() != null ? reservationDTO.getPaymentStatus() : existingReservation.getPaymentStatus());
     134
     135        return reservationRepository.save(existingReservation);
     136    }
    90137
    91138    @Override
    92139    public List<Reservation> listAll() {
    93140        return reservationRepository.findAll();
     141    }
     142
     143    @Override
     144    public List<Reservation> reservationsForTable(TableEntity table) {
     145        return reservationRepository.findAllByTableAndCheckInTime(table, LocalDateTime.now());
    94146    }
    95147
     
    106158            TableEntity table = reservation.getTable();
    107159
    108             LocalDateTime from = reservation.getCheckInTime().minusHours(2);
    109             LocalDateTime till = reservation.getCheckInTime().plusHours(2);
    110 
    111             String[] hours = table.getRestaurant().getOperatingHours().split("-");
    112             LocalTime openingHourTime = LocalTime.parse(hours[0], DateTimeFormatter.ofPattern("HH:mm"));
    113             LocalDateTime openingDateTime = openingHourTime.atDate(from.toLocalDate());
    114             LocalTime closingHourTime = LocalTime.of(22,45);
    115             LocalDateTime closingDateTime = closingHourTime.atDate(till.toLocalDate());
    116             if(from.isBefore(openingDateTime)) {
    117                 from = openingDateTime;
    118             }
    119             if(till.isAfter(closingDateTime)) {
    120                 till = closingDateTime;
    121             }
    122             while (from.isBefore(reservation.getCheckInTime().plusHours(2))) {
    123                 table.addTimeSlot(from);
    124                 from = from.plusMinutes(15);
    125             }
     160            table.removeReservation(reservation);
     161
    126162            reservationHistoryService.moveReservationToHistory(reservation, "Canceled", "Canceled by user");
    127163            reservationRepository.delete(reservation);
     164
    128165            return true;
    129166        } else {
     
    132169    }
    133170
    134 
    135171    @Override
    136172    public List<Reservation> findReservationByUser(User user) {
    137173        LocalDateTime now = LocalDateTime.now();
    138         return reservationRepository.findALlByUserAndCheckInTimeAfter(user, now);
     174        return reservationRepository.findAllByUserAndCheckInTimeAfter(user, now);
     175    }
     176
     177    @Override
     178    public List<Reservation> findAllByUser(User user) {
     179        return reservationRepository.findAllByUser(user);
    139180    }
    140181
     
    142183    public List<Reservation> findReservationsByUserPast(User user) {
    143184        LocalDateTime now = LocalDateTime.now();
    144         return reservationRepository.findALlByUserAndCheckInTimeBefore(user, now);
     185        return reservationRepository.findAllByUserAndCheckInTimeBefore(user, now);
    145186    }
    146187
     
    151192
    152193    @Override
    153     public List<Reservation> findReservationsToMove(LocalDateTime currentTime) {
    154         return reservationRepository.findAllByCheckInTimeBefore(currentTime);
     194    public void findReservationsToMove() {
     195        List<Reservation> pastReservations = reservationRepository.findAllByCheckInTimeBefore(LocalDateTime.now());
     196        for(Reservation reservation : pastReservations) {
     197            reservationHistoryService.moveReservationToHistory(reservation, "successful", "/");
     198            reservationRepository.delete(reservation);
     199        }
    155200    }
    156201
     
    160205        reservationRepository.delete(reservation);
    161206    }
     207
     208    @Override
     209    public List<Reservation> findAllByRestaurant(Restaurant restaurant) {
     210        return reservationRepository.findAllByRestaurantAndCheckInTimeAfter(restaurant, LocalDateTime.now());
     211    }
    162212}
  • src/main/java/com/example/rezevirajmasa/demo/service/impl/RestaurantServiceImpl.java

    rf5b256e rdeea3c4  
    11package com.example.rezevirajmasa.demo.service.impl;
    22
     3import com.example.rezevirajmasa.demo.dto.ReservationDTO;
     4import com.example.rezevirajmasa.demo.dto.RestaurantDTO;
     5import com.example.rezevirajmasa.demo.dto.TableDTO;
     6import com.example.rezevirajmasa.demo.model.Reservation;
    37import com.example.rezevirajmasa.demo.model.Restaurant;
    48import com.example.rezevirajmasa.demo.model.TableEntity;
     9import com.example.rezevirajmasa.demo.model.User;
    510import com.example.rezevirajmasa.demo.model.exceptions.InvalidRestaurantIdException;
    611import com.example.rezevirajmasa.demo.repository.RestaurantRepository;
    712import com.example.rezevirajmasa.demo.repository.TableRepository;
     13import com.example.rezevirajmasa.demo.service.ReservationService;
    814import com.example.rezevirajmasa.demo.service.RestaurantService;
    915import com.example.rezevirajmasa.demo.service.TableService;
    1016import com.sun.tools.jconsole.JConsoleContext;
    1117import jakarta.transaction.Transactional;
     18import org.openqa.selenium.InvalidArgumentException;
    1219import org.springframework.stereotype.Service;
    13 
     20import org.modelmapper.ModelMapper;
    1421import java.time.LocalDate;
    1522import java.time.LocalDateTime;
     
    3138    private final TableRepository tableRepository;
    3239    private final TableService tableService;
    33 
    34     public RestaurantServiceImpl(RestaurantRepository restaurantRepository, TableRepository tableRepository, TableService tableService) {
     40    private final ReservationService reservationService;
     41    private ModelMapper modelMapper = new ModelMapper();
     42
     43    public RestaurantServiceImpl(RestaurantRepository restaurantRepository, TableRepository tableRepository, TableService tableService, ReservationService reservationService) {
    3544        this.restaurantRepository = restaurantRepository;
    3645        this.tableRepository = tableRepository;
    3746        this.tableService = tableService;
    38     }
    39 
    40     @Override
    41     public List<Restaurant> listall() {
     47        this.reservationService = reservationService;
     48    }
     49
     50    @Override
     51    public List<RestaurantDTO> listall() {
     52        List<Restaurant> restaurants = restaurantRepository.findAll();
     53
     54        List<RestaurantDTO> restaurantDTOS = new ArrayList<>();
     55
     56        for (Restaurant restaurant : restaurants) {
     57            RestaurantDTO restaurantDTO = modelMapper.map(restaurant, RestaurantDTO.class);
     58            List<TableDTO> tableDTOS = new ArrayList<>();
     59            for (TableEntity table : restaurant.getTablesList()) {
     60                TableDTO tableDTO = modelMapper.map(table, TableDTO.class);
     61                List<ReservationDTO> reservationDTOS = new ArrayList<>();
     62                for (Reservation reservation : table.getReservations()) {
     63                    ReservationDTO reservationDTO = modelMapper.map(reservation, ReservationDTO.class);
     64
     65                    reservationDTOS.add(reservationDTO);
     66                }
     67                tableDTO.setReservations(reservationDTOS);
     68                tableDTOS.add(tableDTO);
     69            }
     70            restaurantDTO.setTablesList(tableDTOS);
     71            restaurantDTOS.add(restaurantDTO);
     72        }
     73        return restaurantDTOS;
     74    }
     75
     76    @Override
     77    public List<Restaurant> listAll() {
    4278        return restaurantRepository.findAll();
    4379    }
     
    5187    @Override
    5288    public void save(Restaurant restaurant, int numberOfTables, List<Integer> tableCapacities, List<String> tableLocations, List<String> tableSmokingAreas, List<String> tableDescriptions) {
     89        if (numberOfTables != tableCapacities.size() || numberOfTables != tableLocations.size() || numberOfTables != tableSmokingAreas.size() || numberOfTables != tableDescriptions.size()) {
     90            throw new IllegalArgumentException("Mismatched table data. Number of tables does not match the size of the input lists.");
     91        }
     92
    5393        restaurantRepository.save(restaurant);
    5494        String[] hours = restaurant.getOperatingHours().split("-");
     
    60100            LocalTime startTime = LocalTime.parse(hours[0], DateTimeFormatter.ofPattern("HH:mm"));
    61101            LocalTime endTime = LocalTime.parse(hours[1], DateTimeFormatter.ofPattern("HH:mm"));
    62             System.out.println("IsBefore: " + startTime.isBefore(endTime) + " and equals: " + startTime.equals(endTime));
    63102
    64103            for (int i = 0; i < numberOfTables; i++) {
    65104                TableEntity table = new TableEntity();
    66 
    67 //                table.initializeTimeSlots(startTime, endTime);
    68 
    69105                table.setCapacity(tableCapacities.get(i));
    70106                table.setLocation(tableLocations.get(i));
    71 
    72                 String smokingAreaString = tableSmokingAreas.get(i);
    73                 table.setSmokingArea(smokingAreaString.equalsIgnoreCase("on"));
     107                table.setSmokingArea(tableSmokingAreas.get(i).equalsIgnoreCase("on"));
    74108                table.setDescription(tableDescriptions.get(i));
    75109                table.setRestaurant(restaurant);
    76 
    77110                tableRepository.save(table);
    78111            }
     
    84117    }
    85118    @Override
    86     public Restaurant findById(Long restaurantId) {
    87         return restaurantRepository.findById(restaurantId).orElseThrow(InvalidRestaurantIdException::new);
    88     }
     119    public RestaurantDTO findById(Long restaurantId) {
     120        Restaurant restaurant = restaurantRepository.findById(restaurantId)
     121                .orElseThrow(InvalidRestaurantIdException::new);
     122
     123        RestaurantDTO restaurantDTO = modelMapper.map(restaurant, RestaurantDTO.class);
     124
     125        List<TableDTO> tableDTOS = new ArrayList<>();
     126        for (TableEntity table : restaurant.getTablesList()) {
     127            TableDTO tableDTO = modelMapper.map(table, TableDTO.class);
     128
     129            List<ReservationDTO> reservationDTOS = new ArrayList<>();
     130            for (Reservation reservation : table.getReservations()) {
     131                ReservationDTO reservationDTO = modelMapper.map(reservation, ReservationDTO.class);
     132                reservationDTOS.add(reservationDTO);
     133            }
     134
     135            tableDTO.setReservations(reservationDTOS);
     136            tableDTOS.add(tableDTO);
     137        }
     138
     139        restaurantDTO.setTablesList(tableDTOS);
     140
     141        return restaurantDTO;
     142    }
     143
     144    @Override
     145    public Restaurant findByIdRestaurant(Long restaurantId) {
     146        return restaurantRepository.findById(restaurantId).orElseThrow(()-> new InvalidArgumentException("No restaurant with provided id"));
     147    }
     148
    89149
    90150    @Override
     
    115175    @Override
    116176    public List<Restaurant> listRestaurantBy(String search) {
    117         // Get all restaurants from the repository
    118177        List<Restaurant> allRestaurants = restaurantRepository.findAll();
    119178
     
    134193
    135194        for (Restaurant restaurant : restaurants) {
    136             // Check if the restaurant has available time slots for today
    137195            boolean hasAvailableTimeSlots = tableService.hasAvailableTimeSlotsForRestaurantAndDate(restaurant, today);
    138196            if (hasAvailableTimeSlots) {
     
    146204    @Override
    147205    public List<Restaurant> findRestaurantsByDateTimeAndPartySize(LocalDateTime dateTime, int partySize, String search) {
     206        LocalDateTime checkOutTime = dateTime.plusHours(2);
    148207        List<Restaurant> allRestaurants = restaurantRepository.findAll();
     208
    149209        return allRestaurants.stream()
    150                 .filter(restaurant -> hasAvailableTable(restaurant, dateTime, partySize))
     210                .filter(restaurant -> restaurant.getTablesList().stream()
     211                        .anyMatch(table -> tableRepository.findAvailableTables(dateTime, checkOutTime, partySize)
     212                                .contains(table)))
    151213                .filter(restaurant -> isMatch(restaurant, search))
    152214                .collect(Collectors.toList());
    153215    }
    154216
    155     private boolean hasAvailableTable(Restaurant restaurant, LocalDateTime dateTime, int partySize) {
    156         for (TableEntity table : restaurant.getTablesList()) {
    157             if (table.isAvailable(dateTime) && table.getCapacity() >= partySize) {
    158                 return true;
    159             }
    160         }
    161         return false;
    162     }
    163 
    164217    private boolean isMatch(Restaurant restaurant, String name) {
    165218        return name == null || name.isEmpty() || restaurant.getName().contains(name);
     
    167220
    168221    @Override
    169     public List<Restaurant> findRestaurantsBySearchParams(LocalDateTime dateTime, int partySize, String search) {
     222    public List<RestaurantDTO> findRestaurantsBySearchParams(LocalDateTime dateTime, int partySize, String search) {
     223        List<Restaurant> availableRestaurants = new ArrayList<>();
     224
     225        List<Restaurant> restaurantList;
    170226        if (search == null || search.isEmpty()) {
    171             List<TableEntity> tableEntities = tableRepository.findAllByTimeSlotsContainingAndCapacityGreaterThanEqual(dateTime, partySize);
    172             return tableEntities.stream()
    173                     .map(TableEntity::getRestaurant)
    174                     .distinct()
    175                     .collect(Collectors.toList());
     227            restaurantList = restaurantRepository.findAll();
    176228        } else {
    177229            String searchTerm = "%" + search + "%";
    178             List<Restaurant> restaurantList = restaurantRepository.findAllByNameLikeIgnoreCase(searchTerm);
     230            restaurantList = restaurantRepository.findAllByNameLikeIgnoreCase(searchTerm);
     231
    179232            if (restaurantList.isEmpty()) {
    180233                restaurantList = restaurantRepository.findAllByCuisineTypeContaining(search);
    181234            }
    182             return restaurantList;
    183         }
     235        }
     236
     237        for (Restaurant restaurant : restaurantList) {
     238            boolean hasAvailableTable = restaurant.getTablesList().stream()
     239                    .anyMatch(table -> table.isAvailable(dateTime, partySize));
     240
     241            if (hasAvailableTable) {
     242                availableRestaurants.add(restaurant);
     243            }
     244        }
     245
     246        List<RestaurantDTO> restaurantDTOS = availableRestaurants.stream().map(this::convertToDto).toList();
     247        return restaurantDTOS;
    184248    }
    185249
     
    190254
    191255    @Override
    192     public List<Restaurant> findRestaurantsByCuisineType(String param) {
    193         return restaurantRepository.findAllByCuisineType(param);
     256    public List<RestaurantDTO> findRestaurantsByCuisineType(String param) {
     257        List<Restaurant> restaurants = restaurantRepository.findAllByCuisineType(param);
     258        return restaurants.stream().map(this::convertToDto).toList();
     259    }
     260
     261    public RestaurantDTO convertToDto(Restaurant restaurant) {
     262        return modelMapper.map(restaurant, RestaurantDTO.class);
     263    }
     264
     265    public TableDTO convertToDto(TableEntity table) {
     266        return modelMapper.map(table, TableDTO.class);
     267    }
     268
     269    public ReservationDTO convertToDto(Reservation reservation) {
     270        return modelMapper.map(reservation, ReservationDTO.class);
    194271    }
    195272}
  • src/main/java/com/example/rezevirajmasa/demo/service/impl/TableServiceImpl.java

    rf5b256e rdeea3c4  
    11package com.example.rezevirajmasa.demo.service.impl;
    22
     3import com.example.rezevirajmasa.demo.dto.ReservationDTO;
     4import com.example.rezevirajmasa.demo.dto.RestaurantDTO;
     5import com.example.rezevirajmasa.demo.dto.TableDTO;
     6import com.example.rezevirajmasa.demo.model.Reservation;
    37import com.example.rezevirajmasa.demo.model.Restaurant;
    48import com.example.rezevirajmasa.demo.model.TableEntity;
    5 import com.example.rezevirajmasa.demo.model.exceptions.InvalidRestaurantIdException;
    69import com.example.rezevirajmasa.demo.model.exceptions.InvalidTableNumberException;
     10import com.example.rezevirajmasa.demo.repository.ReservationRepository;
    711import com.example.rezevirajmasa.demo.repository.RestaurantRepository;
    812import com.example.rezevirajmasa.demo.repository.TableRepository;
    913import com.example.rezevirajmasa.demo.service.TableService;
     14import jakarta.persistence.Table;
     15import org.modelmapper.ModelMapper;
     16import org.openqa.selenium.InvalidArgumentException;
    1017import org.springframework.cglib.core.Local;
    1118import org.springframework.stereotype.Service;
     
    1825import java.time.chrono.ChronoLocalDateTime;
    1926import java.time.format.DateTimeFormatter;
     27import java.util.ArrayList;
    2028import java.util.Iterator;
    2129import java.util.List;
     
    2533    private final TableRepository tableRepository;
    2634    private final RestaurantRepository restaurantRepository;
     35    private final ReservationRepository reservationRepository;
     36    private ModelMapper modelMapper = new ModelMapper();
    2737
    28     public TableServiceImpl(TableRepository tableRepository, RestaurantRepository restaurantRepository) {
     38    public TableServiceImpl(TableRepository tableRepository, RestaurantRepository restaurantRepository, ReservationRepository reservationRepository) {
    2939        this.tableRepository = tableRepository;
    3040        this.restaurantRepository = restaurantRepository;
    31     }
    32 
    33     @Override
    34     public TableEntity findById(Long id) {
    35         return tableRepository.findById(id).orElseThrow(InvalidTableNumberException::new);
     41        this.reservationRepository = reservationRepository;
    3642    }
    3743
     
    4147    }
    4248
     49    @Override
     50    public TableDTO findById(Long id) {
     51        TableEntity table = tableRepository.findById(id)
     52                .orElseThrow(InvalidTableNumberException::new);
     53
     54        TableDTO tableDTO = modelMapper.map(table, TableDTO.class);
     55
     56        List<ReservationDTO> reservationDTOS = new ArrayList<>();
     57        for (Reservation reservation : table.getReservations()) {
     58            ReservationDTO reservationDTO = modelMapper.map(reservation, ReservationDTO.class);
     59            reservationDTOS.add(reservationDTO);
     60        }
     61
     62        tableDTO.setReservations(reservationDTOS);
     63
     64        return tableDTO;
     65    }
     66
     67    @Override
     68    public TableEntity findByIdTable(Long id) {
     69        return tableRepository.findById(id).orElseThrow(() -> new InvalidArgumentException("Invalid table id"));
     70    }
     71
     72
     73    @Override
    4374    public void save(int numberOfTables, List<Integer> tableCapacities, List<String> tableLocations, List<String> tableSmokingAreas, List<String> tableDescriptions, Restaurant restaurant) {
    4475        for (int i = 0; i < numberOfTables; i++) {
     
    5586    @Override
    5687    public void deleteTimeSlotsForReservation(Long tableId, LocalDateTime reservationTime) {
    57         LocalDateTime startTime = reservationTime.minusHours(2);
    58         LocalDateTime endTime = reservationTime.plusHours(2);
    59 
    60         TableEntity table = findById(tableId);
    61         List<LocalDateTime> timeSlots = table.getTimeSlots();
    62 
    63         timeSlots.removeIf(timeSlot -> timeSlot.isAfter(startTime) && timeSlot.isBefore(endTime));
    64 
    65         table.setTimeSlots(timeSlots);
     88        TableDTO tableDTO = findById(tableId);
     89        TableEntity table = convertFromDTO(tableDTO);
     90        LocalDate threeDaysAgo = LocalDate.now().minusDays(3);
     91        table.cleanUnusedTimeSlots(threeDaysAgo);
    6692
    6793        tableRepository.saveAndFlush(table);
     
    7096    @Override
    7197    public void canceledTimeSlots(Long tableId, LocalDateTime reservationTime) {
    72         TableEntity table = findById(tableId);
    73         List<LocalDateTime> timeSlots = table.getTimeSlots();
     98        TableDTO tableDTO = findById(tableId);
     99        TableEntity table = convertFromDTO(tableDTO);
    74100        LocalDateTime startTime = reservationTime.minusHours(1).minusMinutes(45);
    75101        LocalDateTime endTime = reservationTime.plusHours(1).plusMinutes(45);
    76102
    77         LocalDate localDate = reservationTime.toLocalDate();
    78 
    79103        String[] hours = table.getRestaurant().getOperatingHours().split("-");
    80104        LocalTime openingHourTime = LocalTime.parse(hours[0], DateTimeFormatter.ofPattern("HH:mm"));
     105        LocalDateTime openingHour = openingHourTime.atDate(reservationTime.toLocalDate());
     106        LocalDateTime closingHour = LocalTime.of(23, 45).atDate(reservationTime.toLocalDate());
    81107
    82         LocalDateTime openingHour = openingHourTime.atDate(localDate);
    83         LocalDateTime closingHour = LocalTime.of(23, 45).atDate(localDate);
    84         if(startTime.isBefore(openingHour)) {
    85             startTime = LocalDateTime.from(openingHour);
     108        if (startTime.isBefore(openingHour)) {
     109            startTime = openingHour;
    86110        }
    87         while(startTime.isBefore(endTime) || startTime.equals(endTime)) {
    88             timeSlots.add(startTime);
    89             startTime = startTime.plusMinutes(15);
    90             if(startTime.isAfter(closingHour) || startTime.equals(closingHour)) {
     111
     112        while (startTime.isBefore(endTime) || startTime.equals(endTime)) {
     113            if (startTime.isAfter(closingHour) || startTime.equals(closingHour)) {
    91114                break;
    92115            }
     116
     117            Reservation reservation = new Reservation();
     118            reservation.setReservationDateTime(startTime);
     119            reservation.setTable(table);
     120            reservationRepository.save(reservation);
     121
     122            startTime = startTime.plusMinutes(15);
    93123        }
    94         table.setTimeSlots(timeSlots);
     124
    95125        tableRepository.saveAndFlush(table);
    96126    }
     
    105135        return tableRepository.findById(number).orElseThrow(InvalidTableNumberException::new);
    106136    }
     137
    107138    @Override
    108139    public TableEntity deleteTable(Long number) {
     
    116147        List<TableEntity> tables = tableRepository.findByRestaurant(restaurant);
    117148
    118         // Iterate through each table to check for available time slots
    119149        for (TableEntity table : tables) {
    120150            boolean hasAvailableTimeSlots = hasAvailableTimeSlotsForTableAndDate(table, today);
    121151            if (hasAvailableTimeSlots) {
    122                 return true; // If any table has available time slots, return true
     152                return true;
    123153            }
    124154        }
     
    128158
    129159    public boolean hasAvailableTimeSlotsForTableAndDate(TableEntity table, LocalDate date) {
    130         List<LocalDateTime> timeSlots = table.getTimeSlots();
     160        for (Reservation reservation : table.getReservations()) {
     161            LocalDateTime startTime = reservation.getReservationDateTime();
     162            LocalDateTime endTime = startTime.plusHours(reservation.getTable().getReservationDurationHours());
    131163
    132         // Implement your logic to check if the table has available time slots for the given date
    133         // This could involve querying the database for reservations for the given table and date,
    134         // and checking if there are any open time slots.
    135         // You may need to consider factors such as operating hours, existing reservations, etc.
    136         // Return true if there are available time slots, false otherwise.
    137         return false;
     164            if (startTime.toLocalDate().equals(date) || endTime.toLocalDate().equals(date)) {
     165                return false;
     166            }
     167        }
     168        return true;
    138169    }
    139170
     171    public RestaurantDTO convertToDto(Restaurant restaurant) {
     172        return modelMapper.map(restaurant, RestaurantDTO.class);
     173    }
     174
     175    public TableDTO convertToDto(TableEntity table) {
     176        return modelMapper.map(table, TableDTO.class);
     177    }
     178
     179    public ReservationDTO convertToDto(Reservation reservation) {
     180        return modelMapper.map(reservation, ReservationDTO.class);
     181    }
     182
     183    public TableEntity convertFromDTO(TableDTO tableDTO) {
     184        return modelMapper.map(tableDTO, TableEntity.class);
     185    }
    140186}
  • src/main/java/com/example/rezevirajmasa/demo/web/rest/testController.java

    rf5b256e rdeea3c4  
    11package com.example.rezevirajmasa.demo.web.rest;
    22
    3 import com.example.rezevirajmasa.demo.dto.CustomerDTO;
    4 import com.example.rezevirajmasa.demo.dto.UserDto;
     3import com.example.rezevirajmasa.demo.dto.*;
    54import com.example.rezevirajmasa.demo.mappers.UserMapper;
    65import com.example.rezevirajmasa.demo.model.*;
     6import com.example.rezevirajmasa.demo.model.exceptions.InvalidReservationException;
    77import com.example.rezevirajmasa.demo.service.*;
    88import com.example.rezevirajmasa.demo.service.impl.TokenService;
     
    2525import java.time.LocalDateTime;
    2626import java.time.format.DateTimeFormatter;
    27 import java.util.ArrayList;
    28 import java.util.List;
    29 import java.util.Map;
    30 import java.util.Optional;
     27import java.util.*;
     28import java.util.stream.Collectors;
    3129
    3230@CrossOrigin(origins = "http://localhost:3000/")
     
    5755    }
    5856
    59     //restaurants
    60 
    61     @RequestMapping("/api/restaurants")
    62     public ResponseEntity<List<Restaurant>> getAllRestaurants() {
    63         return new ResponseEntity<List<Restaurant>>(restaurantService.listall(), HttpStatus.OK);
    64     }
    65 
    66     @RequestMapping("/api/restaurants/{restaurantId}")
    67     public ResponseEntity<Restaurant> getRestaurantById(@PathVariable Long restaurantId) {
    68         return new ResponseEntity<Restaurant>(restaurantService.findById(restaurantId), HttpStatus.OK);
     57    //restaurants calls
     58
     59    @GetMapping("/api/restaurants")
     60    public ResponseEntity<List<RestaurantDTO>> getAllRestaurants() {
     61            return new ResponseEntity<List<RestaurantDTO>>(restaurantService.listall(), HttpStatus.OK);
     62    }
     63
     64    @GetMapping("/api/restaurants/{restaurantId}")
     65    public ResponseEntity<RestaurantDTO> getRestaurantById(@PathVariable Long restaurantId) {
     66        return new ResponseEntity<RestaurantDTO>(restaurantService.findById(restaurantId), HttpStatus.OK);
    6967    }
    7068
    7169    @PostMapping("/api/search")
    72     public ResponseEntity<List<Restaurant>> searchRestaurants(@RequestBody Map<String, Object> requestData) {
     70    public ResponseEntity<List<RestaurantDTO>> searchRestaurants(@RequestBody Map<String, Object> requestData) {
    7371        Optional<String> dateTimeOptional = Optional.ofNullable((String) requestData.get("dateTime"));
    7472        int partySize = Integer.parseInt(requestData.get("partySize").toString());
     
    8482        }
    8583
    86         List<Restaurant> filteredRestaurants = restaurantService.findRestaurantsBySearchParams(parsedDateTime, partySize, search);
    87 
    88         return new ResponseEntity<List<Restaurant>>(filteredRestaurants, HttpStatus.OK);
     84        List<RestaurantDTO> filteredRestaurants = restaurantService.findRestaurantsBySearchParams(parsedDateTime, partySize, search);
     85
     86        return new ResponseEntity<>(filteredRestaurants, HttpStatus.OK);
    8987    }
    9088
    9189    @PostMapping("/api/search/shortcut/{param}")
    92     public ResponseEntity<List<Restaurant>> searchByCuisineTypeShortcut(@PathVariable String param) {
    93         List<Restaurant> filteredRestaurants;
     90    public ResponseEntity<List<RestaurantDTO>> searchByCuisineTypeShortcut(@PathVariable String param) {
     91        List<RestaurantDTO> filteredRestaurants;
    9492        if(param != null && !param.isEmpty()) {
    9593            filteredRestaurants = restaurantService.findRestaurantsByCuisineType(param);
     
    9795            filteredRestaurants = restaurantService.listall();
    9896        }
    99         return new ResponseEntity<List<Restaurant>>(filteredRestaurants, HttpStatus.OK);
     97        return new ResponseEntity<List<RestaurantDTO>>(filteredRestaurants, HttpStatus.OK);
    10098    }
    10199
     
    106104    }
    107105
     106    // User calls
     107
     108    @GetMapping("/api/user/{email}")
     109    public ResponseEntity<User> getUserByEmail(@PathVariable String email)
     110    {
     111        User user = userService.findByMail(email);
     112        return ResponseEntity.ok(user);
     113    }
     114
    108115//    Customer CALLS
    109116
    110     @RequestMapping("/api/customers")
     117    @GetMapping("/api/customers")
    111118    public ResponseEntity<List<CustomerDTO>> getAllCustomers() {
    112119        List<Customer> customers = customerService.listAll();
     
    119126    }
    120127
    121     @RequestMapping("/api/customers/{id}")
     128    @GetMapping("/api/customers/{id}")
    122129    public ResponseEntity<Customer> getCustomerById(@PathVariable Long id) {
    123130        return new ResponseEntity<Customer>(customerService.findById(id), HttpStatus.OK);
     
    130137        );
    131138    }
    132     @GetMapping("/api/user")
    133     public ResponseEntity<?> getCurrentUser() {
    134         Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    135 
    136         if (authentication == null || !authentication.isAuthenticated() || authentication.getPrincipal().equals("anonymousUser")) {
    137             return new ResponseEntity<>("User is not authenticated", HttpStatus.UNAUTHORIZED);
    138         }
    139 
    140         Customer customer = (Customer) authentication.getPrincipal();
    141         return new ResponseEntity<>(customer, HttpStatus.OK);
    142     }
    143 
    144139
    145140    @PostMapping("/api/customers")
     
    166161
    167162    @GetMapping("/api/reservations/by/{email}")
    168     public ResponseEntity<List<Reservation>> getReservations(@PathVariable String email) {
    169         User user = userService.findByMail(email);
    170         return new ResponseEntity<List<Reservation>>(reservationService.findReservationByUser(user), HttpStatus.OK);
    171     }
    172 
    173     @PostMapping("/api/reservations/{email}")
    174     public ResponseEntity<Reservation> createReservation(@RequestBody Reservation reservation, @PathVariable String email) {
    175         User user = userService.findByMail(email);
     163    public ResponseEntity<List<ReservationDTO>> getReservations(@PathVariable String email) {
     164        if (email == null || email.isEmpty()) {
     165            return ResponseEntity.badRequest().build();
     166        }
     167        User user = userService.findByMail(email);
     168        if (user == null) {
     169            return ResponseEntity.notFound().build();
     170        }
     171
     172        List<Reservation> reservations = reservationService.findReservationByUser(user);
     173        List<ReservationDTO> reservationDTOs = reservations.stream()
     174                .map(ReservationDTO::new)
     175                .collect(Collectors.toList());
     176
     177        return ResponseEntity.ok(reservationDTOs);
     178    }
     179
     180    @PostMapping("/api/reservations")
     181    public ResponseEntity<?> createReservation(@RequestBody ReservationDTO reservation) {
     182        User user = userService.findByMail(reservation.getUserEmail());
    176183        Reservation savedReservation = reservationService.makeReservationRest(reservation, user);
    177184
     
    179186    }
    180187
    181 
    182188    @GetMapping("/api/reservations/{reservationId}")
    183     public ResponseEntity<Reservation> getReservation(@PathVariable Long reservationId) {
     189    public ResponseEntity<ReservationDTO> getReservation(@PathVariable Long reservationId) {
    184190        Reservation reservation = reservationService.findById(reservationId);
    185191        if (reservation != null) {
    186             return ResponseEntity.ok(reservation);
    187         } else {
    188             return ResponseEntity.notFound().build();
    189         }
    190     }
     192            return ResponseEntity.ok(new ReservationDTO(reservation));
     193        } else {
     194            return ResponseEntity.notFound().build();
     195        }
     196    }
     197
     198//    @GetMapping("/api/reservations/{restaurantId}")
     199//    public ResponseEntity<List<Reservation>> getReservationsByRestaurant(@PathVariable Long restaurantId)
     200//    {
     201//        Restaurant restaurant = restaurantService.findByIdRestaurant(restaurantId);
     202//        List<Reservation> reservations = reservationService.findAllByRestaurant(restaurant);
     203//        return ResponseEntity.ok(reservations);
     204//    }
     205
     206    @GetMapping("/api/table-reservations/{tableId}")
     207    public ResponseEntity<List<LocalDateTime>> tableReservations(@PathVariable Long tableId) {
     208        TableEntity table = tableService.findByIdTable(tableId);
     209        if (table == null) {
     210            return ResponseEntity.notFound().build();
     211        }
     212
     213        List<Reservation> reservations = reservationService.reservationsForTable(table);
     214        List<LocalDateTime> reservedTimes = reservations.stream()
     215                .map(Reservation::getReservationDateTime)
     216                .collect(Collectors.toList());
     217
     218        return ResponseEntity.ok(reservedTimes);
     219    }
     220
    191221
    192222    @PostMapping("/api/reservations/{reservationId}/{email}")
    193223    public ResponseEntity<Reservation> editReservation(@PathVariable Long reservationId,
    194                                                        @RequestBody Reservation reservation,
     224                                                       @RequestBody ReservationDTO reservationDTO,
    195225                                                       @PathVariable String email) {
    196226        User user = userService.findByMail(email);
    197227
    198         if (!reservation.getReservationID().equals(reservationId)) {
     228        if (!reservationDTO.getReservationID().equals(reservationId)) {
    199229            return ResponseEntity.badRequest().build();
    200230        }
    201231
    202         // Fetch existing reservation
    203         Reservation existingReservation = reservationService.findById(reservationId);
    204         if (existingReservation == null) {
    205             return ResponseEntity.notFound().build();
    206         }
    207 
    208         if (!reservation.getCheckInTime().equals(existingReservation.getCheckInTime())) {
    209             tableService.canceledTimeSlots(existingReservation.getTable().getId(), existingReservation.getCheckInTime());
    210 
    211             tableService.deleteTimeSlotsForReservation(reservation.getTable().getId(), reservation.getCheckInTime());
    212         }
    213 
    214         existingReservation.setReservationDateTime(LocalDateTime.now());
    215         existingReservation.setCheckInTime(reservation.getCheckInTime());
    216         existingReservation.setCheckOutTime(reservation.getCheckInTime().plusHours(2));
    217         existingReservation.setPartySize(reservation.getPartySize());
    218         existingReservation.setSpecialRequests(reservation.getSpecialRequests());
    219 
    220         Reservation updatedReservation = reservationService.makeReservationRest(existingReservation, user);
    221 
    222         System.out.println("Updated reservation time: " + updatedReservation.getCheckInTime());
    223         return ResponseEntity.ok(updatedReservation);
    224     }
     232        try {
     233            Reservation updatedReservation = reservationService.updateReservation(reservationId, reservationDTO, user);
     234            return ResponseEntity.ok(updatedReservation);
     235        } catch (InvalidReservationException e) {
     236            return ResponseEntity.status(409).body(null);
     237        } catch (Exception e) {
     238            return ResponseEntity.status(500).build();
     239        }
     240    }
     241
    225242
    226243
     
    241258    }
    242259
    243 //    TableEntity Calls
    244 
     260    // TableEntity Calls
    245261    @GetMapping("/api/tables/{tableId}")
    246     public ResponseEntity<TableEntity> findTableById(@PathVariable Long tableId) {
    247         return new ResponseEntity<TableEntity>(tableService.findById(tableId), HttpStatus.OK);
     262    public ResponseEntity<TableDTO> findTableById(@PathVariable Long tableId) {
     263        TableDTO tableDTO = tableService.findById(tableId);
     264        return new ResponseEntity<>(tableDTO, HttpStatus.OK);
    248265    }
    249266
     
    255272        return new ResponseEntity<>(reservations, HttpStatus.OK);
    256273    }
    257 
    258274}
Note: See TracChangeset for help on using the changeset viewer.