diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index 968e6c5..82a9c90 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -16,14 +16,14 @@ services: - "5432:5432" restart: always - nominatim: - image: mediagis/nominatim:5.2 - container_name: nominatim - environment: - PBF_URL: https://download.geofabrik.de/europe/germany/nordrhein-westfalen-latest.osm.pbf - REPLICATION_ENABLED: false - volumes: - - nominatim-data:/var/lib/postgresql/14/main - restart: unless-stopped - ports: - - "6666:8080" +# nominatim: +# image: mediagis/nominatim:5.2 +# container_name: nominatim +# environment: +# PBF_URL: https://download.geofabrik.de/europe/germany/nordrhein-westfalen-latest.osm.pbf +# REPLICATION_ENABLED: false +# volumes: +# - nominatim-data:/var/lib/postgresql/14/main +# restart: unless-stopped +# ports: +# - "6666:8080" diff --git a/src/main/java/SuMoC/backend/common/converter/DayOfWeekConverter.java b/src/main/java/SuMoC/backend/common/converter/DayOfWeekConverter.java new file mode 100644 index 0000000..74b6f73 --- /dev/null +++ b/src/main/java/SuMoC/backend/common/converter/DayOfWeekConverter.java @@ -0,0 +1,34 @@ +package SuMoC.backend.common.converter; + +import jakarta.persistence.AttributeConverter; +import jakarta.persistence.Converter; +import java.time.DayOfWeek; + +/** + * This converter handles the conversion between Java's DayOfWeek enum and the SQL DAY_OF_WEEK integer representation. + * In Java, DayOfWeek uses 1 (Monday) to 7 (Sunday), while SQL's DAY_OF_WEEK function returns 1 (Sunday) to 7 (Saturday). + */ +@Converter(autoApply = true) +public class DayOfWeekConverter implements AttributeConverter { + + @Override + public Integer convertToDatabaseColumn(DayOfWeek attribute) { + if (attribute == null) { + return null; + } + // Convert Java DayOfWeek (1=Monday) to SQL format (1=Sunday) + return (attribute.getValue() % 7) + 1; + } + + @Override + public DayOfWeek convertToEntityAttribute(Integer dbData) { + if (dbData == null) { + return null; + } + // Convert SQL format (1=Sunday) back to Java DayOfWeek (1=Monday) + // Example: SQL 1 (Sunday) -> Java 7 + // SQL 7 (Saturday) -> Java 6 + // SQL 2 (Monday) -> Java 1 + return DayOfWeek.of(((dbData + 5) % 7) + 1); + } +} diff --git a/src/main/java/SuMoC/backend/dev/DevController.java b/src/main/java/SuMoC/backend/dev/DevController.java index f19bf8d..0c67871 100644 --- a/src/main/java/SuMoC/backend/dev/DevController.java +++ b/src/main/java/SuMoC/backend/dev/DevController.java @@ -1,19 +1,38 @@ package SuMoC.backend.dev; +import SuMoC.backend.firebase.FirebaseMessageBuilder; +import SuMoC.backend.h3.H3Service; import SuMoC.backend.meteo.ForecastService; import SuMoC.backend.meteo.MeteoClient; +import SuMoC.backend.notification.enums.NotificationStatus; +import SuMoC.backend.notification.enums.NotificationType; +import SuMoC.backend.notification.models.Notification; +import SuMoC.backend.notification.repositories.NotificationRepository; +import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO; +import SuMoC.backend.routing.dtos.RouteDTO; import SuMoC.backend.scheduling.ScheduledTasks; +import SuMoC.backend.suggestion.services.RegularTripSuggestionService; +import SuMoC.backend.trend.dto.TrendDetectionDTO; import SuMoC.backend.trend.services.StatTableUpdateService; +import SuMoC.backend.user.mapper.UserMapper; +import SuMoC.backend.user.models.User; +import SuMoC.backend.user.repository.UserRepository; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.firebase.messaging.FirebaseMessaging; +import com.google.firebase.messaging.Message; +import io.swagger.v3.oas.annotations.Operation; +import jakarta.validation.constraints.NotNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.HashMap; +import java.util.List; @RestController @RequestMapping("/dev") @@ -25,18 +44,36 @@ public class DevController { private final FirebaseMessaging firebaseMessaging; private final MeteoClient meteoClient; private final ForecastService forecastService; + private final FirebaseMessageBuilder firebaseMessageBuilder; + private final ObjectMapper objectMapper; + private final NotificationRepository notificationRepository; + private final UserRepository userRepository; + private final UserMapper userMapper; + private final H3Service h3Service; + private final RegularTripSuggestionService regularTripSuggestionService; public DevController( ScheduledTasks scheduledTasks, StatTableUpdateService statTableUpdateService, @Autowired(required = false) FirebaseMessaging firebaseMessaging, MeteoClient meteoClient, - ForecastService forecastService) { + ForecastService forecastService, + FirebaseMessageBuilder firebaseMessageBuilder, + ObjectMapper objectMapper, + NotificationRepository notificationRepository, UserRepository userRepository, UserMapper userMapper, H3Service h3Service, RegularTripSuggestionService regularTripSuggestionService + ) { this.scheduledTasks = scheduledTasks; this.statTableUpdateService = statTableUpdateService; this.firebaseMessaging = firebaseMessaging; this.meteoClient = meteoClient; this.forecastService = forecastService; + this.firebaseMessageBuilder = firebaseMessageBuilder; + this.objectMapper = objectMapper; + this.notificationRepository = notificationRepository; + this.userRepository = userRepository; + this.userMapper = userMapper; + this.h3Service = h3Service; + this.regularTripSuggestionService = regularTripSuggestionService; } @PostMapping("/trigger-trend-calculation") @@ -49,19 +86,23 @@ public class DevController { statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(day3WeeksAgo); } - @GetMapping("/test-firebase") - public ResponseEntity testFirebaseConnection() { + @GetMapping("/test-firebase-trend-notification/{fcm_token}") + @Operation(description = "Immediately sends a test notification of type TREND to the provided FCM token.") + public ResponseEntity SendTestTrendNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) { if (firebaseMessaging == null) { return ResponseEntity.status(503) .body("✗ Firebase is not configured (firebase.config.enabled=false)"); } try { + Notification notification = new Notification(); + notification.setType(NotificationType.TREND); + notification.setData(objectMapper.writeValueAsString(TrendDetectionDTO.mockTrendDetectionDTO())); + + Message mockTrendMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken); + // Send to a topic (no device registration needed) String message = firebaseMessaging.sendAsync( - com.google.firebase.messaging.Message.builder() - .setTopic("test-topic") - .putData("test", "connection-check") - .build() + mockTrendMessage ).get(); return ResponseEntity.ok("✓ Firebase message sent to topic: " + message); } catch (Exception e) { @@ -69,6 +110,133 @@ public class DevController { } } + @GetMapping("/test-firebase-adhoc-route-notification/{fcm_token}") + @Operation(description = "Immediately sends a test notification of type ADHOC_ALTERNATIVE to the provided FCM token.") + public ResponseEntity SendTestAdhocRouteNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) { + if (firebaseMessaging == null) { + return ResponseEntity.status(503) + .body("✗ Firebase is not configured (firebase.config.enabled=false)"); + } + try { + Notification notification = new Notification(); + notification.setType(NotificationType.ADHOC_ALTERNATIVE); + List mockRoutes = List.of(RouteDTO.getMockRouteDTO(), RouteDTO.getMockRouteDTO()); + notification.setData(objectMapper.writeValueAsString(mockRoutes)); + + Message mockAdhocMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken); + + // Send to a topic (no device registration needed) + String message = firebaseMessaging.sendAsync( + mockAdhocMessage + ).get(); + return ResponseEntity.ok("✓ Firebase message sent to topic: " + message); + } catch (Exception e) { + return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage()); + } + } + + @GetMapping("/test-firebase-regular-trip-notification/{fcm_token}") + @Operation(description = "Immediately sends a test notification of type REGULAR_TRIP_ALTERNATIVE to the provided FCM token.") + public ResponseEntity SendTestRegularTripAlternativeNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) { + if (firebaseMessaging == null) { + return ResponseEntity.status(503) + .body("✗ Firebase is not configured (firebase.config.enabled=false)"); + } + try { + Notification notification = new Notification(); + notification.setType(NotificationType.REGULAR_TRIP_ALTERNATIVE); + RouteDTO mockRoute = RouteDTO.getMockRouteDTO(); + notification.setData(objectMapper.writeValueAsString(mockRoute)); + Message mockRegularTripMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken); + // Send to a topic (no device registration needed) + String message = firebaseMessaging.sendAsync( + mockRegularTripMessage + ).get(); + return ResponseEntity.ok("✓ Firebase message sent to topic: " + message); + } catch (Exception e) { + return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage()); + } + } + + @GetMapping("/test-notification-from-detected-regular-trip") + @Operation(description = "Testing endpoint that mocks the detection of regular trips and then tests the alternative calculation and notification scheduling.") + public ResponseEntity testNotificationFromDetectedRegularTrip() { + if (firebaseMessaging == null) { + return ResponseEntity.status(503) + .body("✗ Firebase is not configured (firebase.config.enabled=false)"); + } + try { + // we seed user 1 and 2 in the dev data loader + HashMap> detectedRegularTripsByUser = new HashMap<>(); + List list1 = List.of( + DetectedRegularTripDTO.getTriggeringMock(h3Service, 1L) + ); + List list2 = List.of( + DetectedRegularTripDTO.getTriggeringMock(h3Service, 2L) + ); + detectedRegularTripsByUser.put(1L, list1); + detectedRegularTripsByUser.put(2L, list2); + + regularTripSuggestionService.checkAlternativesAndNotify(detectedRegularTripsByUser); + return ResponseEntity.ok("✓ Test notifications from detected regular trips processed."); + + + } catch (Exception e) { + return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage()); + } + } + + @Operation(description = "Immediately queues a notification to the fcm key specified in application-dev.properties to be processed by the notification queue.") + @GetMapping("/queue-test-notification") + public ResponseEntity queueTestNotification() { + if (firebaseMessaging == null) { + return ResponseEntity.status(503) + .body("✗ Firebase is not configured (firebase.config.enabled=false)"); + } + try { + User user = userRepository.findByEmail("user1@email.com").orElseThrow(); + + TrendDetectionDTO mockDTO = TrendDetectionDTO.mockTrendDetectionDTO(); + mockDTO.setUserId(user.getId()); + + Notification notification = Notification.builder() + .type(NotificationType.TREND) + .data(objectMapper.writeValueAsString(mockDTO)) + .user(user) + .earliestTimeOfDayToSend(LocalTime.now()) + .createdAt(LocalDateTime.now()) + .status(NotificationStatus.PENDING) + .build(); + + notificationRepository.save(notification); + + return ResponseEntity.ok("✓ Test notification queued."); + } catch (Exception e) { + return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage()); + } + } + + @Operation(description = "Tests the method cleaning old notifications from the database.") + @GetMapping("/test-clean-old-notifications") + public void testCleanOldNotifications() throws JsonProcessingException, InterruptedException { + User user = userRepository.findByEmail("user1@email.com").orElseThrow(); + + Notification notification = Notification.builder() + .type(NotificationType.TREND) + .data(objectMapper.writeValueAsString(TrendDetectionDTO.mockTrendDetectionDTO())) + .user(user) + .earliestTimeOfDayToSend(LocalTime.now()) + .createdAt(LocalDateTime.now().minusDays(60)) + .status(NotificationStatus.SENT) + .build(); + + notificationRepository.save(notification); + + Thread.sleep(5000); + + scheduledTasks.scheduleCleanUpOldNotifications(); + } + @GetMapping("/test-meteo") public void testMeteoClient() { try { diff --git a/src/main/java/SuMoC/backend/dev/DevProperties.java b/src/main/java/SuMoC/backend/dev/DevProperties.java new file mode 100644 index 0000000..88a7454 --- /dev/null +++ b/src/main/java/SuMoC/backend/dev/DevProperties.java @@ -0,0 +1,15 @@ +package SuMoC.backend.dev; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Data +@Component +@ConfigurationProperties(prefix = "sumoc.dev") +public class DevProperties { + /** + * Will be used to init the seeded users with in the dev profile. + */ + private String fcmKey = ""; +} diff --git a/src/main/java/SuMoC/backend/firebase/FirebaseMessageBuilder.java b/src/main/java/SuMoC/backend/firebase/FirebaseMessageBuilder.java new file mode 100644 index 0000000..3221a08 --- /dev/null +++ b/src/main/java/SuMoC/backend/firebase/FirebaseMessageBuilder.java @@ -0,0 +1,17 @@ +package SuMoC.backend.firebase; + +import SuMoC.backend.notification.models.Notification; +import com.google.firebase.messaging.Message; +import org.springframework.stereotype.Service; + +@Service +public class FirebaseMessageBuilder { + + public Message generateMessage(Notification notification, String token) { + var builder = Message.builder().setToken(token); + builder.putData("type", notification.getType().toString()); + builder.putData("data", notification.getData()); + return builder.build(); + } + +} diff --git a/src/main/java/SuMoC/backend/notification/NotificationController.java b/src/main/java/SuMoC/backend/notification/NotificationController.java new file mode 100644 index 0000000..8571ae5 --- /dev/null +++ b/src/main/java/SuMoC/backend/notification/NotificationController.java @@ -0,0 +1,43 @@ +package SuMoC.backend.notification; + +import SuMoC.backend.notification.enums.NotificationProvider; +import SuMoC.backend.notification.services.NotificationTokenService; +import SuMoC.backend.user.models.User; +import SuMoC.backend.user.repository.UserRepository; +import io.swagger.v3.oas.annotations.Operation; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/notifications") +@RequiredArgsConstructor +public class NotificationController { + + private final UserRepository userRepository; + + private final NotificationTokenService notificationTokenService; + + // TODO extend security context with user id to avoid unnecessary db query + private User getAuthenticatedUser() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + return userRepository.findByEmail(authentication.getName()).orElseThrow(() -> new RuntimeException("User not found")); + } + + @PutMapping("/register-device-token") + @Operation(summary = "Registers a device token for push notifications for the authenticated user.") + public ResponseEntity registerDeviceToken(@RequestBody RegisterDeviceTokenRequest request) { + User user = getAuthenticatedUser(); + notificationTokenService.registerDeviceToken(user, request.provider(), request.token()); + return ResponseEntity.ok().build(); + } + + // Simple record for request body + public record RegisterDeviceTokenRequest(String token, NotificationProvider provider) { + } +} diff --git a/src/main/java/SuMoC/backend/notification/config/NotificationProperties.java b/src/main/java/SuMoC/backend/notification/config/NotificationProperties.java new file mode 100644 index 0000000..c30fa86 --- /dev/null +++ b/src/main/java/SuMoC/backend/notification/config/NotificationProperties.java @@ -0,0 +1,15 @@ +package SuMoC.backend.notification.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Data +@Component +@ConfigurationProperties(prefix = "sumoc.notification") +public class NotificationProperties { + /** + * Maximum number of failed send attempts before giving up on a notification. + */ + private int maxFailedSendAttempts = 3; +} diff --git a/src/main/java/SuMoC/backend/notification/enums/NotificationProvider.java b/src/main/java/SuMoC/backend/notification/enums/NotificationProvider.java new file mode 100644 index 0000000..3374577 --- /dev/null +++ b/src/main/java/SuMoC/backend/notification/enums/NotificationProvider.java @@ -0,0 +1,5 @@ +package SuMoC.backend.notification.enums; + +public enum NotificationProvider { + FIREBASE, +} diff --git a/src/main/java/SuMoC/backend/notification/enums/NotificationStatus.java b/src/main/java/SuMoC/backend/notification/enums/NotificationStatus.java index 964bc50..510df81 100644 --- a/src/main/java/SuMoC/backend/notification/enums/NotificationStatus.java +++ b/src/main/java/SuMoC/backend/notification/enums/NotificationStatus.java @@ -1,7 +1,16 @@ package SuMoC.backend.notification.enums; public enum NotificationStatus { + /** + * Has never been sent successfully. Will be retried. + */ PENDING, + /** + * Has been sent successfully. + */ SENT, + /** + * Has failed to send and will not be retried. + */ FAILED } diff --git a/src/main/java/SuMoC/backend/notification/enums/NotificationType.java b/src/main/java/SuMoC/backend/notification/enums/NotificationType.java new file mode 100644 index 0000000..b58a0ef --- /dev/null +++ b/src/main/java/SuMoC/backend/notification/enums/NotificationType.java @@ -0,0 +1,20 @@ +package SuMoC.backend.notification.enums; + +/** + * Notification type that will be included in the data sent to the mobile devices. + */ +public enum NotificationType { + /** + * Informing about a change in mobility trends, e.g. driving less car. + */ + TREND, + /** + * An alternative suggestion following the upload of a recent trip. + */ + ADHOC_ALTERNATIVE, + /** + * 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 +} diff --git a/src/main/java/SuMoC/backend/notification/factories/TrendNotificationFactory.java b/src/main/java/SuMoC/backend/notification/factories/TrendNotificationFactory.java deleted file mode 100644 index d16cc2b..0000000 --- a/src/main/java/SuMoC/backend/notification/factories/TrendNotificationFactory.java +++ /dev/null @@ -1,20 +0,0 @@ -package SuMoC.backend.notification.factories; - -import SuMoC.backend.notification.models.Notification; -import SuMoC.backend.trend.TrendDetection; -import SuMoC.backend.trend.services.TrendMessageGenerator; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Component; - -@Component -@RequiredArgsConstructor -public class TrendNotificationFactory { - - private final TrendMessageGenerator trendMessageGenerator; - - public Notification createNotification(TrendDetection trend) { - return Notification.builder() - .user(trend.getUser()) - .build(); - } -} diff --git a/src/main/java/SuMoC/backend/notification/interfaces/NotificationPublisher.java b/src/main/java/SuMoC/backend/notification/interfaces/NotificationPublisher.java deleted file mode 100644 index 090a260..0000000 --- a/src/main/java/SuMoC/backend/notification/interfaces/NotificationPublisher.java +++ /dev/null @@ -1,4 +0,0 @@ -package SuMoC.backend.notification.interfaces; - -public interface NotificationPublisher { -} diff --git a/src/main/java/SuMoC/backend/notification/interfaces/NotificationSender.java b/src/main/java/SuMoC/backend/notification/interfaces/NotificationSender.java deleted file mode 100644 index 7af6679..0000000 --- a/src/main/java/SuMoC/backend/notification/interfaces/NotificationSender.java +++ /dev/null @@ -1,4 +0,0 @@ -package SuMoC.backend.notification.interfaces; - -public interface NotificationSender { -} diff --git a/src/main/java/SuMoC/backend/notification/interfaces/Notifieable.java b/src/main/java/SuMoC/backend/notification/interfaces/Notifieable.java new file mode 100644 index 0000000..bf2606b --- /dev/null +++ b/src/main/java/SuMoC/backend/notification/interfaces/Notifieable.java @@ -0,0 +1,5 @@ +package SuMoC.backend.notification.interfaces; + +public interface Notifieable { + Long getUserId(); +} diff --git a/src/main/java/SuMoC/backend/notification/models/Notification.java b/src/main/java/SuMoC/backend/notification/models/Notification.java index dda300e..52c1719 100644 --- a/src/main/java/SuMoC/backend/notification/models/Notification.java +++ b/src/main/java/SuMoC/backend/notification/models/Notification.java @@ -1,6 +1,7 @@ package SuMoC.backend.notification.models; import SuMoC.backend.notification.enums.NotificationStatus; +import SuMoC.backend.notification.enums.NotificationType; import SuMoC.backend.user.models.User; import jakarta.persistence.*; import lombok.*; @@ -25,7 +26,11 @@ public class Notification { private User user; @Column(nullable = false) - private String message; + @Enumerated(EnumType.STRING) + private NotificationType type; + + @Column(columnDefinition = "TEXT") + private String data; // Store serialized DTO as JSON /** * Time of day from which on a notification might be sent. @@ -36,11 +41,23 @@ public class Notification { private LocalTime earliestTimeOfDayToSend; @Column(nullable = false) - private NotificationStatus status; + @Enumerated(EnumType.STRING) + private NotificationStatus status = NotificationStatus.PENDING; + /** + * Number of retry attempts made to send this notification. + */ @Column(nullable = false) - private int retryCount; + private int failedSendAttempts = 0; + + @Column + private String lastFailureReason; @Column(nullable = false) + private LocalDateTime createdAt; + + public void incrementFailedSendAttempts() { + this.failedSendAttempts++; + } } diff --git a/src/main/java/SuMoC/backend/notification/models/NotificationToken.java b/src/main/java/SuMoC/backend/notification/models/NotificationToken.java new file mode 100644 index 0000000..3fb132a --- /dev/null +++ b/src/main/java/SuMoC/backend/notification/models/NotificationToken.java @@ -0,0 +1,23 @@ +package SuMoC.backend.notification.models; + +import SuMoC.backend.notification.enums.NotificationProvider; +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +@Entity +public class NotificationToken { + + @Id + @Column(name = "user_id", nullable = false, unique = true) + private Long userId; + + @Column(nullable = false) + @Enumerated(EnumType.STRING) + private NotificationProvider provider; + + @Column(nullable = false, length = 512) + private String token; +} diff --git a/src/main/java/SuMoC/backend/notification/repositories/NotificationRepository.java b/src/main/java/SuMoC/backend/notification/repositories/NotificationRepository.java index 0667d67..1376d14 100644 --- a/src/main/java/SuMoC/backend/notification/repositories/NotificationRepository.java +++ b/src/main/java/SuMoC/backend/notification/repositories/NotificationRepository.java @@ -2,6 +2,29 @@ package SuMoC.backend.notification.repositories; import SuMoC.backend.notification.models.Notification; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; + +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.List; public interface NotificationRepository extends JpaRepository { + @Query(""" + SELECT n + FROM Notification n + LEFT JOIN FETCH n.user u + LEFT JOIN FETCH u.notificationToken + WHERE n.status = 'PENDING' + AND n.earliestTimeOfDayToSend <= :currentTime + """) + List findPendingNotificationsToSend(LocalTime currentTime); + + @Modifying + @Query(""" + DELETE + FROM Notification n + WHERE n.createdAt < :cutOff + """) + void deleteNotificationsOlder(LocalDateTime cutOff); } diff --git a/src/main/java/SuMoC/backend/notification/repositories/NotificationTokenRepository.java b/src/main/java/SuMoC/backend/notification/repositories/NotificationTokenRepository.java new file mode 100644 index 0000000..b0d3d32 --- /dev/null +++ b/src/main/java/SuMoC/backend/notification/repositories/NotificationTokenRepository.java @@ -0,0 +1,10 @@ +package SuMoC.backend.notification.repositories; + +import SuMoC.backend.notification.models.NotificationToken; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface NotificationTokenRepository extends JpaRepository { + Optional findByUserId(Long userId); +} diff --git a/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java b/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java new file mode 100644 index 0000000..e5bdbea --- /dev/null +++ b/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java @@ -0,0 +1,83 @@ +package SuMoC.backend.notification.services; + +import SuMoC.backend.notification.enums.NotificationStatus; +import SuMoC.backend.notification.enums.NotificationType; +import SuMoC.backend.notification.interfaces.Notifieable; +import SuMoC.backend.notification.models.Notification; +import SuMoC.backend.notification.repositories.NotificationRepository; +import SuMoC.backend.user.models.User; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.persistence.EntityManager; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.List; + +@Service +@RequiredArgsConstructor +public class NotificationSchedulerService { + + private final ObjectMapper objectMapper; + + private final NotificationRepository notificationRepository; + + private final EntityManager entityManager; + + public void scheduleAll(List dataBodies, + NotificationType notificationType, + LocalTime earliestTimeOfDayToSend + ) { + List notifications = dataBodies.stream().map(dataBody -> { + String dataBodyJson; + try { + dataBodyJson = objectMapper.writeValueAsString(dataBody); + } catch (Exception e) { + throw new RuntimeException("Failed to serialize notification data body", e); + } + + User userProxy = entityManager.getReference(User.class, dataBody.getUserId()); + + return Notification.builder() + .user(userProxy) + .type(notificationType) + .data(dataBodyJson) + .earliestTimeOfDayToSend(earliestTimeOfDayToSend) + .status(NotificationStatus.PENDING) + .createdAt(LocalDateTime.now()) + .failedSendAttempts(0) + .build(); + }).toList(); + + notificationRepository.saveAll(notifications); + } + + public void schedule( + Long userId, + Object dataBody, + NotificationType notificationType, + LocalTime earliestTimeOfDayToSend + ) { + String dataBodyJson; + try { + dataBodyJson = objectMapper.writeValueAsString(dataBody); + } catch (Exception e) { + throw new RuntimeException("Failed to serialize notification data body", e); + } + + User userProxy = entityManager.getReference(User.class, userId); + + Notification notification = Notification.builder() + .user(userProxy) + .type(notificationType) + .data(dataBodyJson) + .earliestTimeOfDayToSend(earliestTimeOfDayToSend) + .status(NotificationStatus.PENDING) + .createdAt(LocalDateTime.now()) + .failedSendAttempts(0) + .build(); + + notificationRepository.save(notification); + } +} diff --git a/src/main/java/SuMoC/backend/notification/services/NotificationSender.java b/src/main/java/SuMoC/backend/notification/services/NotificationSender.java new file mode 100644 index 0000000..ae0ced7 --- /dev/null +++ b/src/main/java/SuMoC/backend/notification/services/NotificationSender.java @@ -0,0 +1,87 @@ +package SuMoC.backend.notification.services; + +import SuMoC.backend.firebase.FirebaseMessageBuilder; +import SuMoC.backend.notification.config.NotificationProperties; +import SuMoC.backend.notification.enums.NotificationStatus; +import SuMoC.backend.notification.models.Notification; +import SuMoC.backend.notification.models.NotificationToken; +import SuMoC.backend.notification.repositories.NotificationRepository; +import SuMoC.backend.notification.repositories.NotificationTokenRepository; +import com.google.api.core.ApiFuture; +import com.google.api.core.ApiFutureCallback; +import com.google.api.core.ApiFutures; +import com.google.common.util.concurrent.MoreExecutors; +import com.google.firebase.messaging.FirebaseMessaging; +import com.google.firebase.messaging.Message; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.logging.Logger; + +@Service +public class NotificationSender { + + private final FirebaseMessageBuilder firebaseMessageBuilder; + private final Logger logger = Logger.getLogger(NotificationSender.class.getName()); + private final FirebaseMessaging firebaseMessaging; + private final NotificationRepository notificationRepository; + private final NotificationProperties notificationProperties; + + public NotificationSender( + NotificationTokenRepository notificationTokenRepository, + FirebaseMessageBuilder firebaseMessageBuilder, + @Autowired(required = false) FirebaseMessaging firebaseMessaging, + NotificationRepository notificationRepository, NotificationProperties notificationProperties + ) { + this.firebaseMessageBuilder = firebaseMessageBuilder; + this.firebaseMessaging = firebaseMessaging; + this.notificationRepository = notificationRepository; + this.notificationProperties = notificationProperties; + } + + public void sendNotification(Notification notification) { + NotificationToken token = notification.getUser().getNotificationToken(); + + if (token == null) { + logger.warning("No notification token found notification id: " + notification.getId()); + notification.incrementFailedSendAttempts(); + notificationRepository.save(notification); + return; + } + + switch (token.getProvider()) { + case FIREBASE -> sendViaFirebase(token, notification); + } + } + + private void sendViaFirebase(NotificationToken token, Notification notification) { + if (firebaseMessaging == null) { + logger.warning("FirebaseMessaging not configured"); + return; + } + + Message message = firebaseMessageBuilder.generateMessage(notification, token.getToken()); + + ApiFuture future = firebaseMessaging.sendAsync(message); + ApiFutures.addCallback(future, new ApiFutureCallback() { + @Override + public void onSuccess(String messageId) { + notification.setStatus(NotificationStatus.SENT); + notificationRepository.save(notification); + logger.info("Notification sent successfully to user: " + notification.getUser().getId()); + } + + @Override + public void onFailure(Throwable t) { + notification.incrementFailedSendAttempts(); + notification.setLastFailureReason(t.getMessage()); + if (notification.getFailedSendAttempts() >= notificationProperties.getMaxFailedSendAttempts()) { + notification.setStatus(NotificationStatus.FAILED); + } + notificationRepository.save(notification); + logger.severe("Failed to send notification with id:" + notification.getId() + " " + t.getMessage()); + } + }, MoreExecutors.directExecutor()); + + } +} diff --git a/src/main/java/SuMoC/backend/notification/services/NotificationTokenService.java b/src/main/java/SuMoC/backend/notification/services/NotificationTokenService.java new file mode 100644 index 0000000..978791a --- /dev/null +++ b/src/main/java/SuMoC/backend/notification/services/NotificationTokenService.java @@ -0,0 +1,30 @@ +package SuMoC.backend.notification.services; + +import SuMoC.backend.notification.enums.NotificationProvider; +import SuMoC.backend.notification.models.NotificationToken; +import SuMoC.backend.notification.repositories.NotificationTokenRepository; +import SuMoC.backend.user.models.User; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class NotificationTokenService { + + private final NotificationTokenRepository notificationTokenRepository; + + public void registerDeviceToken(User user, NotificationProvider provider, String token) { + var existingToken = notificationTokenRepository.findByUserId(user.getId()); + if (existingToken.isPresent()) { + var notificationToken = existingToken.get(); + notificationToken.setToken(token); + notificationTokenRepository.save(notificationToken); + } else { + var newToken = new NotificationToken(); + newToken.setUserId(user.getId()); + newToken.setProvider(provider); + newToken.setToken(token); + notificationTokenRepository.save(newToken); + } + } +} diff --git a/src/main/java/SuMoC/backend/notification/services/NotificationWorker.java b/src/main/java/SuMoC/backend/notification/services/NotificationWorker.java new file mode 100644 index 0000000..0a0a81d --- /dev/null +++ b/src/main/java/SuMoC/backend/notification/services/NotificationWorker.java @@ -0,0 +1,42 @@ +package SuMoC.backend.notification.services; + +import SuMoC.backend.notification.models.Notification; +import SuMoC.backend.notification.repositories.NotificationRepository; +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.List; + +@Service +@Transactional +@RequiredArgsConstructor +public class NotificationWorker { + + private final NotificationRepository notificationRepository; + + private final NotificationSender notificationSender; + + /** + * Process all pending notifications. + */ + public void run() { + // Get all pending notifications where earliest send time has passed and status is pending + List pendingNotifications = + notificationRepository.findPendingNotificationsToSend(LocalTime.now()); + // Send them + for (Notification notification : pendingNotifications) { + notificationSender.sendNotification(notification); + } + } + + /** + * Clean up old notifications. + */ + public void cleanUpOldNotifications() { + // Delete notifications older than 30 days + notificationRepository.deleteNotificationsOlder(LocalDateTime.now().minusDays(30)); + } +} diff --git a/src/main/java/SuMoC/backend/notification/services/TrendNotificationService.java b/src/main/java/SuMoC/backend/notification/services/TrendNotificationService.java deleted file mode 100644 index d0b8d98..0000000 --- a/src/main/java/SuMoC/backend/notification/services/TrendNotificationService.java +++ /dev/null @@ -1,25 +0,0 @@ -package SuMoC.backend.notification.services; - -import SuMoC.backend.notification.factories.TrendNotificationFactory; -import SuMoC.backend.notification.models.Notification; -import SuMoC.backend.notification.repositories.NotificationRepository; -import SuMoC.backend.trend.TrendDetection; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; - -import java.util.List; - -@Service -@RequiredArgsConstructor -public class TrendNotificationService { - - private final NotificationRepository notificationRepository; - - private final TrendNotificationFactory trendNotificationFactory; - - public List generateTrendNotifications(List trendList) { - List notificationList = trendList.stream().map(trendNotificationFactory::createNotification).toList(); - - return List.of(); - } -} diff --git a/src/main/java/SuMoC/backend/regulartrip/config/DetectorConfiguration.java b/src/main/java/SuMoC/backend/regulartrip/config/DetectorConfiguration.java index 996042a..a71dc93 100644 --- a/src/main/java/SuMoC/backend/regulartrip/config/DetectorConfiguration.java +++ b/src/main/java/SuMoC/backend/regulartrip/config/DetectorConfiguration.java @@ -16,7 +16,7 @@ public class DetectorConfiguration { havingValue = "iterative", matchIfMissing = true ) - public Detector iterativeClusterer(RegularTripDetectionProperties properties) { + public IterativeClusterer iterativeClusterer(RegularTripDetectionProperties properties) { return new IterativeClusterer(properties); } } diff --git a/src/main/java/SuMoC/backend/regulartrip/config/RegularTripDetectionProperties.java b/src/main/java/SuMoC/backend/regulartrip/config/RegularTripDetectionProperties.java index a2b238e..71131fd 100644 --- a/src/main/java/SuMoC/backend/regulartrip/config/RegularTripDetectionProperties.java +++ b/src/main/java/SuMoC/backend/regulartrip/config/RegularTripDetectionProperties.java @@ -19,7 +19,7 @@ public class RegularTripDetectionProperties { /** * Time window in days to look back for detecting regular trips. */ - private Integer detectionTimeWindowDays = 30; + private Integer detectionTimeWindowDays = 40; /** * Maximum time difference in minutes between trips to be considered the same regular trip. diff --git a/src/main/java/SuMoC/backend/regulartrip/dtos/DetectedRegularTripDTO.java b/src/main/java/SuMoC/backend/regulartrip/dtos/DetectedRegularTripDTO.java index d3c9091..6d85105 100644 --- a/src/main/java/SuMoC/backend/regulartrip/dtos/DetectedRegularTripDTO.java +++ b/src/main/java/SuMoC/backend/regulartrip/dtos/DetectedRegularTripDTO.java @@ -1,10 +1,14 @@ package SuMoC.backend.regulartrip.dtos; +import SuMoC.backend.h3.H3Service; import SuMoC.backend.trip.Modality; import SuMoC.backend.trip.dtos.RegularTripDetectionDTO; import lombok.*; +import java.time.DayOfWeek; +import java.time.LocalDateTime; import java.time.LocalTime; +import java.time.ZoneOffset; import java.util.List; /** @@ -18,7 +22,7 @@ import java.util.List; public class DetectedRegularTripDTO { private long userId; private Modality modality; - private int dayOfWeek; + private DayOfWeek dayOfWeek; private LocalTime departureWindowStart; private LocalTime departureWindowEnd; private LocalTime arrivalWindowStart; @@ -28,4 +32,56 @@ public class DetectedRegularTripDTO { private List startH3neighbours; private List endH3Neighbours; private List supportingTrips; + + /** + * Mock dto that should trigger available alternative. + */ + public static DetectedRegularTripDTO getTriggeringMock(H3Service h3Service, Long userId) { + String h3_schutzenbahn = "8a1fa535568ffff"; // Essen Schuetzenbahn + String h3_essen_hbf = "8a1fa535020ffff"; // Essen Hbf + + return DetectedRegularTripDTO.builder() + .userId(userId) + .modality(Modality.CAR) + .dayOfWeek(LocalDateTime.now().getDayOfWeek()) + .departureWindowStart(LocalTime.now().plusMinutes(20)) + .departureWindowEnd(LocalTime.now().plusMinutes(30)) + .arrivalWindowStart(LocalTime.now().plusMinutes(60)) + .arrivalWindowEnd(LocalTime.now().plusMinutes(70)) + .startH3Center(h3_schutzenbahn) // Essen Schuetzenbahn + .endH3Center(h3_essen_hbf) // Essen Hbf + .startH3neighbours(h3Service.getRoutePatternNeighbors(h3_schutzenbahn)) + .endH3Neighbours(h3Service.getRoutePatternNeighbors(h3_essen_hbf)) + .supportingTrips(List.of( + RegularTripDetectionDTO.builder() + .tripId(userId) + .userId(userId) + .startH3Cell(h3_schutzenbahn) + .endH3Cell(h3_essen_hbf) + .startTime(LocalTime.now().plusMinutes(20).atDate(LocalDateTime.now().toLocalDate()).toInstant(ZoneOffset.UTC)) + .endTime(LocalTime.now().plusMinutes(60).atDate(LocalDateTime.now().toLocalDate()).toInstant(ZoneOffset.UTC)) + .mainModality(Modality.CAR) + .startH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(h3_schutzenbahn)) + .endH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(h3_essen_hbf)) + .build() + )) + .build(); + } + + public LocalTime getAverageArrivalTime() { + int totalSeconds = 0; + for (RegularTripDetectionDTO trip : supportingTrips) { + totalSeconds += trip.getEndTime().atOffset(ZoneOffset.UTC).toLocalTime().toSecondOfDay(); + } + int averageSeconds = totalSeconds / supportingTrips.size(); + return LocalTime.ofSecondOfDay(averageSeconds); + } + + public int getAverageDurationMinutes() { + int totalDuration = 0; + for (RegularTripDetectionDTO trip : supportingTrips) { + totalDuration += trip.getDurationMinutes(); + } + return totalDuration / supportingTrips.size(); + } } diff --git a/src/main/java/SuMoC/backend/regulartrip/services/RegularTripDetectionService.java b/src/main/java/SuMoC/backend/regulartrip/services/RegularTripDetectionService.java index 3890f1a..2c7586f 100644 --- a/src/main/java/SuMoC/backend/regulartrip/services/RegularTripDetectionService.java +++ b/src/main/java/SuMoC/backend/regulartrip/services/RegularTripDetectionService.java @@ -9,6 +9,7 @@ import SuMoC.backend.trip.TripRepository; import SuMoC.backend.trip.dtos.RegularTripDetectionDTO; import org.springframework.stereotype.Service; +import java.time.DayOfWeek; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; @@ -26,14 +27,13 @@ public class RegularTripDetectionService { Detector tripDetector; /** - * Detects regular trips for all users based on saved trip data and RegularTripDetectionProperties. + * Detects regular trips for the current day of the week for all users based on saved trip data and RegularTripDetectionProperties. * This is the main method that orchestrates the detection process and should be used to detect trips * we want to suggest alternatives for. */ - public HashMap> detectRegularCarTrips() { - var tripsByUser = getTripsByUser(Modality.CAR); + public HashMap> detectRegularCarTripsByUserForDayOfWeek(DayOfWeek dayOfWeek) { + var tripsByUser = getTripsByUser(Modality.CAR, dayOfWeek); - // TODO this could be parallelized in the future HashMap> results = new HashMap<>(); for (Long userId : tripsByUser.keySet()) { results.put(userId, tripDetector.detectRegularTrips(tripsByUser.get(userId))); @@ -42,9 +42,9 @@ public class RegularTripDetectionService { return results; } - private HashMap> getTripsByUser(Modality modality) { + private HashMap> getTripsByUser(Modality modality, DayOfWeek dayOfWeek) { Instant fromDate = Instant.now().minusSeconds(properties.getDetectionTimeWindowDays() * 24 * 60 * 60); - List dtoList = tripMapper.toRegularTripDetectionDTOS(tripRepository.findAllValidFromDateWithMainModality(fromDate, modality)); + List dtoList = tripMapper.toRegularTripDetectionDTOS(tripRepository.findAllValidFromDateWithMainModalityOnCertainWeekday(fromDate, modality, dayOfWeek)); HashMap> tripsByUser = new HashMap<>(); for (RegularTripDetectionDTO dto : dtoList) { diff --git a/src/main/java/SuMoC/backend/routing/RoutingController.java b/src/main/java/SuMoC/backend/routing/controller/RoutingController.java similarity index 80% rename from src/main/java/SuMoC/backend/routing/RoutingController.java rename to src/main/java/SuMoC/backend/routing/controller/RoutingController.java index e06bd5e..ca642d8 100644 --- a/src/main/java/SuMoC/backend/routing/RoutingController.java +++ b/src/main/java/SuMoC/backend/routing/controller/RoutingController.java @@ -1,12 +1,12 @@ -package SuMoC.backend.routing; +package SuMoC.backend.routing.controller; import SuMoC.backend.routing.dtos.RouteDTO; import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO; -import SuMoC.backend.routing.dtos.RoutingPreferencesDTO; +import SuMoC.backend.routing.services.RoutingPreferencesService; import SuMoC.backend.routing.services.RoutingService; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.Valid; -import org.springframework.beans.factory.annotation.Autowired; +import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -20,25 +20,22 @@ import java.util.logging.Logger; @RestController @RequestMapping("/routing/alternative") +@RequiredArgsConstructor public class RoutingController { private final Logger logger = Logger.getLogger(RoutingController.class.getName()); private final RoutingService routingService; - @Autowired - public RoutingController(RoutingService routingService) { - this.routingService = routingService; - } + private final RoutingPreferencesService routingPreferencesService; @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 (routingAlternativeRequestDTO.getRoutingPreferencesDTO() == null) { // Use default preferences if none are provided - // TODO we might want to also save users preferences in the future - var preferences = new RoutingPreferencesDTO(); // use default preferences - routingAlternativeRequestDTO.setRoutingPreferencesDTO(preferences); + if (routingAlternativeRequestDTO.getRoutingPreferencesDTO() == null) { + // This automatically uses default preferences for unauthenticated users + routingAlternativeRequestDTO.setRoutingPreferencesDTO(routingPreferencesService.getRoutingPreferencesForCurrentUser()); } var routeDTOs = routingService.determineAlternativeRoutesOnUserRequest(routingAlternativeRequestDTO); diff --git a/src/main/java/SuMoC/backend/routing/controller/RoutingPreferencesController.java b/src/main/java/SuMoC/backend/routing/controller/RoutingPreferencesController.java new file mode 100644 index 0000000..9405da0 --- /dev/null +++ b/src/main/java/SuMoC/backend/routing/controller/RoutingPreferencesController.java @@ -0,0 +1,36 @@ +package SuMoC.backend.routing.controller; + +import SuMoC.backend.routing.dtos.RoutingPreferencesDTO; +import SuMoC.backend.routing.services.RoutingPreferencesService; +import SuMoC.backend.user.models.User; +import SuMoC.backend.user.service.CurrentUserService; +import io.swagger.v3.oas.annotations.Operation; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/routing/preferences") +@RequiredArgsConstructor +public class RoutingPreferencesController { + + private final RoutingPreferencesService routingPreferencesService; + + private final CurrentUserService currentUserService; + + @Operation(summary = "Get the routing preferences of the current user", description = "Retrieves the routing preferences set by the authenticated user.") + @GetMapping("/get") + public ResponseEntity getRoutingPreferences() { + User user = currentUserService.get(); + RoutingPreferencesDTO preferences = routingPreferencesService.getUserRoutingPreferences(user.getId()); + return ResponseEntity.ok(preferences); + } + + @Operation(summary = "Update the routing preferences of the current user", description = "Updates the routing preferences for the authenticated user with the provided settings.") + @PutMapping("/update") + public ResponseEntity updateRoutingPreferences(@RequestBody RoutingPreferencesDTO newPreferencesDTO) { + User user = currentUserService.get(); + routingPreferencesService.updateUserRoutingPreferences(user.getId(), newPreferencesDTO); + return ResponseEntity.ok().build(); + } +} diff --git a/src/main/java/SuMoC/backend/routing/mapper/RoutingPreferencesMapper.java b/src/main/java/SuMoC/backend/routing/mapper/RoutingPreferencesMapper.java new file mode 100644 index 0000000..29112d5 --- /dev/null +++ b/src/main/java/SuMoC/backend/routing/mapper/RoutingPreferencesMapper.java @@ -0,0 +1,13 @@ +package SuMoC.backend.routing.mapper; + +import SuMoC.backend.routing.dtos.RoutingPreferencesDTO; +import SuMoC.backend.routing.models.RoutingPreferences; +import org.mapstruct.Mapper; + +@Mapper(componentModel = "spring") +public interface RoutingPreferencesMapper { + RoutingPreferencesDTO toRoutingPreferencesDTO(RoutingPreferences routingPreferences); + + RoutingPreferences toRoutingPreferences(RoutingPreferencesDTO routingPreferencesDTO); +} + diff --git a/src/main/java/SuMoC/backend/routing/models/RoutingPreferences.java b/src/main/java/SuMoC/backend/routing/models/RoutingPreferences.java new file mode 100644 index 0000000..6e6f469 --- /dev/null +++ b/src/main/java/SuMoC/backend/routing/models/RoutingPreferences.java @@ -0,0 +1,40 @@ +package SuMoC.backend.routing.models; + +import SuMoC.backend.trip.Modality; +import SuMoC.backend.user.models.User; +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; + +import java.util.ArrayList; +import java.util.List; + +@Entity +@Table(name = "routing_preferences") +@Getter +@Setter +public class RoutingPreferences { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @OneToOne(mappedBy = "routingPreferences") + private User user; + + private boolean preferPhysicalActivity; + private boolean considerWeatherConditions; + + @ElementCollection(targetClass = Modality.class, fetch = FetchType.EAGER) + @CollectionTable(name = "routing_preferences_modalities", joinColumns = @JoinColumn(name = "routing_preferences_id")) + @Enumerated(EnumType.STRING) + private List modalitiesToConsider = new ArrayList<>(); + + + public static RoutingPreferences getDefaultPreferences() { + RoutingPreferences preferences = new RoutingPreferences(); + preferences.setPreferPhysicalActivity(false); + preferences.setConsiderWeatherConditions(true); + preferences.setModalitiesToConsider(List.of(Modality.WALKING, Modality.BICYCLE, Modality.ESCOOTER, Modality.BUS, Modality.TRAM, Modality.TRAIN)); + return preferences; + } +} diff --git a/src/main/java/SuMoC/backend/routing/repository/RoutingPreferencesRepository.java b/src/main/java/SuMoC/backend/routing/repository/RoutingPreferencesRepository.java new file mode 100644 index 0000000..9f769d2 --- /dev/null +++ b/src/main/java/SuMoC/backend/routing/repository/RoutingPreferencesRepository.java @@ -0,0 +1,10 @@ +package SuMoC.backend.routing.repository; + +import SuMoC.backend.routing.models.RoutingPreferences; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface RoutingPreferencesRepository extends JpaRepository { + Optional findByUserId(Long userId); +} diff --git a/src/main/java/SuMoC/backend/routing/services/RoutingPreferencesService.java b/src/main/java/SuMoC/backend/routing/services/RoutingPreferencesService.java new file mode 100644 index 0000000..558ac21 --- /dev/null +++ b/src/main/java/SuMoC/backend/routing/services/RoutingPreferencesService.java @@ -0,0 +1,62 @@ +package SuMoC.backend.routing.services; + + +import SuMoC.backend.routing.dtos.RoutingPreferencesDTO; +import SuMoC.backend.routing.mapper.RoutingPreferencesMapper; +import SuMoC.backend.routing.models.RoutingPreferences; +import SuMoC.backend.routing.repository.RoutingPreferencesRepository; +import SuMoC.backend.user.service.CurrentUserService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.Optional; + +@Service +@RequiredArgsConstructor +public class RoutingPreferencesService { + + private final RoutingPreferencesRepository routingPreferencesRepository; + + private final RoutingPreferencesMapper routingPreferencesMapper; + + private final CurrentUserService currentUserService; + + public void updateUserRoutingPreferences(Long userId, RoutingPreferencesDTO newPreferencesDTO) { + Optional optionalPreferences = routingPreferencesRepository.findByUserId(userId); + + RoutingPreferences preferences = optionalPreferences.orElseGet(RoutingPreferences::getDefaultPreferences); + + preferences.setPreferPhysicalActivity(newPreferencesDTO.isPreferPhysicalActivity()); + preferences.setConsiderWeatherConditions(newPreferencesDTO.isConsiderWeatherConditions()); + preferences.setModalitiesToConsider(newPreferencesDTO.getModalitiesToConsider()); + routingPreferencesRepository.save(preferences); + } + + /** + * Get routing preferences for a specific user. + */ + public RoutingPreferencesDTO getUserRoutingPreferences(Long userId) { + Optional optionalPreferences = routingPreferencesRepository.findByUserId(userId); + + RoutingPreferencesDTO preferencesDTO; + if (optionalPreferences.isEmpty()) { + // TODO after testing phase this should throw an exception or create new preferences for the user + preferencesDTO = routingPreferencesMapper.toRoutingPreferencesDTO(RoutingPreferences.getDefaultPreferences()); + } else { + preferencesDTO = routingPreferencesMapper.toRoutingPreferencesDTO(optionalPreferences.get()); + } + return preferencesDTO; + } + + /** + * Gets routing preferences for the current user, if user is logged in returns his preferences, if not logged in returns default preferences. + */ + public RoutingPreferencesDTO getRoutingPreferencesForCurrentUser() { + if (currentUserService.isAuthenticated()) { + var currentUser = currentUserService.get(); + return getUserRoutingPreferences(currentUser.getId()); + } else { + return routingPreferencesMapper.toRoutingPreferencesDTO(RoutingPreferences.getDefaultPreferences()); + } + } +} diff --git a/src/main/java/SuMoC/backend/routing/services/RoutingService.java b/src/main/java/SuMoC/backend/routing/services/RoutingService.java index 7d67d0d..a8c400c 100644 --- a/src/main/java/SuMoC/backend/routing/services/RoutingService.java +++ b/src/main/java/SuMoC/backend/routing/services/RoutingService.java @@ -142,6 +142,38 @@ public class RoutingService { return routes; } + public RouteDTO determineBestAlternativeRouteForRegularTrip(RoutingAlternativeRequestDTO requestDTO) { + assert requestDTO.getRoutingPreferencesDTO() != null; + + // TODO for now we use adHocRoutingProperties here, in the future we might want to have separate properties for regular trip alternatives + List routes = getPossibleAlternativeRoutes(requestDTO); + routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, adHocRoutingProperties); + if (requestDTO.getRoutingPreferencesDTO().isConsiderWeatherConditions()) { + routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties); + } + + RouteDTO bestRoute = null; + // if users wants physical activity, we pick the fastest physical activity route, if any + if (requestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity()) { + bestRoute = routes.stream() + .filter(RouteDTO::isPhysicalActivity) + .min((r1, r2) -> Long.compare( + r1.getDurationSeconds(), + r2.getDurationSeconds() + )).orElse(null); + if (bestRoute != null) { + return bestRoute; + } + } + // else we pick the fastest route overall + bestRoute = routes.stream() + .min((r1, r2) -> Long.compare( + r1.getDurationSeconds(), + r2.getDurationSeconds() + )).orElse(null); + return bestRoute; + } + /** * Returns possible alternative routes for the request - no sanity filtering regarding travel times etc. is applied. */ diff --git a/src/main/java/SuMoC/backend/scheduling/ScheduledTasks.java b/src/main/java/SuMoC/backend/scheduling/ScheduledTasks.java index df949d5..09ff888 100644 --- a/src/main/java/SuMoC/backend/scheduling/ScheduledTasks.java +++ b/src/main/java/SuMoC/backend/scheduling/ScheduledTasks.java @@ -1,6 +1,9 @@ package SuMoC.backend.scheduling; +import SuMoC.backend.notification.services.NotificationWorker; +import SuMoC.backend.suggestion.services.RegularTripSuggestionService; import SuMoC.backend.trend.services.StatTableUpdateService; +import SuMoC.backend.trend.services.TrendNotificationService; import lombok.RequiredArgsConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -19,14 +22,63 @@ public class ScheduledTasks { private final StatTableUpdateService statTableUpdateService; - @Scheduled(cron = "#{@schedulingProperties.calculateWeeklyMobilityStats}") - public void scheduleCalculateWeeklyMobilityStats() { + private final TrendNotificationService trendNotificationService; + + private final RegularTripSuggestionService regularTripSuggestionService; + + private final NotificationWorker notificationWorker; + + /** + * Calculate weekly mobility stats for all users and generate corresponding notifications. + */ + @Scheduled(cron = "#{@schedulingProperties.notifyWeeklyMobilityStats}") + public void scheduleNotifyWeeklyMobilityStats() { logger.info("Scheduled task triggered: calculateWeeklyMobilityStatsForAllUsers"); try { - LocalDate dayOfLastWeek = LocalDate.now().minusDays(7); + LocalDate dayOfLastWeek = LocalDate.now().minusWeeks(1); statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(dayOfLastWeek); + trendNotificationService.detectAndNotifyTrends(dayOfLastWeek.getYear(), dayOfLastWeek.get(java.time.temporal.IsoFields.WEEK_OF_WEEK_BASED_YEAR)); } catch (Exception e) { logger.error("Error calculating weekly mobility stats.", e); } } + + /** + * Run the notification worker to process pending notifications. + */ + @Scheduled(cron = "#{@schedulingProperties.runNotificationWorker}") + public void scheduleRunNotificationWorker() { + logger.info("Scheduled task triggered: runNotificationWorker"); + try { + notificationWorker.run(); + } catch (Exception e) { + logger.error("Error running notification worker.", e); + } + } + + /** + * Clean up old notifications from the database. + */ + @Scheduled(cron = "#{@schedulingProperties.cleanUpOldNotifications}") + public void scheduleCleanUpOldNotifications() { + logger.info("Scheduled task triggered: cleanUpOldNotifications"); + try { + notificationWorker.cleanUpOldNotifications(); + } catch (Exception e) { + logger.error("Error cleaning up old notifications.", e); + } + } + + /** + * Detect regular routes for all users and plan notifications for better alternatives. + */ + @Scheduled(cron = "#{@schedulingProperties.notifyRegularRouteAlternatives}") + public void scheduleNotifyRegularRouteAlternatives() { + logger.info("Scheduled task triggered: notifyRegularRouteAlternatives"); + try { + regularTripSuggestionService.detectAndNotifyRegularTripsForTodaysDayOfWeek(); + } catch (Exception e) { + logger.error("Error notifying regular route alternatives.", e); + } + } } diff --git a/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java b/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java index f6103e7..cce5861 100644 --- a/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java +++ b/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java @@ -11,5 +11,8 @@ import org.springframework.stereotype.Component; @Setter public class SchedulingProperties { private int poolSize = 5; - private String calculateWeeklyMobilityStats = "1 30 0 * * 1"; // Once per week + private String notifyWeeklyMobilityStats = "1 30 0 * * 1"; // Once per week + private String runNotificationWorker = "0 * * * * *"; // Every minute + private String cleanUpOldNotifications = "0 0 3 * * *"; // Daily at 3 AM + private String notifyRegularRouteAlternatives = "0 0 4 * * * " ; // Daily at 4 AM } diff --git a/src/main/java/SuMoC/backend/security/SecurityConfiguration.java b/src/main/java/SuMoC/backend/security/SecurityConfiguration.java index c5b45f1..efd98ae 100644 --- a/src/main/java/SuMoC/backend/security/SecurityConfiguration.java +++ b/src/main/java/SuMoC/backend/security/SecurityConfiguration.java @@ -98,11 +98,13 @@ public class SecurityConfiguration { auth.requestMatchers("/friendship/**").hasAnyRole("ADMIN", "USER"); auth.requestMatchers("/trip/**").hasAnyRole("USER", "ADMIN"); auth.requestMatchers("/geocoding/**").hasAnyRole("USER", "ADMIN"); + auth.requestMatchers("/routing/preferences/**").hasAnyRole("USER", "ADMIN"); // gamification auth.requestMatchers("/badges/**").hasAnyRole("ADMIN", "USER"); auth.requestMatchers("/leaderboard/**").hasAnyRole("ADMIN", "USER"); + auth.requestMatchers("/notifications/**").hasAnyRole("USER", "ADMIN"); //auth.requestMatchers("/error").permitAll(); auth.anyRequest().authenticated(); diff --git a/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java b/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java index 54b0e6e..1e58d73 100644 --- a/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java +++ b/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java @@ -1,7 +1,12 @@ package SuMoC.backend.seed.user; +import SuMoC.backend.dev.DevProperties; +import SuMoC.backend.notification.enums.NotificationProvider; +import SuMoC.backend.notification.services.NotificationTokenService; import SuMoC.backend.security.dtos.UserRegistrationDTO; import SuMoC.backend.security.services.AuthenticationService; +import SuMoC.backend.user.models.User; +import SuMoC.backend.user.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Profile; @@ -15,26 +20,47 @@ public class DevUserSeeder implements CommandLineRunner { private final AuthenticationService authenticationService; + private final NotificationTokenService notificationTokenService; + + private final UserRepository userRepository; + + private final DevProperties devProperties; + @Autowired - public DevUserSeeder(AuthenticationService authenticationService) { + public DevUserSeeder(AuthenticationService authenticationService, NotificationTokenService notificationTokenService, UserRepository userRepository, DevProperties devProperties) { this.authenticationService = authenticationService; + this.notificationTokenService = notificationTokenService; + this.userRepository = userRepository; + this.devProperties = devProperties; } @Override public void run(String... args) throws Exception { - UserRegistrationDTO user1 = UserRegistrationDTO.builder() + UserRegistrationDTO user1dto = UserRegistrationDTO.builder() .email("user1@email.com") .publicName("Nutzer 1 Public") .privateName("Nutzer 1 Privat") .password("password1") .build(); - authenticationService.registerUser(user1); - UserRegistrationDTO user2 = UserRegistrationDTO.builder() + authenticationService.registerUser(user1dto); + User user1 = userRepository.findByEmail("user1@email.com").orElseThrow(); + notificationTokenService.registerDeviceToken( + user1, + NotificationProvider.FIREBASE, + devProperties.getFcmKey() + ); + UserRegistrationDTO user2dto = UserRegistrationDTO.builder() .email("user2@email.com") .publicName("Nutzer 2 Public") .privateName("Nutzer 2 Privat") .password("password2") .build(); - authenticationService.registerUser(user2); + authenticationService.registerUser(user2dto); + User user2 = userRepository.findByEmail("user2@email.com").orElseThrow(); + notificationTokenService.registerDeviceToken( + user2, + NotificationProvider.FIREBASE, + devProperties.getFcmKey() + ); } } diff --git a/src/main/java/SuMoC/backend/suggestion/config/AdHocSuggestionProperties.java b/src/main/java/SuMoC/backend/suggestion/config/AdHocSuggestionProperties.java index c7be2f8..0e849b8 100644 --- a/src/main/java/SuMoC/backend/suggestion/config/AdHocSuggestionProperties.java +++ b/src/main/java/SuMoC/backend/suggestion/config/AdHocSuggestionProperties.java @@ -7,7 +7,7 @@ import org.springframework.stereotype.Component; @Data @Component -@ConfigurationProperties(prefix = "adhocsuggestion") +@ConfigurationProperties(prefix = "sumoc.adhocsuggestion") public class AdHocSuggestionProperties { /** diff --git a/src/main/java/SuMoC/backend/suggestion/config/RegularTripSuggestionProperties.java b/src/main/java/SuMoC/backend/suggestion/config/RegularTripSuggestionProperties.java new file mode 100644 index 0000000..5aed4f2 --- /dev/null +++ b/src/main/java/SuMoC/backend/suggestion/config/RegularTripSuggestionProperties.java @@ -0,0 +1,17 @@ +package SuMoC.backend.suggestion.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Data +@Component +@ConfigurationProperties(prefix = "sumoc.regulartripsuggestion") +public class RegularTripSuggestionProperties { + + /** + * Number of minutes a notification is send before the regular trip is usually started. + * We keep it relatively short since regular trips have a time window. + */ + private Integer notifyBeforeMinutes = 15; +} diff --git a/src/main/java/SuMoC/backend/suggestion/services/AdHocSuggestionService.java b/src/main/java/SuMoC/backend/suggestion/services/AdHocSuggestionService.java index f6de03c..be623a8 100644 --- a/src/main/java/SuMoC/backend/suggestion/services/AdHocSuggestionService.java +++ b/src/main/java/SuMoC/backend/suggestion/services/AdHocSuggestionService.java @@ -1,16 +1,23 @@ package SuMoC.backend.suggestion.services; +import SuMoC.backend.notification.enums.NotificationType; +import SuMoC.backend.notification.services.NotificationSchedulerService; +import SuMoC.backend.routing.dtos.RouteDTO; import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO; import SuMoC.backend.routing.dtos.RoutingPreferencesDTO; +import SuMoC.backend.routing.services.RoutingPreferencesService; import SuMoC.backend.routing.services.RoutingService; import SuMoC.backend.suggestion.config.AdHocSuggestionProperties; +import SuMoC.backend.trip.Modality; import SuMoC.backend.trip.models.Trip; import lombok.RequiredArgsConstructor; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import java.time.Instant; +import java.time.LocalTime; +import java.util.List; @Service @RequiredArgsConstructor @@ -18,8 +25,12 @@ public class AdHocSuggestionService { private final RoutingService routingService; + private final RoutingPreferencesService routingPreferencesService; + private final AdHocSuggestionProperties adHocSuggestionProperties; + private final NotificationSchedulerService notificationSchedulerService; + /** * Receives a trip a user has just uploaded, if it is a recent trip and there is a more sustainable alternative, * schedules a notification to push to the user. @@ -27,14 +38,52 @@ public class AdHocSuggestionService { @Async public void checkNewTripForNotifiedAlternativeSuggestion(Trip newTrip) { if (!isRecentTrip(newTrip)) return; + if (!(newTrip.getMainModality().equals(Modality.CAR) || newTrip.getMainModality().equals(Modality.MOTORCYCLE) || newTrip.getMainModality().equals(Modality.TAXI))) { + return; // only suggest alternatives for trips mainly done by car, motorcycle or taxi + } var viableAlternatives = routingService.determineAlternativeRoutesAdHoc(alternativeRequestFromTrip(newTrip)); - // check if there are viable alternative routings - // if yes, generate notification - // TODO notification generator - // schedule send of notification - // TODO sending of notification + if (!viableAlternatives.isEmpty()) { + // Since notification bodies have a size limit, we only send the best alternative + RoutingPreferencesDTO preferencesDTO = routingPreferencesService.getUserRoutingPreferences(newTrip.getUser().getId()); + List bestAlternatives = pickBestAlternatives(viableAlternatives, preferencesDTO); + + notificationSchedulerService.schedule( + newTrip.getUser().getId(), + bestAlternatives, + NotificationType.ADHOC_ALTERNATIVE, + LocalTime.now() + ); + } + } + + /** + * Picks the best alternative route, if user does not prefer physical activity, picks the fastes route. + * If user prefers physical activity, picks fastest of all modalities plus fastest physical activity only route. + */ + private List pickBestAlternatives(List routes, RoutingPreferencesDTO preferences) { + List bestAlternatives = new java.util.ArrayList<>(); + if (preferences.isPreferPhysicalActivity()) { + // find fastest physical activity only route + routes.stream() + .filter(RouteDTO::isPhysicalActivity) + .min((r1, r2) -> Long.compare( + r1.getDurationSeconds(), + r2.getDurationSeconds() + )).ifPresent(bestAlternatives::add); + } + // find fastest route overall + routes.stream() + .min((r1, r2) -> Long.compare( + r1.getDurationSeconds(), + r2.getDurationSeconds() + )).ifPresent(fastestRoute -> { + if (!bestAlternatives.contains(fastestRoute)) { + bestAlternatives.add(fastestRoute); + } + }); + return bestAlternatives; } private boolean isRecentTrip(Trip trip) { @@ -43,8 +92,7 @@ public class AdHocSuggestionService { } private RoutingAlternativeRequestDTO alternativeRequestFromTrip(Trip trip) { - // TODO for now we assume the preferences here, it would be better if we store these per user - var preferences = new RoutingPreferencesDTO(); + var preferences = routingPreferencesService.getUserRoutingPreferences(trip.getUser().getId()); return RoutingAlternativeRequestDTO.builder() .originLat(trip.getStartLatitude()) .originLon(trip.getStartLongitude()) diff --git a/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java b/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java new file mode 100644 index 0000000..3ffc48b --- /dev/null +++ b/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java @@ -0,0 +1,92 @@ +package SuMoC.backend.suggestion.services; + +import SuMoC.backend.h3.H3Service; +import SuMoC.backend.notification.enums.NotificationType; +import SuMoC.backend.notification.services.NotificationSchedulerService; +import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO; +import SuMoC.backend.regulartrip.services.RegularTripDetectionService; +import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO; +import SuMoC.backend.routing.dtos.RoutingPreferencesDTO; +import SuMoC.backend.routing.services.RoutingPreferencesService; +import SuMoC.backend.routing.services.RoutingService; +import SuMoC.backend.suggestion.config.RegularTripSuggestionProperties; +import com.uber.h3core.util.LatLng; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.time.DayOfWeek; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.HashMap; +import java.util.List; + +@Service +@RequiredArgsConstructor +public class RegularTripSuggestionService { + + private final RoutingService routingService; + + private final RoutingPreferencesService routingPreferencesService; + + private final RegularTripSuggestionProperties properties; + + private final NotificationSchedulerService notificationSchedulerService; + + private final RegularTripDetectionService regularTripDetectionService; + + private final H3Service h3Service; + + public void detectAndNotifyRegularTripsForTodaysDayOfWeek() { + // detect + DayOfWeek dayOfWeek = LocalDateTime.now().getDayOfWeek(); + var detectedRegularTripsByUser = regularTripDetectionService.detectRegularCarTripsByUserForDayOfWeek(dayOfWeek); + + // notify + checkAlternativesAndNotify(detectedRegularTripsByUser); + } + + public void checkAlternativesAndNotify(HashMap> detectedRegularTripsByUser) { + for (Long userId : detectedRegularTripsByUser.keySet()) { + var detectedRegularTrips = detectedRegularTripsByUser.get(userId); + RoutingPreferencesDTO preferencesDTO = routingPreferencesService.getUserRoutingPreferences(userId); + + // For each detected regular trip, determine alternatives and notify the user if applicable + for (var detectedRegularTrip : detectedRegularTrips) { + var alternativeRequest = createAlternativeRequest(detectedRegularTrip); + alternativeRequest.setRoutingPreferencesDTO(preferencesDTO); + + var bestAlternative = routingService.determineBestAlternativeRouteForRegularTrip(alternativeRequest); + // if present, schedule notification + if (bestAlternative != null) { + notificationSchedulerService.schedule( + userId, + bestAlternative, + NotificationType.REGULAR_TRIP_ALTERNATIVE, + detectedRegularTrip.getArrivalWindowEnd().minusMinutes(properties.getNotifyBeforeMinutes()) + ); + } + } + } + } + + private RoutingAlternativeRequestDTO createAlternativeRequest(DetectedRegularTripDTO trip) { + LatLng origin = h3Service.cellToLatLng(trip.getStartH3Center()); + LatLng destination = h3Service.cellToLatLng(trip.getEndH3Center()); + // we plan the trip to arrive at the average arrival time of the regular trip + Instant arrivalTime = LocalDateTime.now() + .with(trip.getAverageArrivalTime()) + .atZone(ZoneId.systemDefault()) + .toInstant(); + Instant departureTime = arrivalTime.minusSeconds(trip.getAverageDurationMinutes() * 60L); + + return RoutingAlternativeRequestDTO.builder() + .originLat(origin.lat) + .originLon(origin.lng) + .destinationLat(destination.lat) + .destinationLon(destination.lng) + .arrivalTime(arrivalTime) + .departureTime(departureTime) + .build(); + } +} diff --git a/src/main/java/SuMoC/backend/trend/TrendDetection.java b/src/main/java/SuMoC/backend/trend/TrendDetection.java deleted file mode 100644 index b715afd..0000000 --- a/src/main/java/SuMoC/backend/trend/TrendDetection.java +++ /dev/null @@ -1,37 +0,0 @@ -package SuMoC.backend.trend; - -import SuMoC.backend.trend.enums.*; -import SuMoC.backend.user.models.User; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; - -@Data -@Builder -@AllArgsConstructor -public class TrendDetection { - private User user; - private TrendTimespan timespan; - private TrendType type; - private StatAttribute attribute; - private DeltaType deltaType; - private double changeValue; - - public TrendConnotation getTrendConnotation() { - if (this.type == TrendType.INCREASING) { - return switch (attribute) { - case CAR_DISTANCE -> TrendConnotation.NEGATIVE; - default -> TrendConnotation.NEUTRAL; - }; - } else if (type == TrendType.DECREASING) { - return switch (attribute) { - case CAR_DISTANCE -> TrendConnotation.POSITIVE; - default -> TrendConnotation.NEUTRAL; - }; - } else { - return TrendConnotation.NEUTRAL; - } - } -} - - diff --git a/src/main/java/SuMoC/backend/trend/config/TrendDetectionProperties.java b/src/main/java/SuMoC/backend/trend/config/TrendProperties.java similarity index 54% rename from src/main/java/SuMoC/backend/trend/config/TrendDetectionProperties.java rename to src/main/java/SuMoC/backend/trend/config/TrendProperties.java index 4930a6d..1595da4 100644 --- a/src/main/java/SuMoC/backend/trend/config/TrendDetectionProperties.java +++ b/src/main/java/SuMoC/backend/trend/config/TrendProperties.java @@ -4,10 +4,12 @@ import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; +import java.time.LocalTime; + @Data @Component -@ConfigurationProperties(prefix = "trenddetection") -public class TrendDetectionProperties { +@ConfigurationProperties(prefix = "sumoc.trenddetection") +public class TrendProperties { /** * Minimum percentage change to detect a positive trend (e.g., 25.0 for 25%) @@ -18,4 +20,10 @@ public class TrendDetectionProperties { * Minimum percentage change to detect a negative trend (e.g., -25.0 for -25%) */ private double negativeThreshold = -25.0; + + /** + * Time of day from which on trend notifications might be sent. + * Useful since we dont want to inform about trend changes in the middle of night when calculating jobs might run. + */ + private LocalTime earliestTrendNotificationTimeOfDay = LocalTime.of(12, 0); } diff --git a/src/main/java/SuMoC/backend/trend/dto/TrendDetectionDTO.java b/src/main/java/SuMoC/backend/trend/dto/TrendDetectionDTO.java new file mode 100644 index 0000000..e05b6b3 --- /dev/null +++ b/src/main/java/SuMoC/backend/trend/dto/TrendDetectionDTO.java @@ -0,0 +1,50 @@ +package SuMoC.backend.trend.dto; + +import SuMoC.backend.notification.interfaces.Notifieable; +import SuMoC.backend.trend.enums.*; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +public class TrendDetectionDTO implements Notifieable { + private Long userId; + private TrendTimespan timespan; + private TrendType type; + private StatAttribute attribute; + private DeltaType deltaType; + private double changeValue; + private TrendConnotation trendConnotation; + + public TrendDetectionDTO(Long userId, TrendTimespan timespan, TrendType type, StatAttribute attribute, DeltaType deltaType, double changeValue) { + this.userId = userId; + this.timespan = timespan; + this.type = type; + this.attribute = attribute; + this.deltaType = deltaType; + this.changeValue = changeValue; + this.trendConnotation = getTrendConnotation(); + } + + public static TrendDetectionDTO mockTrendDetectionDTO() { + return new TrendDetectionDTO(null, TrendTimespan.WEEKLY, TrendType.INCREASING, StatAttribute.CAR_DISTANCE, DeltaType.ABSOLUTE, 15.0); + } + + public TrendConnotation getTrendConnotation() { + if (this.type == TrendType.INCREASING) { + return switch (attribute) { + case CAR_DISTANCE -> TrendConnotation.NEGATIVE; + default -> TrendConnotation.NEUTRAL; + }; + } else if (type == TrendType.DECREASING) { + return switch (attribute) { + case CAR_DISTANCE -> TrendConnotation.POSITIVE; + default -> TrendConnotation.NEUTRAL; + }; + } else { + return TrendConnotation.NEUTRAL; + } + } +} + + diff --git a/src/main/java/SuMoC/backend/trend/services/TrendDetectorService.java b/src/main/java/SuMoC/backend/trend/services/TrendDetectorService.java index 766bab6..4b777e7 100644 --- a/src/main/java/SuMoC/backend/trend/services/TrendDetectorService.java +++ b/src/main/java/SuMoC/backend/trend/services/TrendDetectorService.java @@ -1,8 +1,8 @@ package SuMoC.backend.trend.services; -import SuMoC.backend.trend.TrendDetection; import SuMoC.backend.trend.WeeklyMobilityStatsRepository; -import SuMoC.backend.trend.config.TrendDetectionProperties; +import SuMoC.backend.trend.config.TrendProperties; +import SuMoC.backend.trend.dto.TrendDetectionDTO; import SuMoC.backend.trend.enums.DeltaType; import SuMoC.backend.trend.enums.StatAttribute; import SuMoC.backend.trend.enums.TrendTimespan; @@ -22,9 +22,9 @@ public class TrendDetectorService { private final WeeklyMobilityStatsRepository weeklyMobilityStatsRepository; - private final TrendDetectionProperties trendDetectionProperties; + private final TrendProperties trendProperties; - public List detectWeeklyTrends(Integer year, Integer weekNumber, StatAttribute attribute) { + public List detectWeeklyTrends(Integer year, Integer weekNumber, StatAttribute attribute) { // Fetch stats for current and previous week List previousWeekStatsList; if (weekNumber > 1) { @@ -43,7 +43,7 @@ public class TrendDetectorService { .collect(Collectors.toMap(stats -> stats.getUser().getId(), stats -> stats)); // Detect trends for provided attribute - List detectedTrends = new ArrayList<>(); + List detectedTrends = new ArrayList<>(); for (Map.Entry entry : currentWeekStats.entrySet()) { Long userId = entry.getKey(); WeeklyMobilityStats currentStats = entry.getValue(); @@ -56,18 +56,18 @@ public class TrendDetectorService { if (previousValue != 0) { double percentageChange = ((currentValue - previousValue) / previousValue) * 100.0; - if (percentageChange >= trendDetectionProperties.getPositiveThreshold()) { - detectedTrends.add(new TrendDetection( - currentStats.getUser(), + if (percentageChange >= trendProperties.getPositiveThreshold()) { + detectedTrends.add(new TrendDetectionDTO( + currentStats.getUser().getId(), TrendTimespan.WEEKLY, TrendType.INCREASING, StatAttribute.CAR_DISTANCE, DeltaType.PERCENTAGE, percentageChange )); - } else if (percentageChange <= trendDetectionProperties.getNegativeThreshold()) { - detectedTrends.add(new TrendDetection( - previousStats.getUser(), + } else if (percentageChange <= trendProperties.getNegativeThreshold()) { + detectedTrends.add(new TrendDetectionDTO( + previousStats.getUser().getId(), TrendTimespan.WEEKLY, TrendType.DECREASING, StatAttribute.CAR_DISTANCE, diff --git a/src/main/java/SuMoC/backend/trend/services/TrendMessageGenerator.java b/src/main/java/SuMoC/backend/trend/services/TrendMessageGenerator.java deleted file mode 100644 index 59754b7..0000000 --- a/src/main/java/SuMoC/backend/trend/services/TrendMessageGenerator.java +++ /dev/null @@ -1,8 +0,0 @@ -package SuMoC.backend.trend.services; - - -import org.springframework.stereotype.Component; - -@Component -public class TrendMessageGenerator { -} diff --git a/src/main/java/SuMoC/backend/trend/services/TrendNotificationService.java b/src/main/java/SuMoC/backend/trend/services/TrendNotificationService.java new file mode 100644 index 0000000..327a35e --- /dev/null +++ b/src/main/java/SuMoC/backend/trend/services/TrendNotificationService.java @@ -0,0 +1,31 @@ +package SuMoC.backend.trend.services; + +import SuMoC.backend.notification.enums.NotificationType; +import SuMoC.backend.notification.services.NotificationSchedulerService; +import SuMoC.backend.trend.config.TrendProperties; +import SuMoC.backend.trend.enums.StatAttribute; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; + +@Service +@RequiredArgsConstructor +public class TrendNotificationService { + + private final TrendDetectorService trendDetectorService; + + private final NotificationSchedulerService notificationSchedulerService; + + private final TrendProperties trendProperties; + + /** + * Detects trends for the given year and week number and sends notifications to users. + */ + public void detectAndNotifyTrends(int year, int weekNumber) { + // TODO for now we only consider CAR_DISTANCE, but this can be extended later + var detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE); + // we create a new list so the java type system is happy + notificationSchedulerService.scheduleAll(new ArrayList<>(detectedTrends), NotificationType.TREND, trendProperties.getEarliestTrendNotificationTimeOfDay()); + } +} diff --git a/src/main/java/SuMoC/backend/trip/TripRepository.java b/src/main/java/SuMoC/backend/trip/TripRepository.java index 4b8c96a..4251b1b 100644 --- a/src/main/java/SuMoC/backend/trip/TripRepository.java +++ b/src/main/java/SuMoC/backend/trip/TripRepository.java @@ -1,11 +1,13 @@ package SuMoC.backend.trip; +import SuMoC.backend.common.converter.DayOfWeekConverter; import SuMoC.backend.trip.models.Trip; import SuMoC.backend.user.models.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; +import java.time.DayOfWeek; import java.time.Instant; import java.time.LocalDateTime; import java.util.List; @@ -22,9 +24,20 @@ public interface TripRepository extends JpaRepository { "WHERE trip.invalidated = false AND trip.startTime >= :start AND trip.startTime < :end") List findValidTripsInWeek(@Param("start") LocalDateTime start, @Param("end") LocalDateTime end); - @Query("SELECT trip FROM Trip trip " + - "JOIN FETCH trip.user " + - "JOIN FETCH trip.tripSegments " + - "WHERE trip.invalidated = false AND trip.startTime >= :fromDate AND trip.mainModality = :modality") - List findAllValidFromDateWithMainModality(Instant fromDate, Modality modality); + default List findAllValidFromDateWithMainModalityOnCertainWeekday( + Instant fromDate, + Modality modality, + DayOfWeek dayOfWeek + ) { + DayOfWeekConverter converter = new DayOfWeekConverter(); + return findAllValidFromDateWithMainModalityOnCertainWeekdayInt( + fromDate, + modality, + converter.convertToDatabaseColumn(dayOfWeek) + ); + } + + @Query("SELECT t FROM Trip t WHERE t.invalidated = false AND t.startTime >= :fromDate AND t.mainModality = :modality AND FUNCTION('day_of_week', t.startTime) = :dayOfWeek") + List findAllValidFromDateWithMainModalityOnCertainWeekdayInt(Instant fromDate, Modality modality, int dayOfWeek); + } diff --git a/src/main/java/SuMoC/backend/trip/dtos/RegularTripDetectionDTO.java b/src/main/java/SuMoC/backend/trip/dtos/RegularTripDetectionDTO.java index 0ce1ada..d469964 100644 --- a/src/main/java/SuMoC/backend/trip/dtos/RegularTripDetectionDTO.java +++ b/src/main/java/SuMoC/backend/trip/dtos/RegularTripDetectionDTO.java @@ -3,6 +3,7 @@ package SuMoC.backend.trip.dtos; import SuMoC.backend.trip.Modality; import lombok.*; +import java.time.DayOfWeek; import java.time.Instant; import java.util.List; @@ -25,7 +26,11 @@ public class RegularTripDetectionDTO { private List startH3CellKRingNeighboors; private List endH3CellKRingNeighboors; - public int getDayOfTheWeek() { - return startTime.atZone(java.time.ZoneId.systemDefault()).getDayOfWeek().getValue(); + public DayOfWeek getDayOfTheWeek() { + return startTime.atZone(java.time.ZoneId.systemDefault()).getDayOfWeek(); + } + + public int getDurationMinutes() { + return (int) java.time.Duration.between(startTime, endTime).toMinutes(); } } diff --git a/src/main/java/SuMoC/backend/user/controller/FriendshipController.java b/src/main/java/SuMoC/backend/user/controller/FriendshipController.java index 465efb5..127110b 100644 --- a/src/main/java/SuMoC/backend/user/controller/FriendshipController.java +++ b/src/main/java/SuMoC/backend/user/controller/FriendshipController.java @@ -66,6 +66,16 @@ public class FriendshipController { return ResponseEntity.ok().build(); } + @Operation(summary = "Request a friendship with another user by friend code.", description = "Sends a friendship request to another user identified by their friend code from the logged in user.") + @PostMapping("/request/by-friendcode/{friendCode}") + public ResponseEntity requestFriendshipByFriendcode(@PathVariable String friendCode) { + User user = getAuthenticatedUser(); + User requestedFriend = userRepository.findByFriendCode(friendCode).orElseThrow(); + checkSelfAction(user.getId(), requestedFriend.getId()); + friendshipService.requestFriendship(user, requestedFriend.getId()); + return ResponseEntity.ok().build(); + } + @Operation(summary = "Accept a friendship request.", description = "Accepts a pending friendship request for the logged in user from user with friendId.") @PostMapping("/accept/{friendId}") public ResponseEntity acceptFriendship(@PathVariable Long friendId) { diff --git a/src/main/java/SuMoC/backend/user/models/User.java b/src/main/java/SuMoC/backend/user/models/User.java index 1e36955..0865f11 100644 --- a/src/main/java/SuMoC/backend/user/models/User.java +++ b/src/main/java/SuMoC/backend/user/models/User.java @@ -1,13 +1,17 @@ package SuMoC.backend.user.models; import SuMoC.backend.gamification.badges.models.UserBadge; +import SuMoC.backend.notification.models.NotificationToken; +import SuMoC.backend.routing.models.RoutingPreferences; import SuMoC.backend.trip.models.Trip; import SuMoC.backend.user.enums.RoleName; import SuMoC.backend.user.enums.VisibilityPrivacy; import SuMoC.backend.user.stats.StatsList; import jakarta.persistence.*; +import lombok.Setter; -import java.util.*; +import java.util.HashSet; +import java.util.Set; @Entity @Table(name = "users") @@ -47,19 +51,29 @@ public class User { @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true) private Set friendships = new HashSet<>(); + @Setter @ElementCollection(targetClass = RoleName.class, fetch = FetchType.EAGER) @Enumerated(EnumType.STRING) @CollectionTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id")) @Column(name = "role") private Set roles; + @OneToOne + @JoinColumn(name = "id", referencedColumnName = "user_id") + private NotificationToken notificationToken; + @OneToMany(mappedBy = "user", cascade = CascadeType.ALL) private Set badges = new HashSet<>(); @OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true) private StatsList statsList; - public User() {} + @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true) + @JoinColumn(name = "routing_preferences_id", unique = true) + private RoutingPreferences routingPreferences; + + public User() { + } // public User(Long id, String publicName, String privateName, String email, String password, VisibilityPrivacy visibilityPrivacy, String friendCode, Set trips, Set friendships, Set roles) { // this.id = id; @@ -81,6 +95,7 @@ public class User { this.password = password; this.visibilityPrivacy = VisibilityPrivacy.NONE; this.friendCode = java.util.UUID.randomUUID().toString(); // generate unique friend code + this.routingPreferences = RoutingPreferences.getDefaultPreferences(); // Init with default routing preferences this.roles = new HashSet<>(); this.roles.add(RoleName.USER); this.statsList = new StatsList(this); @@ -169,15 +184,35 @@ public class User { return roles; } - public void setRoles(Set roles) { - this.roles = roles; + public Set getBadges() { + return badges; } - public Set getBadges() { return badges; } + public void setBadges(Set badges) { + this.badges = badges; + } - public void setBadges(Set badges) { this.badges = badges; } + public StatsList getStats() { + return statsList; + } - public StatsList getStats() { return statsList;} + public void setStats(StatsList statsList) { + this.statsList = statsList; + } - public void setStats(StatsList statsList) { this.statsList = statsList; } + public NotificationToken getNotificationToken() { + return notificationToken; + } + + public void setNotificationToken(NotificationToken notificationToken) { + this.notificationToken = notificationToken; + } + + public RoutingPreferences getRoutingPreferences() { + return routingPreferences; + } + + public void setRoutingPreferences(RoutingPreferences routingPreferences) { + this.routingPreferences = routingPreferences; + } } diff --git a/src/main/java/SuMoC/backend/user/repository/UserRepository.java b/src/main/java/SuMoC/backend/user/repository/UserRepository.java index 3de9e29..a932d29 100644 --- a/src/main/java/SuMoC/backend/user/repository/UserRepository.java +++ b/src/main/java/SuMoC/backend/user/repository/UserRepository.java @@ -10,6 +10,8 @@ public interface UserRepository extends JpaRepository { Optional findByEmail(String email); + Optional findByFriendCode(String friendCode); + boolean existsByPublicName(String username); boolean existsByEmail(String email); diff --git a/src/main/java/SuMoC/backend/user/service/CurrentUserService.java b/src/main/java/SuMoC/backend/user/service/CurrentUserService.java index e8e5554..c4a6f19 100644 --- a/src/main/java/SuMoC/backend/user/service/CurrentUserService.java +++ b/src/main/java/SuMoC/backend/user/service/CurrentUserService.java @@ -31,4 +31,9 @@ public class CurrentUserService { HttpStatus.NOT_FOUND, "Der Nutzer existiert nicht")); } + + public boolean isAuthenticated() { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + return auth != null && auth.isAuthenticated(); + } } \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 3566bcf..808e46c 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -11,15 +11,16 @@ springdoc.api-docs.path=/v3/api-docs springdoc.swagger-ui.path=/swagger-ui.html spring.profiles.active=dev spring.jackson.serialization.write-dates-as-timestamps=false -# Disabled for development - TODO set reasonable rhythm -sumoc.scheduling.calculate-trend-table-cron=- +# Rhythm settings for scheduled tasks +sumoc.scheduling.run-notification-worker=*/15 * * * * * +sumoc.scheduling.notify-weekly-mobility-stats=1 30 0 * * 1 +sumoc.scheduling.clean-up-old-notifications=0 0 3 * * * +sumoc.scheduling.notify-regular-route-alternatives=0 0 4 * * * # Trend detection settings -trenddetection.negative-threshold=-25.0 -trenddetection.positive-threshold=25.0 -# Regular trip detection settings -#regulartripdetection.detection-algorithm=iterative +sumoc.trenddetection.positive-threshold=-25.0 +sumoc.trenddetection.negative-threshold=-25.0 # FireBase -firebase.config.enabled=false +firebase.config.enabled=true firebase.config.service-account=classpath:firebase-private-key.json # Base URL to external services carta.base-url=https://www.innamoruhr.de/c2 @@ -27,4 +28,6 @@ carta.base-url=https://www.innamoruhr.de/c2 geocoding.provider=carta geocoding.nominatim.base-url=http://localhost:6666 geocoding.carta.base-url=https://mobydex.locoslab.com/carta -meteo.base-url=https://api.open-meteo.com/v1 \ No newline at end of file +meteo.base-url=https://api.open-meteo.com/v1 +# Dev debug settings +sumoc.dev.fcm-key=dmydW4a_RjKCDjcBLZ9Kl8:APA91bFjBIjw8NcjeMIsNkfPuW9jhMlK3n_LHoG5UBW0E_76nTp1yV6jkdiBIvle7Txj_mLY3W9e9gy_op6YWyxJksqZrJFgapruCdBdg9ACYDJAANGTWJk \ No newline at end of file diff --git a/src/test/java/SuMoC/backend/Factories/RegularTripDetectionDTOFactory.java b/src/test/java/SuMoC/backend/Factories/RegularTripDetectionDTOFactory.java new file mode 100644 index 0000000..7b2ae51 --- /dev/null +++ b/src/test/java/SuMoC/backend/Factories/RegularTripDetectionDTOFactory.java @@ -0,0 +1,142 @@ +package SuMoC.backend.Factories; + +import SuMoC.backend.h3.H3Service; +import SuMoC.backend.trip.Modality; +import SuMoC.backend.trip.dtos.RegularTripDetectionDTO; +import org.springframework.stereotype.Component; + +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +@Component +public class RegularTripDetectionDTOFactory { + + private final H3Service h3Service; + + private final Random random = new Random(); + + private final String h3_essen_schuetzenbahn = "8a1fa535568ffff"; + private final String h3_essen_hbf = "8a1fa535020ffff"; + private final String h3_essen_west = "8a1fa5356a5ffff"; + + public RegularTripDetectionDTOFactory(H3Service h3Service) { + this.h3Service = h3Service; + } + + public List regularFromAtoBwithOverlappingAndPreferredTimeWindows() { + List dtos = new ArrayList<>(); + + for (int i = 0; i < 5; i++) { + var startDateTime = LocalDateTime.now().minusMinutes(20 * i).minusWeeks(i); + var endDateTime = startDateTime.plusMinutes(15); + + dtos.add(RegularTripDetectionDTO.builder() + .tripId(i) + .userId(1L) + .startH3Cell(h3_essen_schuetzenbahn) + .endH3Cell(h3_essen_hbf) + .startTime(startDateTime.toInstant(ZoneOffset.UTC)) + .endTime(endDateTime.toInstant(ZoneOffset.UTC)) + .mainModality(Modality.CAR) + .startH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(h3_essen_schuetzenbahn)) + .endH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(h3_essen_hbf)) + .build()); + + if (i == 0) { + // Create double entry for i = 0 to test if detector correctly focusses on the most supported time window + dtos.add(RegularTripDetectionDTO.builder() + .tripId(400 + i) + .userId(1L) + .startH3Cell(h3_essen_schuetzenbahn) + .endH3Cell(h3_essen_hbf) + .startTime(startDateTime.plusWeeks(1).toInstant(ZoneOffset.UTC)) // overlapping time window + .endTime(endDateTime.plusWeeks(1).toInstant(ZoneOffset.UTC)) + .mainModality(Modality.CAR) + .startH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(h3_essen_schuetzenbahn)) + .endH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(h3_essen_hbf)) + .build()); + } + } + return dtos; + } + + public List regularFromAtoB(int size) { + List dtos = new ArrayList<>(); + for (int i = 0; i < size; i++) { + var startDateTime = LocalDateTime.now().minusMinutes(30).minusWeeks(i); + var endDateTime = startDateTime.plusMinutes(15); + + dtos.add(RegularTripDetectionDTO.builder() + .tripId(i) + .userId(1L) + .startH3Cell(h3_essen_schuetzenbahn) + .endH3Cell(h3_essen_hbf) + .startTime(startDateTime.toInstant(ZoneOffset.UTC)) + .endTime(endDateTime.toInstant(ZoneOffset.UTC)) + .mainModality(Modality.CAR) + .startH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(h3_essen_schuetzenbahn)) + .endH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(h3_essen_hbf)) + .build()); + } + + return dtos; + } + + public List regularFromAtoBwithNeighbourCells(int size) { + List dtos = new ArrayList<>(); + for (int i = 0; i < size; i++) { + var startDateTime = LocalDateTime.now().minusMinutes(30).minusWeeks(i); + var endDateTime = startDateTime.plusMinutes(15); + + String startCell = h3Service.getRoutePatternNeighbors(h3_essen_schuetzenbahn).get(random.nextInt(6)); // h3 always has 6 neighbors + if (i == 0) { + startCell = h3_essen_schuetzenbahn; // one time use the original cell - simulates some noise + } + + String endCell = h3Service.getRoutePatternNeighbors(h3_essen_hbf).get(random.nextInt(6)); + if (i == 0) { + endCell = h3_essen_hbf; // one time use the original cell - simulates some noise + } + + dtos.add(RegularTripDetectionDTO.builder() + .tripId(200 + i) + .userId(1L) + .startH3Cell(startCell) + .endH3Cell(endCell) + .startTime(startDateTime.toInstant(ZoneOffset.UTC)) + .endTime(endDateTime.toInstant(ZoneOffset.UTC)) + .mainModality(Modality.CAR) + .startH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(startCell)) + .endH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(endCell)) + .build()); + } + + return dtos; + } + + public List nonRegularFromAtoC() { + List dtos = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + var startDateTime = LocalDateTime.now().minusMinutes(30).minusDays(i); + var endDateTime = startDateTime.plusMinutes(15); + + dtos.add(RegularTripDetectionDTO.builder() + .tripId(100 + i) + .userId(1L) + .startH3Cell(h3_essen_schuetzenbahn) + .endH3Cell(h3_essen_west) + .startTime(startDateTime.toInstant(ZoneOffset.UTC)) + .endTime(endDateTime.toInstant(ZoneOffset.UTC)) + .mainModality(Modality.CAR) + .startH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(h3_essen_schuetzenbahn)) + .endH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(h3_essen_west)) + .build()); + } + + return dtos; + } + +} diff --git a/src/test/java/SuMoC/backend/Factories/TripTestFactory.java b/src/test/java/SuMoC/backend/Factories/TripTestFactory.java new file mode 100644 index 0000000..d500fd2 --- /dev/null +++ b/src/test/java/SuMoC/backend/Factories/TripTestFactory.java @@ -0,0 +1,37 @@ +package SuMoC.backend.Factories; + +import SuMoC.backend.trip.Modality; +import SuMoC.backend.trip.models.Trip; +import SuMoC.backend.trip.models.TripSegment; +import SuMoC.backend.user.models.User; + +import java.time.Instant; +import java.util.HashSet; + +public class TripTestFactory { + + /** + * Returns structurally valid trip, position data is arbitrary. + */ + public static Trip getValidTrip(Instant start, Instant end, User user) { + Trip trip = new Trip(); + trip.setUser(user); + trip.setStartTime(start); + trip.setEndTime(end); + trip.setStartPlace("Start Place"); + trip.setStartLatitude(40.7128); + trip.setStartLongitude(-74.0060); + trip.setStartH3Cell("8928308280fffff"); + trip.setEndPlace("End Place"); + trip.setEndLatitude(34.0522); + trip.setEndLongitude(-118.2437); + trip.setEndH3Cell("8928308280bffff"); + trip.setCo2Emissions(10.5); + trip.setMobilityScore(50); + trip.setCost(50f); + trip.setTripSegments(new HashSet()); + trip.setMainModality(Modality.CAR); + trip.setInvalidated(false); + return trip; + } +} diff --git a/src/test/java/SuMoC/backend/notification/services/NotificationSchedulerServiceTest.java b/src/test/java/SuMoC/backend/notification/services/NotificationSchedulerServiceTest.java new file mode 100644 index 0000000..5df0e47 --- /dev/null +++ b/src/test/java/SuMoC/backend/notification/services/NotificationSchedulerServiceTest.java @@ -0,0 +1,248 @@ +package SuMoC.backend.notification.services; + +import SuMoC.backend.notification.enums.NotificationStatus; +import SuMoC.backend.notification.enums.NotificationType; +import SuMoC.backend.notification.models.Notification; +import SuMoC.backend.notification.repositories.NotificationRepository; +import SuMoC.backend.trend.dto.TrendDetectionDTO; +import SuMoC.backend.trend.enums.DeltaType; +import SuMoC.backend.trend.enums.StatAttribute; +import SuMoC.backend.trend.enums.TrendTimespan; +import SuMoC.backend.trend.enums.TrendType; +import SuMoC.backend.user.models.User; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.persistence.EntityManager; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.time.LocalTime; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +public class NotificationSchedulerServiceTest { + + @Mock + private NotificationRepository notificationRepository; + + @Mock + private EntityManager entityManager; + + private ObjectMapper objectMapper; + + private NotificationSchedulerService notificationSchedulerService; + + @Captor + private ArgumentCaptor> notificationListCaptor; + + private User mockUser; + private LocalTime testTime; + + @BeforeEach + void setUp() { + objectMapper = new ObjectMapper(); + notificationSchedulerService = new NotificationSchedulerService(objectMapper, notificationRepository, entityManager); + mockUser = new User("privateName", "publicName", "test@example.com", "password"); + mockUser.setId(1L); + testTime = LocalTime.of(9, 0); + } + + @Test + @SuppressWarnings("unchecked") + void scheduleAll_WithTrendDetectionDTO_SerializesAndPersistsSuccessfully() { + // Arrange + TrendDetectionDTO trendDetectionDTO = new TrendDetectionDTO( + 1L, + TrendTimespan.WEEKLY, + TrendType.INCREASING, + StatAttribute.CAR_DISTANCE, + DeltaType.ABSOLUTE, + 25.5 + ); + + List dataBodies = List.of(trendDetectionDTO); + + // Mock EntityManager to return a proxy + when(entityManager.getReference(eq(User.class), eq(1L))).thenReturn(mockUser); + + // Act + notificationSchedulerService.scheduleAll( + (List) dataBodies, + NotificationType.TREND, + testTime + ); + + // Assert + verify(notificationRepository, times(1)).saveAll(notificationListCaptor.capture()); + List savedNotifications = notificationListCaptor.getValue(); + + assertEquals(1, savedNotifications.size()); + Notification notification = savedNotifications.getFirst(); + + // Verify notification properties + assertEquals(mockUser, notification.getUser()); + assertEquals(NotificationType.TREND, notification.getType()); + assertEquals(NotificationStatus.PENDING, notification.getStatus()); + assertEquals(testTime, notification.getEarliestTimeOfDayToSend()); + assertEquals(0, notification.getFailedSendAttempts()); + assertNotNull(notification.getCreatedAt()); + + // Verify that the data was serialized correctly + assertNotNull(notification.getData()); + assertTrue(notification.getData().contains("userId")); + assertTrue(notification.getData().contains("WEEKLY")); + assertTrue(notification.getData().contains("INCREASING")); + assertTrue(notification.getData().contains("CAR_DISTANCE")); + } + + @Test + @SuppressWarnings("unchecked") + void scheduleAll_WithTrendDetectionDTO_DataCanBeDeserialized() throws Exception { + // Arrange + TrendDetectionDTO originalDTO = new TrendDetectionDTO( + 1L, + TrendTimespan.WEEKLY, + TrendType.DECREASING, + StatAttribute.CAR_DISTANCE, + DeltaType.PERCENTAGE, + 15.75 + ); + + List dataBodies = List.of(originalDTO); + when(entityManager.getReference(eq(User.class), eq(1L))).thenReturn(mockUser); + + // Act + notificationSchedulerService.scheduleAll( + (List) dataBodies, + NotificationType.TREND, + testTime + ); + + // Capture the saved notification + verify(notificationRepository).saveAll(notificationListCaptor.capture()); + Notification savedNotification = notificationListCaptor.getValue().getFirst(); + + // Assert - deserialize and verify the data + TrendDetectionDTO deserializedDTO = objectMapper.readValue( + savedNotification.getData(), + TrendDetectionDTO.class + ); + + assertEquals(originalDTO.getUserId(), deserializedDTO.getUserId()); + assertEquals(originalDTO.getTimespan(), deserializedDTO.getTimespan()); + assertEquals(originalDTO.getType(), deserializedDTO.getType()); + assertEquals(originalDTO.getAttribute(), deserializedDTO.getAttribute()); + assertEquals(originalDTO.getDeltaType(), deserializedDTO.getDeltaType()); + assertEquals(originalDTO.getChangeValue(), deserializedDTO.getChangeValue()); + } + + @Test + @SuppressWarnings("unchecked") + void scheduleAll_WithMultipleTrendDetectionDTOs_SerializesAll() { + // Arrange + TrendDetectionDTO dto1 = new TrendDetectionDTO( + 1L, + TrendTimespan.WEEKLY, + TrendType.INCREASING, + StatAttribute.CAR_DISTANCE, + DeltaType.ABSOLUTE, + 10.0 + ); + + TrendDetectionDTO dto2 = new TrendDetectionDTO( + 2L, + TrendTimespan.WEEKLY, + TrendType.DECREASING, + StatAttribute.CAR_DISTANCE, + DeltaType.PERCENTAGE, + 5.0 + ); + + List dataBodies = List.of(dto1, dto2); + + // Mock EntityManager to return proxies + User mockUser2 = new User("privateName2", "publicName2", "test2@example.com", "password"); + mockUser2.setId(2L); + + when(entityManager.getReference(eq(User.class), eq(1L))).thenReturn(mockUser); + when(entityManager.getReference(eq(User.class), eq(2L))).thenReturn(mockUser2); + + // Act + notificationSchedulerService.scheduleAll( + (List) dataBodies, + NotificationType.TREND, + testTime + ); + + // Assert + verify(notificationRepository, times(1)).saveAll(notificationListCaptor.capture()); + List savedNotifications = notificationListCaptor.getValue(); + + assertEquals(2, savedNotifications.size()); + assertEquals(mockUser, savedNotifications.get(0).getUser()); + assertEquals(mockUser2, savedNotifications.get(1).getUser()); + } + + @Test + @SuppressWarnings("unchecked") + void scheduleAll_WithTrendDetectionDTO_SerializationException_ThrowsRuntimeException() { + // Arrange + TrendDetectionDTO dto = new TrendDetectionDTO( + 1L, + TrendTimespan.WEEKLY, + TrendType.INCREASING, + StatAttribute.CAR_DISTANCE, + DeltaType.ABSOLUTE, + 25.5 + ); + + List dataBodies = List.of(dto); + + when(entityManager.getReference(eq(User.class), eq(1L))).thenReturn(mockUser); + + // Act & Assert + // The service should handle serialization correctly and not throw exceptions + // for valid DTOs + assertDoesNotThrow(() -> + notificationSchedulerService.scheduleAll( + (List) dataBodies, + NotificationType.TREND, + testTime + ) + ); + } + + @Test + @SuppressWarnings("unchecked") + void scheduleAll_VerifyNotificationStatusIsInitiallyPending() { + // Arrange + TrendDetectionDTO trendDetectionDTO = TrendDetectionDTO.mockTrendDetectionDTO(); + trendDetectionDTO.setUserId(1L); + + List dataBodies = List.of(trendDetectionDTO); + when(entityManager.getReference(eq(User.class), eq(1L))).thenReturn(mockUser); + + // Act + notificationSchedulerService.scheduleAll( + (List) dataBodies, + NotificationType.TREND, + testTime + ); + + // Assert + verify(notificationRepository).saveAll(notificationListCaptor.capture()); + Notification notification = notificationListCaptor.getValue().getFirst(); + + assertEquals(NotificationStatus.PENDING, notification.getStatus()); + assertEquals(0, notification.getFailedSendAttempts()); + } +} + diff --git a/src/test/java/SuMoC/backend/regulartrip/detectionapproaches/IterativeClustererTest.java b/src/test/java/SuMoC/backend/regulartrip/detectionapproaches/IterativeClustererTest.java new file mode 100644 index 0000000..99042d9 --- /dev/null +++ b/src/test/java/SuMoC/backend/regulartrip/detectionapproaches/IterativeClustererTest.java @@ -0,0 +1,90 @@ +package SuMoC.backend.regulartrip.detectionapproaches; + +import SuMoC.backend.Factories.RegularTripDetectionDTOFactory; +import SuMoC.backend.regulartrip.config.RegularTripDetectionProperties; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import static org.mockito.Mockito.when; + +@SpringBootTest(properties = { + "geocoding.provider=carta", + "geocoding.carta.base-url=https://mobydex.locoslab.com/carta" +}) +public class IterativeClustererTest { + + @Mock(lenient = true) + private RegularTripDetectionProperties properties; + + @InjectMocks + private IterativeClusterer iterativeClusterer; + + @Autowired + private RegularTripDetectionDTOFactory regularTripDetectionDTOFactory; + + @BeforeEach + void setUp() { + when(properties.getDetectionTimeWindowDays()).thenReturn(30); + when(properties.getTimeWindowSeconds()).thenReturn(90 * 60); + when(properties.getMinTripsForRegularity()).thenReturn(2); + when(properties.getIterativeShuffleAmounts()).thenReturn(5); + } + + /** + * Easiest case: We only have regular trips from cell a to cell b. + * But also non regular from a to c, b to d, which should not be included in the result. + */ + @Test + public void detectFromSameCellToSameCell_Success() { + // Arrange + var dtos = regularTripDetectionDTOFactory.regularFromAtoB(5); + dtos.addAll(regularTripDetectionDTOFactory.nonRegularFromAtoC()); + + // Act + var result = iterativeClusterer.detectRegularTrips(dtos); + + // Assert + assert (result.size() == 1); + assert (result.get(0).getSupportingTrips().size() == 5); + } + + /** + * Regaulr Trips from cell a to cell b, but we have two overlapping time windows. + * E.g. when window is 90 minutes, we have trips at 08:00 and 08:30 and 09:00 and 09:30. + * The desired behavior is to still only detect one regular trip where the time window is the one that covers as many trips as possible. + */ + @Test + public void detectFromSameCellToSameCellOverlapping_Success() { + // Arrange + var dtos = regularTripDetectionDTOFactory.regularFromAtoBwithOverlappingAndPreferredTimeWindows(); + dtos.addAll(regularTripDetectionDTOFactory.nonRegularFromAtoC()); + + // Act + var result = iterativeClusterer.detectRegularTrips(dtos); + + // Assert + assert (result.size() == 1); + assert (result.get(0).getSupportingTrips().size() == 4); + } + + /** + * We have single non-regular trips from a to b, a+1 to b+1, a-1 to b-1, but together they form a regular trip from neighboring cells. + */ + @Test + public void detectFromNeighboringCells_Success() { + // Arrange + var dtos = regularTripDetectionDTOFactory.regularFromAtoBwithNeighbourCells(5); + dtos.addAll(regularTripDetectionDTOFactory.nonRegularFromAtoC()); + + // Act + var result = iterativeClusterer.detectRegularTrips(dtos); + + // Assert + assert (result.size() == 1); + assert (result.get(0).getSupportingTrips().size() == 5); + } +} diff --git a/src/test/java/SuMoC/backend/trend/services/TrendDetectorServiceTest.java b/src/test/java/SuMoC/backend/trend/services/TrendDetectorServiceTest.java index 41602da..a271961 100644 --- a/src/test/java/SuMoC/backend/trend/services/TrendDetectorServiceTest.java +++ b/src/test/java/SuMoC/backend/trend/services/TrendDetectorServiceTest.java @@ -1,8 +1,8 @@ package SuMoC.backend.trend.services; -import SuMoC.backend.trend.TrendDetection; import SuMoC.backend.trend.WeeklyMobilityStatsRepository; -import SuMoC.backend.trend.config.TrendDetectionProperties; +import SuMoC.backend.trend.config.TrendProperties; +import SuMoC.backend.trend.dto.TrendDetectionDTO; import SuMoC.backend.trend.enums.DeltaType; import SuMoC.backend.trend.enums.StatAttribute; import SuMoC.backend.trend.enums.TrendTimespan; @@ -28,7 +28,7 @@ public class TrendDetectorServiceTest { private WeeklyMobilityStatsRepository weeklyMobilityStatsRepository; @Mock - private TrendDetectionProperties trendDetectionProperties; + private TrendProperties trendProperties; @InjectMocks private TrendDetectorService trendDetectorService; @@ -56,8 +56,8 @@ public class TrendDetectorServiceTest { int weekNumber = 2; // Set threshold values for this test - when(trendDetectionProperties.getPositiveThreshold()).thenReturn(25.0); - when(trendDetectionProperties.getNegativeThreshold()).thenReturn(-25.0); + when(trendProperties.getPositiveThreshold()).thenReturn(25.0); + when(trendProperties.getNegativeThreshold()).thenReturn(-25.0); // User 1: Significant increase (100m -> 400m = +300%) WeeklyMobilityStats user1Previous = createWeeklyStats(user1, year, weekNumber - 1, 100L); @@ -77,14 +77,14 @@ public class TrendDetectorServiceTest { .thenReturn(List.of(user1Current, user2Current, user3Current)); // Act - List detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE); + List detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE); // Assert assertEquals(2, detectedTrends.size(), "Should detect 2 trends (1 increase, 1 decrease)"); // Verify increasing trend for user1 - TrendDetection user1Trend = detectedTrends.stream() - .filter(t -> t.getUser().getId().equals(user1.getId())) + TrendDetectionDTO user1Trend = detectedTrends.stream() + .filter(t -> t.getUserId().equals(user1.getId())) .findFirst() .orElse(null); assertNotNull(user1Trend, "User 1 should have a detected trend"); @@ -95,8 +95,8 @@ public class TrendDetectorServiceTest { assertEquals(300.0, user1Trend.getChangeValue(), 0.01); // Verify decreasing trend for user2 - TrendDetection user2Trend = detectedTrends.stream() - .filter(t -> t.getUser().getId().equals(user2.getId())) + TrendDetectionDTO user2Trend = detectedTrends.stream() + .filter(t -> t.getUserId().equals(user2.getId())) .findFirst() .orElse(null); assertNotNull(user2Trend, "User 2 should have a detected trend"); @@ -108,7 +108,7 @@ public class TrendDetectorServiceTest { // Verify no trend detected for user3 boolean user3HasTrend = detectedTrends.stream() - .anyMatch(t -> t.getUser().getId().equals(user3.getId())); + .anyMatch(t -> t.getUserId().equals(user3.getId())); assertFalse(user3HasTrend, "User 3 should not have a detected trend (change below threshold)"); } @@ -131,7 +131,7 @@ public class TrendDetectorServiceTest { // Act & Assert - should not throw any exception assertDoesNotThrow(() -> { - List detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE); + List detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE); assertEquals(0, detectedTrends.size(), "Should not detect any trends when matching data is missing"); }); } diff --git a/src/test/java/SuMoC/backend/trip/TripRepositoryTest.java b/src/test/java/SuMoC/backend/trip/TripRepositoryTest.java new file mode 100644 index 0000000..1260d59 --- /dev/null +++ b/src/test/java/SuMoC/backend/trip/TripRepositoryTest.java @@ -0,0 +1,70 @@ +package SuMoC.backend.trip; + +import SuMoC.backend.Factories.TripTestFactory; +import SuMoC.backend.Factories.UserTestFactory; +import SuMoC.backend.common.converter.DayOfWeekConverter; +import SuMoC.backend.trip.models.Trip; +import SuMoC.backend.user.models.User; +import SuMoC.backend.user.repository.UserRepository; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import java.time.DayOfWeek; +import java.time.Instant; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@DataJpaTest +@TestPropertySource(properties = { + "spring.jpa.hibernate.ddl-auto=create-drop", + "spring.datasource.url=jdbc:h2:mem:testdb" +}) +public class TripRepositoryTest { + + @Autowired + private TripRepository tripRepository; + + @Autowired + private UserRepository userRepository; + + @Test + void testDayOfWeekConverterAppliedInQuery() { + // Create a user + User user = UserTestFactory.validUser(); + userRepository.save(user); + + // Create trips on different days of the week + // 2025-01-13 is a Monday + Trip mondayTrip = TripTestFactory.getValidTrip(Instant.parse("2025-01-13T10:00:00Z"), Instant.parse("2025-01-13T11:00:00Z"), user); + tripRepository.save(mondayTrip); + + // 2025-01-19 is a Sunday + Trip sundayTrip = TripTestFactory.getValidTrip(Instant.parse("2025-01-19T10:00:00Z"), Instant.parse("2025-01-19T11:00:00Z"), user); + tripRepository.save(sundayTrip); + + // Query for trips on Monday + List mondayTrips = tripRepository.findAllValidFromDateWithMainModalityOnCertainWeekday( + Instant.parse("2025-01-01T00:00:00Z"), + Modality.CAR, + DayOfWeek.MONDAY + ); + + // Verify only Monday trip is returned + assertEquals(1, mondayTrips.size()); + assertEquals(mondayTrip.getId(), mondayTrips.get(0).getId()); + + // Query for trips on Sunday + List sundayTrips = tripRepository.findAllValidFromDateWithMainModalityOnCertainWeekday( + Instant.parse("2025-01-01T00:00:00Z"), + Modality.CAR, + DayOfWeek.SUNDAY + ); + + // Verify only Tuesday trip is returned + assertEquals(1, sundayTrips.size()); + assertEquals(sundayTrip.getId(), sundayTrips.get(0).getId()); + } +}