|
| 1 | +package kattsyn.dev.rentplace.services.impl; |
| 2 | + |
| 3 | +import jakarta.transaction.Transactional; |
| 4 | +import kattsyn.dev.rentplace.dtos.PropertyDTO; |
| 5 | +import kattsyn.dev.rentplace.entities.Property; |
| 6 | +import kattsyn.dev.rentplace.entities.User; |
| 7 | +import kattsyn.dev.rentplace.exceptions.NotFoundException; |
| 8 | +import kattsyn.dev.rentplace.mappers.PropertyMapper; |
| 9 | +import kattsyn.dev.rentplace.repositories.PropertyRepository; |
| 10 | +import kattsyn.dev.rentplace.repositories.UserRepository; |
| 11 | +import kattsyn.dev.rentplace.services.FavouritesService; |
| 12 | +import lombok.RequiredArgsConstructor; |
| 13 | +import org.springframework.stereotype.Service; |
| 14 | + |
| 15 | +import java.util.List; |
| 16 | + |
| 17 | +@Service |
| 18 | +@RequiredArgsConstructor |
| 19 | +public class FavouritesServiceImpl implements FavouritesService { |
| 20 | + |
| 21 | + private final UserRepository userRepository; |
| 22 | + private final PropertyRepository propertyRepository; |
| 23 | + private final PropertyMapper propertyMapper; |
| 24 | + |
| 25 | + private User getUserByEmail(String email) { |
| 26 | + return userRepository.findByEmail(email).orElseThrow( |
| 27 | + () -> new NotFoundException(String.format("User email %s NOT FOUND", email)) |
| 28 | + ); |
| 29 | + } |
| 30 | + |
| 31 | + private Property getPropertyById(long propertyId) { |
| 32 | + return propertyRepository.findById(propertyId).orElseThrow( |
| 33 | + () -> new NotFoundException(String.format("Property id %s NOT FOUND", propertyId)) |
| 34 | + ); |
| 35 | + } |
| 36 | + |
| 37 | + @Transactional |
| 38 | + @Override |
| 39 | + public void addPropertyToFavourites(long propertyId, String userEmail) { |
| 40 | + User user = getUserByEmail(userEmail); |
| 41 | + user.getFavourites().add(getPropertyById(propertyId)); |
| 42 | + userRepository.save(user); |
| 43 | + } |
| 44 | + |
| 45 | + @Transactional |
| 46 | + @Override |
| 47 | + public void removePropertyFromFavourites(long propertyId, String userEmail) { |
| 48 | + User user = getUserByEmail(userEmail); |
| 49 | + user.getFavourites().remove(getPropertyById(propertyId)); |
| 50 | + userRepository.save(user); |
| 51 | + } |
| 52 | + |
| 53 | + @Transactional |
| 54 | + @Override |
| 55 | + public List<PropertyDTO> getUserFavouritesByUserEmail(String userEmail) { |
| 56 | + return propertyMapper.fromProperties(getUserByEmail(userEmail).getFavourites().stream().toList()); |
| 57 | + } |
| 58 | + |
| 59 | +} |
0 commit comments