diff --git a/src/main/java/SuMoC/backend/notification/enums/NotificationType.java b/src/main/java/SuMoC/backend/notification/enums/NotificationType.java index b58a0ef..7d49e3f 100644 --- a/src/main/java/SuMoC/backend/notification/enums/NotificationType.java +++ b/src/main/java/SuMoC/backend/notification/enums/NotificationType.java @@ -16,5 +16,9 @@ public enum NotificationType { * An alternative suggestion that refers to a detected regular trip. * E.g. user drives by car every monday at 8 am and there is a sustainable alternative. */ - REGULAR_TRIP_ALTERNATIVE + REGULAR_TRIP_ALTERNATIVE, + /** + * A notification informing the user about a new pending friendship request. + */ + FRIENDSHIP_REQUEST_RECEIVED, } diff --git a/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java b/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java index e5bdbea..e6593aa 100644 --- a/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java +++ b/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java @@ -15,6 +15,10 @@ import java.time.LocalDateTime; import java.time.LocalTime; import java.util.List; +/** + * This service is the main entry point to schedule notifications to be sent to a users' mobile device. + * It creates Notification entities in the database with status PENDING which are then later processed by the notification worker. + */ @Service @RequiredArgsConstructor public class NotificationSchedulerService { @@ -25,6 +29,14 @@ public class NotificationSchedulerService { private final EntityManager entityManager; + /** + * Can be used to schedule multiple notifications at once. Notifieable interface allows sending to multiple users. + * dataBodies need to be serializable to JSON. + * + * @param dataBodies + * @param notificationType + * @param earliestTimeOfDayToSend + */ public void scheduleAll(List dataBodies, NotificationType notificationType, LocalTime earliestTimeOfDayToSend @@ -53,11 +65,20 @@ public class NotificationSchedulerService { notificationRepository.saveAll(notifications); } + /** + * Schedules a notification to be sent to the specified user. + * Data body needs to be serializable to JSON. + * + * @param userId + * @param dataBody + * @param notificationType + * @param earliestTimeOfDayToSend TOD from which on the notification can be sent. If null, send as soon as possible. + */ public void schedule( Long userId, Object dataBody, - NotificationType notificationType, - LocalTime earliestTimeOfDayToSend + NotificationType notificationType, + LocalTime earliestTimeOfDayToSend ) { String dataBodyJson; try { @@ -66,6 +87,10 @@ public class NotificationSchedulerService { throw new RuntimeException("Failed to serialize notification data body", e); } + if (earliestTimeOfDayToSend == null) { + earliestTimeOfDayToSend = LocalTime.now(); + } + User userProxy = entityManager.getReference(User.class, userId); Notification notification = Notification.builder() diff --git a/src/main/java/SuMoC/backend/routing/controller/RoutingController.java b/src/main/java/SuMoC/backend/routing/controller/RoutingController.java index ca642d8..3a7ecfc 100644 --- a/src/main/java/SuMoC/backend/routing/controller/RoutingController.java +++ b/src/main/java/SuMoC/backend/routing/controller/RoutingController.java @@ -4,6 +4,7 @@ import SuMoC.backend.routing.dtos.RouteDTO; import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO; import SuMoC.backend.routing.services.RoutingPreferencesService; import SuMoC.backend.routing.services.RoutingService; +import SuMoC.backend.user.service.CurrentUserService; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; @@ -29,10 +30,19 @@ public class RoutingController { private final RoutingPreferencesService routingPreferencesService; + private final CurrentUserService currentUserService; + @PostMapping("/request") @Schema(description = "Calculates alternative, sustainable routes for the request. The delta of departure and arrival in the requestdto is used as baseline to determine if alternatives are acceptable.") public ResponseEntity> requestAlternativeRoutes(@Valid @RequestBody RoutingAlternativeRequestDTO routingAlternativeRequestDTO) { try { + + if (currentUserService.isAuthenticated()) { + logger.info("Authenticaed user is making request: " + currentUserService.get().getEmail()); + } else { + logger.info("Unauthenticated user is making request."); + } + if (routingAlternativeRequestDTO.getRoutingPreferencesDTO() == null) { // This automatically uses default preferences for unauthenticated users routingAlternativeRequestDTO.setRoutingPreferencesDTO(routingPreferencesService.getRoutingPreferencesForCurrentUser()); diff --git a/src/main/java/SuMoC/backend/user/dtos/FriendshipDTO.java b/src/main/java/SuMoC/backend/user/dtos/FriendshipDTO.java index 3cab722..fcc0756 100644 --- a/src/main/java/SuMoC/backend/user/dtos/FriendshipDTO.java +++ b/src/main/java/SuMoC/backend/user/dtos/FriendshipDTO.java @@ -1,6 +1,8 @@ package SuMoC.backend.user.dtos; import SuMoC.backend.user.enums.FriendShipStatus; +import lombok.Getter; +import lombok.Setter; import java.time.Instant; @@ -11,6 +13,8 @@ import java.time.Instant; * The MinimalUserDTO of the friend represents the friend depending on the relationship. * So only if friendship is accepted the private name of the friend is used as displayname. */ +@Setter +@Getter public class FriendshipDTO { private Long friendshipId; private Long userId; @@ -29,43 +33,4 @@ public class FriendshipDTO { this.createdAt = createdAt; } - public Long getFriendshipId() { - return friendshipId; - } - - public void setFriendshipId(Long friendshipId) { - this.friendshipId = friendshipId; - } - - public Long getUserId() { - return userId; - } - - public void setUserId(Long userId) { - this.userId = userId; - } - - public MinimalUserDTO getFriend() { - return friend; - } - - public void setFriend(MinimalUserDTO friend) { - this.friend = friend; - } - - public FriendShipStatus getStatus() { - return status; - } - - public void setStatus(FriendShipStatus status) { - this.status = status; - } - - public Instant getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Instant createdAt) { - this.createdAt = createdAt; - } } diff --git a/src/main/java/SuMoC/backend/user/service/FriendshipService.java b/src/main/java/SuMoC/backend/user/service/FriendshipService.java index ba8d5af..3a80d94 100644 --- a/src/main/java/SuMoC/backend/user/service/FriendshipService.java +++ b/src/main/java/SuMoC/backend/user/service/FriendshipService.java @@ -1,5 +1,6 @@ package SuMoC.backend.user.service; +import SuMoC.backend.notification.services.NotificationSchedulerService; import SuMoC.backend.user.dtos.FriendshipDTO; import SuMoC.backend.user.dtos.MinimalUserDTO; import SuMoC.backend.user.enums.FriendShipStatus; @@ -8,25 +9,22 @@ import SuMoC.backend.user.models.User; import SuMoC.backend.user.repository.FriendshipRepository; import SuMoC.backend.user.repository.UserRepository; import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; import org.jspecify.annotations.NonNull; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; -import java.util.Map; + +import static SuMoC.backend.notification.enums.NotificationType.FRIENDSHIP_REQUEST_RECEIVED; @Service @Transactional +@RequiredArgsConstructor public class FriendshipService { private final FriendshipRepository friendshipRepository; private final UserRepository userRepository; - - @Autowired - public FriendshipService(FriendshipRepository friendshipRepository, UserRepository userRepository) { - this.friendshipRepository = friendshipRepository; - this.userRepository = userRepository; - } + private final NotificationSchedulerService notificationSchedulerService; private static @NonNull MinimalUserDTO getMinimalUserDTOforFriend(Friendship friendship) { User friend = friendship.getFriend(); @@ -156,6 +154,36 @@ public class FriendshipService { Friendship reverseFriendship = new Friendship(requestedFriend, sender, FriendShipStatus.PENDING); friendshipRepository.save(friendship); friendshipRepository.save(reverseFriendship); + + // Send notification to requestedFriend about new friendship request + notifyAboutFriendshipRequest(reverseFriendship, sender, requestedFriend); + } + + /** + * Converts pending friendship into a dto and schedules a notification to the requested friend. + * This method should be called with the reverse friendship, so that the client receives the friendshipDto + * with a MinimalUserDTO of the sender. + */ + public void notifyAboutFriendshipRequest(Friendship requestFriendship, User sender, User requestedFriend) { + MinimalUserDTO senderMinimalUserDTO = new MinimalUserDTO( + sender.getId(), + sender.getPrivateName() + ); + + FriendshipDTO friendshipDTO = new FriendshipDTO( + requestFriendship.getId(), + requestedFriend.getId(), + senderMinimalUserDTO, + requestFriendship.getStatus(), + requestFriendship.getCreatedAt() + ); + + notificationSchedulerService.schedule( + requestedFriend.getId(), + friendshipDTO, + FRIENDSHIP_REQUEST_RECEIVED, + null + ); } public void acceptFriendship(User sender, long friendId) { @@ -272,14 +300,6 @@ public class FriendshipService { return dtoList; } - - - public record NameWithFriendship( - Long id, - String name, - boolean friendship - ) {} - public List getPrivateNameIfFriendshipAccepted(User user, List otherUserIds) { List result = new ArrayList<>(); @@ -323,4 +343,11 @@ public class FriendshipService { return friends; } + + public record NameWithFriendship( + Long id, + String name, + boolean friendship + ) { + } } diff --git a/src/test/java/SuMoC/backend/user/service/FriendshipServiceTest.java b/src/test/java/SuMoC/backend/user/service/FriendshipServiceTest.java index 068940f..115fbde 100644 --- a/src/test/java/SuMoC/backend/user/service/FriendshipServiceTest.java +++ b/src/test/java/SuMoC/backend/user/service/FriendshipServiceTest.java @@ -1,5 +1,6 @@ package SuMoC.backend.user.service; +import SuMoC.backend.notification.services.NotificationSchedulerService; import SuMoC.backend.user.enums.FriendShipStatus; import SuMoC.backend.user.models.Friendship; import SuMoC.backend.user.models.User; @@ -20,6 +21,7 @@ import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) @@ -31,6 +33,9 @@ public class FriendshipServiceTest { @Mock private UserRepository userRepository; + @Mock + private NotificationSchedulerService notificationSchedulerService; + @InjectMocks private FriendshipService friendshipService; @@ -69,6 +74,21 @@ public class FriendshipServiceTest { // Verify one friendship: friend -> sender, PENDING assertTrue(capturedFriendships.stream() .anyMatch(f -> f.getUser().equals(friend) && f.getFriend().equals(sender) && f.getStatus().equals(FriendShipStatus.PENDING))); + + // Verify notificationSchedulerService.schedule called with correct params + verify(notificationSchedulerService, times(1)).schedule( + eq(friend.getId()), + argThat(arg -> { + // Check FriendshipDTO fields + if (!(arg instanceof SuMoC.backend.user.dtos.FriendshipDTO dto)) return false; + return dto.getUserId().equals(friend.getId()) && + dto.getFriend().getId().equals(sender.getId()) && + dto.getFriend().getDisplayName().equals(sender.getPrivateName()) && + dto.getStatus() == FriendShipStatus.PENDING; + }), + eq(SuMoC.backend.notification.enums.NotificationType.FRIENDSHIP_REQUEST_RECEIVED), + isNull() + ); } @Test