Sfoglia il codice sorgente

ont to many relation, all functionalities are done, todo: code cleaning

mateuszsudra 2 anni fa
parent
commit
aa51d68b8c

+ 6 - 1
boat-reservation-logic/src/main/java/pl/sudra/controller/ReservationController.java

@@ -6,9 +6,11 @@ import org.springframework.web.bind.annotation.*;
 //import pl.sudra.domain.Reservation;
 import pl.sudra.domain.Bill;
 import pl.sudra.domain.Reservation;
+import pl.sudra.repository.UserRepository;
 import pl.sudra.service.BillService;
 import pl.sudra.service.BoatService;
 import pl.sudra.service.ReservationService;
+import pl.sudra.service.UserService;
 
 import java.sql.Date;
 import java.util.List;
@@ -19,12 +21,14 @@ public class ReservationController {
     private final ReservationService reservationService;
     private final BillService billService;
     private final BoatService boatService;
+    private final UserRepository userRepository;
 
     public ReservationController(ReservationService reservationService,
-                                 BillService billService, BoatService boatService) {
+                                 BillService billService, BoatService boatService, UserRepository userRepository) {
         this.reservationService = reservationService;
         this.billService = billService;
         this.boatService = boatService;
+        this.userRepository = userRepository;
     }
 
     @RequestMapping(
@@ -59,6 +63,7 @@ public class ReservationController {
                         * (reservation.getEndHour() - reservation.getStartHour()));
 
         reservation.setBill(bill);
+        reservation.setUser(this.userRepository.findById(reservation.getUser().getId()).get());
         System.out.println(bill);
         System.out.println(reservation);
 

+ 23 - 7
boat-reservation-logic/src/main/java/pl/sudra/domain/Reservation.java

@@ -1,6 +1,8 @@
 package pl.sudra.domain;
 
+import com.fasterxml.jackson.annotation.JsonBackReference;
 import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
 import jakarta.persistence.*;
 import jakarta.validation.constraints.NotNull;
 
@@ -16,8 +18,13 @@ public class Reservation {
     //    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
 //    @JoinColumn(name = "user_id")
 //    @JsonBackReference
-    @NotNull
-    private Long userId;
+//    @NotNull
+//    private Long userId;
+
+    @ManyToOne(fetch = FetchType.EAGER)
+    @JoinColumn(name = "userId")
+    @JsonIgnoreProperties("reservations")
+    private User user;
     @NotNull
     private Long boatId;
     @NotNull
@@ -37,7 +44,7 @@ public class Reservation {
     public String toString() {
         return "Reservation{" +
                 "id=" + id +
-                ", user=" + userId +
+                ", user=" + user.getId() +
                 ", boatId=" + boatId +
                 ", date=" + date +
                 ", startHour=" + startHour +
@@ -65,12 +72,21 @@ public class Reservation {
         this.id = id;
     }
 
-    public Long getUserId() {
-        return userId;
+//    public Long getUserId() {
+//        return userId;
+//    }
+
+//    public void setUserId(Long user_id) {
+//        this.userId = user_id;
+//    }
+
+
+    public User getUser() {
+        return user;
     }
 
-    public void setUserId(Long user_id) {
-        this.userId = user_id;
+    public void setUser(User user) {
+        this.user = user;
     }
 
     public Long getBoatId() {

+ 10 - 5
boat-reservation-logic/src/main/java/pl/sudra/domain/User.java

@@ -62,12 +62,17 @@ public class User {
     public void setEnabled(boolean enabled) {
         this.enabled = enabled;
     }
-    //    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
-//    private List<Reservation> reservations;
 
-//    public void setReservations(Collection<Reservation> reservations) {
-//        this.reservations = (List<Reservation>) reservations;
-//    }
+    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
+    private List<Reservation> reservations;
+
+    public List<Reservation> getReservations() {
+        return reservations;
+    }
+
+    public void setReservations(List<Reservation> reservations) {
+        this.reservations = reservations;
+    }
 
     public String[] getRolesForToken() {
         Set<Role> appUserRoles = getRole(); // Assuming you have a method to retrieve the Set<AppUserRole>

+ 5 - 6
boat-reservation-logic/src/main/java/pl/sudra/repository/ReservationRepository.java

@@ -1,9 +1,7 @@
 package pl.sudra.repository;
 
 import jakarta.transaction.Transactional;
-import org.springframework.data.jpa.repository.EntityGraph;
 import org.springframework.data.jpa.repository.JpaRepository;
-import org.springframework.data.jpa.repository.Query;
 import org.springframework.data.repository.query.Param;
 import org.springframework.stereotype.Repository;
 import pl.sudra.domain.Reservation;
@@ -16,10 +14,11 @@ import java.util.List;
 public interface ReservationRepository extends JpaRepository<Reservation, Long> {
     Reservation findReservationById(long id);
 
-    List<Reservation> findAllByBoatIdAndDate(long id, Date date);
-    @EntityGraph(attributePaths = "bill")
-    @Query("SELECT r FROM Reservation r WHERE r.boatId = :boatId AND r.date = :date")
-    List<Reservation> findReservationsByBoatIdAndDate(@Param("boatId") Long boatId, @Param("date") Date date);
+//    List<Reservation> findAllByBoatIdAndDate(long id, Date date);
+//    @EntityGraph(attributePaths = "bill")
+//    @Query("SELECT r FROM Reservation r WHERE r.boatId = :boatId AND r.date = :date")
+//    @Query("SELECT new com.example.dto.ReservationDTO(r.id, r.date, r.startHour, r.endHour) FROM Reservation r WHERE r.boatId = :boatId AND r.date = :date")
+    List<Reservation> findAllByBoatIdAndDate(@Param("boatId") Long boatId, @Param("date") Date date);
 
     List<Reservation> findReservationsByUserId(Long userId);
 }

+ 2 - 2
boat-reservation-logic/src/main/java/pl/sudra/securityController/CustomInterceptor.java

@@ -36,14 +36,14 @@ public class CustomInterceptor implements HandlerInterceptor {
     List<String> manager_and_above = Stream.concat(customer_and_above.stream(),
                     List.of(
                             "/addBoat",
-                            "/getAllReservations"
+                            "/getAllReservations",
+                            "/getAllUsers"
                     ).stream())
             .collect(Collectors.toList());
 
     List<String> admin = Stream.concat(manager_and_above.stream(),
                     List.of(
                             "/generateReservations",
-                            "/getAllUsers",
                             "/updateUser",
                             "/deleteUser"
                     ).stream())

+ 2 - 4
boat-reservation-logic/src/main/java/pl/sudra/securityController/JwtTokenUtil.java

@@ -15,10 +15,8 @@ import java.util.function.Function;
 public class JwtTokenUtil {
 
     private static final String SECRET_KEY = "SuperSecureKey2023".repeat(5); // Replace with your own secret key
-    //    private static final long EXPIRATION_TIME = 86400000; // 24 hours in milliseconds
-//    private static final long EXPIRATION_TIME = 1000 * 30; // 30 sec
-//    private static final long EXPIRATION_TIME = 1000 * 60 * 30; // 30 min
-    private static final long EXPIRATION_TIME = 1000 * 60 * 60 * 24; // 1 day
+
+    private static final long EXPIRATION_TIME = 1000 * 60 * 60 * 1; // 1 hour
     private static final long EXPIRATION_TIME_USER_ACTIVATION = 1000 * 60 * 60 * 24; // 1 day
 
     public static String generateToken(String username, Long id, String role) {

+ 2 - 29
boat-reservation-logic/src/main/java/pl/sudra/service/ReservationServiceImpl.java

@@ -4,17 +4,13 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.scheduling.annotation.Scheduled;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
-import pl.sudra.domain.Bill;
 import pl.sudra.domain.Reservation;
 import pl.sudra.repository.BillRepository;
 import pl.sudra.repository.ReservationRepository;
 
 import java.sql.Date;
 import java.text.SimpleDateFormat;
-import java.time.LocalDate;
 import java.time.LocalTime;
-import java.time.format.DateTimeFormatter;
-import java.time.temporal.ChronoUnit;
 import java.util.List;
 import java.util.Objects;
 
@@ -92,7 +88,7 @@ public class ReservationServiceImpl implements ReservationService {
     @Override
     @Transactional
     public List<Reservation> findReservations(long boat_id, Date date) {
-        return this.reservationRepository.findReservationsByBoatIdAndDate(boat_id, date);
+        return this.reservationRepository.findAllByBoatIdAndDate(boat_id, date);
     }
 
     @Override
@@ -107,24 +103,15 @@ public class ReservationServiceImpl implements ReservationService {
 
     // every hour at 0 minutes
 //    @Scheduled(cron = "0 0 * * * *")
-    @Scheduled(cron = "0 * * * * *")
+    @Scheduled(cron = "0 0 * * * *")
     public void updateBill() {
         java.util.Date currentDate = new java.util.Date();
         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
         String formattedDate = dateFormat.format(currentDate);
         LocalTime date_now = LocalTime.now();
         int hour_now = date_now.getHour();
-//        System.out.println("Updating reservation's Bill: ");
-//        System.out.println("Date: " + formattedDate);
-//        System.out.println("Hour: " + hour_now);
         List<Reservation> reservations = reservationRepository.findAll();
         reservations.forEach(reservation -> {
-//            System.out.println("Hour: " + hour_now);
-//            System.out.println("Start: " + reservation.getStartHour());
-//            System.out.println("End: " + reservation.getEndHour());
-//            System.out.println("Date: " + reservation.getDate().toString());
-//            System.out.println("Status: " + reservation.getBill().getStatus());
-
             if (formattedDate.equals(reservation.getDate().toString()) &&
                     hour_now == reservation.getStartHour() &&
                     Objects.equals(reservation.getBill().getStatus(), "Confirmed")) {
@@ -137,20 +124,6 @@ public class ReservationServiceImpl implements ReservationService {
                 reservation.getBill().setStatus("Completed");
                 reservationRepository.saveAndFlush(reservation);
             }
-
-//            LocalDate date1 = LocalDate.parse(bill.getIssueDate().toString());
-//            LocalDate date2 = LocalDate.parse(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")).toString());
-//
-//            System.out.println(date1.toString() + ">" + date2.toString());
-//
-//            if (ChronoUnit.DAYS.between(
-//                    LocalDate.parse(bill.getIssueDate().toString()),
-//                    LocalDate.parse(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")).toString())) > 30
-//                    && date1.isBefore(date2)) {
-//                bill.setStatus("CANCELLED");
-//                billRepository.saveAndFlush(bill);
-//                System.out.println(bill.getId());
-//            }
         });
     }
 }

+ 4 - 2
boat-reservation-view/src/app/domain/reservation.ts

@@ -1,6 +1,8 @@
 export class Reservation {
   id = ''
-  clientId = ''
+  user = {
+    id : ''
+  }
   boatId = ''
   date = ''
   startHour = ''
@@ -11,7 +13,7 @@ export class Reservation {
 
   constructor(id: string, client_id: string, boat_id: string, date: string, start_hour: string, end_hour: string) {
     this.id = id;
-    this.clientId = client_id;
+    this.user.id = client_id;
     this.boatId = boat_id;
     this.date = date;
     this.startHour = start_hour;

+ 8 - 2
boat-reservation-view/src/app/manager-panel/manager-panel.component.ts

@@ -32,7 +32,7 @@ export class ManagerPanelComponent {
               private boatService: BoatService) {
     this.reservationService.getReservations().subscribe(
       reservations => {
-        console.log(reservations)
+        console.log("res1", reservations)
         this.reservations_info = reservations.map(r => {
           r.date = new Date(r.date).toISOString().split("T")[0]
           return r;
@@ -49,9 +49,15 @@ export class ManagerPanelComponent {
         this.userService.getAllUsers().subscribe(
           users => {
             console.log(users)
+            console.log(this.reservations_info)
             this.reservations_info.map(r => {
-              r.userId = users.find(u => u.id == r.userId)!.username
+              if (r.user == undefined) {
+                r.userId = '*deleted*'
+              } else {
+                r.userId = r.user.username
+              }
             })
+            console.log(this.reservations_info)
           }
         )
 

+ 8 - 3
boat-reservation-view/src/app/reservation-view/reservation-view.component.ts

@@ -76,15 +76,20 @@ export class ReservationViewComponent {
 
   makeReservation() {
     let reservation_info = {
-      "userId": sessionStorage.getItem("username_id"),
+      "user": {
+        "id": sessionStorage.getItem("username_id")
+      },
       "boatId": this.boat,
       "date": this.date,
       "startHour": this.fromHour,
       "endHour": this.toHour
     }
     console.log("reservation_info: ", reservation_info)
-    this.reservationService.createReservation(reservation_info)
-    this.updateSquares()
+    this.reservationService.createReservation(reservation_info).subscribe(
+      (response) => {
+        this.updateSquares()
+      }
+    )
   }
 
   async ngOnInit() {

+ 2 - 10
boat-reservation-view/src/app/services/reservation.service.ts

@@ -41,22 +41,14 @@ export class ReservationService {
     return this.http.get<Reservation[]>(url, {headers});
   }
 
-  createReservation(reservation_info: object): any {
+  createReservation(reservation_info: object): Observable<any> {
     const url = 'http://localhost:2137/createReservation';
 
     const headers = new HttpHeaders()
       .set('Content-Type', 'application/json')
       .set('Authorization', sessionStorage.getItem("jwtToken")!);
 
-    this.http.post(url, reservation_info, {headers}).subscribe(
-      (response) => {
-        console.log('POST request successful', response);
-        return response;
-      },
-      (error) => {
-        console.error('Error making POST request:', error);
-        return error;
-      });
+    return this.http.post(url, reservation_info, {headers})
   }
 
   cancelReservation(id: number): any {