[77205be] | 1 | package edu.gjoko.schedlr.services;
|
---|
| 2 |
|
---|
| 3 | import edu.gjoko.schedlr.entity.Appointment;
|
---|
| 4 | import edu.gjoko.schedlr.entity.AppointmentStatus;
|
---|
| 5 | import edu.gjoko.schedlr.entity.Review;
|
---|
| 6 | import edu.gjoko.schedlr.repositories.AppointmentRepository;
|
---|
| 7 | import edu.gjoko.schedlr.repositories.ReviewRepository;
|
---|
| 8 | import lombok.AllArgsConstructor;
|
---|
| 9 | import org.springframework.stereotype.Service;
|
---|
| 10 |
|
---|
| 11 | import javax.persistence.EntityNotFoundException;
|
---|
| 12 | import java.util.List;
|
---|
| 13 | import java.util.Optional;
|
---|
| 14 |
|
---|
| 15 | @Service
|
---|
| 16 | @AllArgsConstructor
|
---|
| 17 | public class ReviewService {
|
---|
| 18 |
|
---|
| 19 | private final ReviewRepository reviewRepository;
|
---|
| 20 | private final AppointmentRepository appointmentRepository;
|
---|
| 21 |
|
---|
| 22 | public void save(Review review, Long customerId) {
|
---|
| 23 | Optional<Appointment> appointmentOptional = appointmentRepository.findById(review.getAppointment().getId());
|
---|
| 24 | if (appointmentOptional.isEmpty()) {
|
---|
| 25 | throw new EntityNotFoundException();
|
---|
| 26 | }
|
---|
| 27 | Appointment appointment = appointmentOptional.get();
|
---|
| 28 | if (appointment.getCustomer().getId().equals(customerId)) {
|
---|
| 29 | review.setAppointment(appointment);
|
---|
| 30 | markAppointmentAsReviewed(review.getAppointment());
|
---|
| 31 | calculateAndUpdateCumulatedRatingForService(appointment.getService(), review.getRating());
|
---|
| 32 | reviewRepository.save(review);
|
---|
| 33 | } else {
|
---|
| 34 | throw new EntityNotFoundException();
|
---|
| 35 | }
|
---|
| 36 | }
|
---|
| 37 |
|
---|
| 38 | public List<Review> getReviewsByServiceId(Long businessId) {
|
---|
| 39 | return reviewRepository.findAllByAppointment_Service_Id(businessId);
|
---|
| 40 | }
|
---|
| 41 |
|
---|
| 42 | public List<Review> getReviewsByCustomerId(Long customerId) {
|
---|
| 43 | return reviewRepository.findAllByAppointment_Customer_Id(customerId);
|
---|
| 44 | }
|
---|
| 45 |
|
---|
| 46 | private void markAppointmentAsReviewed(Appointment appointment) {
|
---|
| 47 | appointment.setAppointmentStatus(AppointmentStatus.FINISHED_AND_REVIEWED_BY_USER);
|
---|
| 48 | }
|
---|
| 49 |
|
---|
| 50 | private void calculateAndUpdateCumulatedRatingForService(edu.gjoko.schedlr.entity.Service service, int rating) {
|
---|
| 51 | int newReviewsCount = service.getReviewsCount() + 1;
|
---|
| 52 | float currentRating = service.getRating();
|
---|
| 53 | float newRating = (currentRating * service.getReviewsCount() + rating) / newReviewsCount;
|
---|
| 54 | service.setReviewsCount(newReviewsCount);
|
---|
| 55 | service.setRating(newRating);
|
---|
| 56 | }
|
---|
| 57 | }
|
---|