From ba642d10a5eade412fd7303801967479b7c557e0 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Tue, 13 Jan 2026 12:22:44 +0100 Subject: [PATCH 01/61] add demo endpoint for notification mocks --- .../java/SuMoC/backend/dev/DevController.java | 36 +++++++++++++------ .../backend/firebase/MessageBuilder.java | 24 +++++++++++++ .../notification/NotificationController.java | 9 +++++ .../notification/enums/NotificationType.java | 20 +++++++++++ .../factories/TrendNotificationFactory.java | 4 +-- .../notification/models/Notification.java | 6 +++- .../services/TrendNotificationService.java | 4 +-- .../security/SecurityConfiguration.java | 1 + .../TrendDetectionDTO.java} | 15 ++++++-- .../trend/services/TrendDetectorService.java | 10 +++--- src/main/resources/application.properties | 2 +- .../IterativeClustererTest.java | 8 +++++ .../services/TrendDetectorServiceTest.java | 10 +++--- 13 files changed, 120 insertions(+), 29 deletions(-) create mode 100644 src/main/java/SuMoC/backend/firebase/MessageBuilder.java create mode 100644 src/main/java/SuMoC/backend/notification/NotificationController.java create mode 100644 src/main/java/SuMoC/backend/notification/enums/NotificationType.java rename src/main/java/SuMoC/backend/trend/{TrendDetection.java => dto/TrendDetectionDTO.java} (65%) create mode 100644 src/test/java/SuMoC/backend/regulartrip/detectionapproaches/IterativeClustererTest.java diff --git a/src/main/java/SuMoC/backend/dev/DevController.java b/src/main/java/SuMoC/backend/dev/DevController.java index f19bf8d..1561584 100644 --- a/src/main/java/SuMoC/backend/dev/DevController.java +++ b/src/main/java/SuMoC/backend/dev/DevController.java @@ -1,17 +1,21 @@ package SuMoC.backend.dev; +import SuMoC.backend.firebase.MessageBuilder; import SuMoC.backend.meteo.ForecastService; import SuMoC.backend.meteo.MeteoClient; +import SuMoC.backend.notification.enums.NotificationType; +import SuMoC.backend.notification.models.Notification; import SuMoC.backend.scheduling.ScheduledTasks; +import SuMoC.backend.trend.dto.TrendDetectionDTO; import SuMoC.backend.trend.services.StatTableUpdateService; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.firebase.messaging.FirebaseMessaging; +import com.google.firebase.messaging.Message; +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; @@ -25,18 +29,25 @@ public class DevController { private final FirebaseMessaging firebaseMessaging; private final MeteoClient meteoClient; private final ForecastService forecastService; + private final MessageBuilder messageBuilder; + private final ObjectMapper objectMapper; public DevController( ScheduledTasks scheduledTasks, StatTableUpdateService statTableUpdateService, @Autowired(required = false) FirebaseMessaging firebaseMessaging, MeteoClient meteoClient, - ForecastService forecastService) { + ForecastService forecastService, + MessageBuilder messageBuilder, + ObjectMapper objectMapper + ) { this.scheduledTasks = scheduledTasks; this.statTableUpdateService = statTableUpdateService; this.firebaseMessaging = firebaseMessaging; this.meteoClient = meteoClient; this.forecastService = forecastService; + this.messageBuilder = messageBuilder; + this.objectMapper = objectMapper; } @PostMapping("/trigger-trend-calculation") @@ -49,19 +60,22 @@ public class DevController { statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(day3WeeksAgo); } - @GetMapping("/test-firebase") - public ResponseEntity testFirebaseConnection() { + @GetMapping("/test-firebase/{fcm_token}") + public ResponseEntity testFirebaseConnection(@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 = messageBuilder.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) { diff --git a/src/main/java/SuMoC/backend/firebase/MessageBuilder.java b/src/main/java/SuMoC/backend/firebase/MessageBuilder.java new file mode 100644 index 0000000..2a41b67 --- /dev/null +++ b/src/main/java/SuMoC/backend/firebase/MessageBuilder.java @@ -0,0 +1,24 @@ +package SuMoC.backend.firebase; + +import SuMoC.backend.notification.models.Notification; +import com.google.firebase.messaging.Message; +import org.springframework.stereotype.Service; + +@Service +public class MessageBuilder { + + public Message generateMessage(Notification notification, String overrideToken) { + // TODO get users token from database + String token = "fEfi8Ao_SQiqURpniIT5cF:APA91bHdfhPIpoSC4Bw7HHr4LzszBWvkyJ4sX0jkAr03gG1XTfRkVxJvLEmV0DiiYzRHN-l2LZVgHicxeWGQek-qYvAkJylfXHxn902nGZOgQ5jyNYqN58M"; + + if (overrideToken != null && !overrideToken.isEmpty()) { + token = overrideToken; + } + + 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..65270c5 --- /dev/null +++ b/src/main/java/SuMoC/backend/notification/NotificationController.java @@ -0,0 +1,9 @@ +package SuMoC.backend.notification; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/notifications") +public class NotificationController { +} 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 index d16cc2b..0b3140e 100644 --- a/src/main/java/SuMoC/backend/notification/factories/TrendNotificationFactory.java +++ b/src/main/java/SuMoC/backend/notification/factories/TrendNotificationFactory.java @@ -1,7 +1,7 @@ package SuMoC.backend.notification.factories; import SuMoC.backend.notification.models.Notification; -import SuMoC.backend.trend.TrendDetection; +import SuMoC.backend.trend.dto.TrendDetectionDTO; import SuMoC.backend.trend.services.TrendMessageGenerator; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; @@ -12,7 +12,7 @@ public class TrendNotificationFactory { private final TrendMessageGenerator trendMessageGenerator; - public Notification createNotification(TrendDetection trend) { + public Notification createNotification(TrendDetectionDTO trend) { return Notification.builder() .user(trend.getUser()) .build(); diff --git a/src/main/java/SuMoC/backend/notification/models/Notification.java b/src/main/java/SuMoC/backend/notification/models/Notification.java index dda300e..5ed95fa 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,10 @@ public class Notification { private User user; @Column(nullable = false) - private String message; + 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. diff --git a/src/main/java/SuMoC/backend/notification/services/TrendNotificationService.java b/src/main/java/SuMoC/backend/notification/services/TrendNotificationService.java index d0b8d98..1715652 100644 --- a/src/main/java/SuMoC/backend/notification/services/TrendNotificationService.java +++ b/src/main/java/SuMoC/backend/notification/services/TrendNotificationService.java @@ -3,7 +3,7 @@ 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 SuMoC.backend.trend.dto.TrendDetectionDTO; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @@ -17,7 +17,7 @@ public class TrendNotificationService { private final TrendNotificationFactory trendNotificationFactory; - public List generateTrendNotifications(List trendList) { + public List generateTrendNotifications(List trendList) { List notificationList = trendList.stream().map(trendNotificationFactory::createNotification).toList(); return List.of(); diff --git a/src/main/java/SuMoC/backend/security/SecurityConfiguration.java b/src/main/java/SuMoC/backend/security/SecurityConfiguration.java index 04d9308..ba1bcf0 100644 --- a/src/main/java/SuMoC/backend/security/SecurityConfiguration.java +++ b/src/main/java/SuMoC/backend/security/SecurityConfiguration.java @@ -98,6 +98,7 @@ public class SecurityConfiguration { auth.requestMatchers("/friendship/**").hasAnyRole("ADMIN", "USER"); auth.requestMatchers("/trip/**").hasAnyRole("USER", "ADMIN"); auth.requestMatchers("/geocoding/**").hasAnyRole("USER", "ADMIN"); + auth.requestMatchers("/notifications/**").hasAnyRole("USER", "ADMIN"); //auth.requestMatchers("/error").permitAll(); auth.anyRequest().authenticated(); diff --git a/src/main/java/SuMoC/backend/trend/TrendDetection.java b/src/main/java/SuMoC/backend/trend/dto/TrendDetectionDTO.java similarity index 65% rename from src/main/java/SuMoC/backend/trend/TrendDetection.java rename to src/main/java/SuMoC/backend/trend/dto/TrendDetectionDTO.java index b715afd..eba82e4 100644 --- a/src/main/java/SuMoC/backend/trend/TrendDetection.java +++ b/src/main/java/SuMoC/backend/trend/dto/TrendDetectionDTO.java @@ -1,4 +1,4 @@ -package SuMoC.backend.trend; +package SuMoC.backend.trend.dto; import SuMoC.backend.trend.enums.*; import SuMoC.backend.user.models.User; @@ -9,7 +9,7 @@ import lombok.Data; @Data @Builder @AllArgsConstructor -public class TrendDetection { +public class TrendDetectionDTO { private User user; private TrendTimespan timespan; private TrendType type; @@ -17,6 +17,17 @@ public class TrendDetection { private DeltaType deltaType; private double changeValue; + public static TrendDetectionDTO mockTrendDetectionDTO() { + return TrendDetectionDTO.builder() + .user(null) // Replace with a mock User if needed + .timespan(TrendTimespan.WEEKLY) + .type(TrendType.INCREASING) + .attribute(StatAttribute.CAR_DISTANCE) + .deltaType(DeltaType.ABSOLUTE) + .changeValue(15.0) + .build(); + } + public TrendConnotation getTrendConnotation() { if (this.type == TrendType.INCREASING) { return switch (attribute) { diff --git a/src/main/java/SuMoC/backend/trend/services/TrendDetectorService.java b/src/main/java/SuMoC/backend/trend/services/TrendDetectorService.java index 766bab6..7b6f004 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.dto.TrendDetectionDTO; import SuMoC.backend.trend.enums.DeltaType; import SuMoC.backend.trend.enums.StatAttribute; import SuMoC.backend.trend.enums.TrendTimespan; @@ -24,7 +24,7 @@ public class TrendDetectorService { private final TrendDetectionProperties trendDetectionProperties; - 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(); @@ -57,7 +57,7 @@ public class TrendDetectorService { double percentageChange = ((currentValue - previousValue) / previousValue) * 100.0; if (percentageChange >= trendDetectionProperties.getPositiveThreshold()) { - detectedTrends.add(new TrendDetection( + detectedTrends.add(new TrendDetectionDTO( currentStats.getUser(), TrendTimespan.WEEKLY, TrendType.INCREASING, @@ -66,7 +66,7 @@ public class TrendDetectorService { percentageChange )); } else if (percentageChange <= trendDetectionProperties.getNegativeThreshold()) { - detectedTrends.add(new TrendDetection( + detectedTrends.add(new TrendDetectionDTO( previousStats.getUser(), TrendTimespan.WEEKLY, TrendType.DECREASING, diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index d6aff90..15ec039 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -19,7 +19,7 @@ trenddetection.positive-threshold=25.0 # Regular trip detection settings #regulartripdetection.detection-algorithm=iterative # 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 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..7ce3749 --- /dev/null +++ b/src/test/java/SuMoC/backend/regulartrip/detectionapproaches/IterativeClustererTest.java @@ -0,0 +1,8 @@ +package SuMoC.backend.regulartrip.detectionapproaches; + +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +public class IterativeClustererTest { +} diff --git a/src/test/java/SuMoC/backend/trend/services/TrendDetectorServiceTest.java b/src/test/java/SuMoC/backend/trend/services/TrendDetectorServiceTest.java index 41602da..2f5c4e3 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.dto.TrendDetectionDTO; import SuMoC.backend.trend.enums.DeltaType; import SuMoC.backend.trend.enums.StatAttribute; import SuMoC.backend.trend.enums.TrendTimespan; @@ -77,13 +77,13 @@ 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() + TrendDetectionDTO user1Trend = detectedTrends.stream() .filter(t -> t.getUser().getId().equals(user1.getId())) .findFirst() .orElse(null); @@ -95,7 +95,7 @@ public class TrendDetectorServiceTest { assertEquals(300.0, user1Trend.getChangeValue(), 0.01); // Verify decreasing trend for user2 - TrendDetection user2Trend = detectedTrends.stream() + TrendDetectionDTO user2Trend = detectedTrends.stream() .filter(t -> t.getUser().getId().equals(user2.getId())) .findFirst() .orElse(null); @@ -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"); }); } From bef418d77d9486a952466f432b38bf38c4923cbc Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Tue, 13 Jan 2026 14:43:36 +0100 Subject: [PATCH 02/61] basic firebase notification sending + token registration logic --- .../java/SuMoC/backend/dev/DevController.java | 10 ++-- ...ilder.java => FirebaseMessageBuilder.java} | 11 +--- .../notification/NotificationController.java | 34 +++++++++++ .../enums/NotificationProvider.java | 5 ++ .../notification/models/Notification.java | 2 + .../models/NotificationToken.java | 25 ++++++++ .../NotificationTokenRepository.java | 10 ++++ .../services/NotificationSender.java | 60 +++++++++++++++++++ .../services/NotificationTokenService.java | 30 ++++++++++ 9 files changed, 173 insertions(+), 14 deletions(-) rename src/main/java/SuMoC/backend/firebase/{MessageBuilder.java => FirebaseMessageBuilder.java} (55%) create mode 100644 src/main/java/SuMoC/backend/notification/enums/NotificationProvider.java create mode 100644 src/main/java/SuMoC/backend/notification/models/NotificationToken.java create mode 100644 src/main/java/SuMoC/backend/notification/repositories/NotificationTokenRepository.java create mode 100644 src/main/java/SuMoC/backend/notification/services/NotificationSender.java create mode 100644 src/main/java/SuMoC/backend/notification/services/NotificationTokenService.java diff --git a/src/main/java/SuMoC/backend/dev/DevController.java b/src/main/java/SuMoC/backend/dev/DevController.java index 1561584..e2eb722 100644 --- a/src/main/java/SuMoC/backend/dev/DevController.java +++ b/src/main/java/SuMoC/backend/dev/DevController.java @@ -1,6 +1,6 @@ package SuMoC.backend.dev; -import SuMoC.backend.firebase.MessageBuilder; +import SuMoC.backend.firebase.FirebaseMessageBuilder; import SuMoC.backend.meteo.ForecastService; import SuMoC.backend.meteo.MeteoClient; import SuMoC.backend.notification.enums.NotificationType; @@ -29,7 +29,7 @@ public class DevController { private final FirebaseMessaging firebaseMessaging; private final MeteoClient meteoClient; private final ForecastService forecastService; - private final MessageBuilder messageBuilder; + private final FirebaseMessageBuilder firebaseMessageBuilder; private final ObjectMapper objectMapper; public DevController( @@ -38,7 +38,7 @@ public class DevController { @Autowired(required = false) FirebaseMessaging firebaseMessaging, MeteoClient meteoClient, ForecastService forecastService, - MessageBuilder messageBuilder, + FirebaseMessageBuilder firebaseMessageBuilder, ObjectMapper objectMapper ) { this.scheduledTasks = scheduledTasks; @@ -46,7 +46,7 @@ public class DevController { this.firebaseMessaging = firebaseMessaging; this.meteoClient = meteoClient; this.forecastService = forecastService; - this.messageBuilder = messageBuilder; + this.firebaseMessageBuilder = firebaseMessageBuilder; this.objectMapper = objectMapper; } @@ -71,7 +71,7 @@ public class DevController { notification.setType(NotificationType.TREND); notification.setData(objectMapper.writeValueAsString(TrendDetectionDTO.mockTrendDetectionDTO())); - Message mockTrendMessage = messageBuilder.generateMessage(notification, fcmToken); + Message mockTrendMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken); // Send to a topic (no device registration needed) String message = firebaseMessaging.sendAsync( diff --git a/src/main/java/SuMoC/backend/firebase/MessageBuilder.java b/src/main/java/SuMoC/backend/firebase/FirebaseMessageBuilder.java similarity index 55% rename from src/main/java/SuMoC/backend/firebase/MessageBuilder.java rename to src/main/java/SuMoC/backend/firebase/FirebaseMessageBuilder.java index 2a41b67..3221a08 100644 --- a/src/main/java/SuMoC/backend/firebase/MessageBuilder.java +++ b/src/main/java/SuMoC/backend/firebase/FirebaseMessageBuilder.java @@ -5,16 +5,9 @@ import com.google.firebase.messaging.Message; import org.springframework.stereotype.Service; @Service -public class MessageBuilder { - - public Message generateMessage(Notification notification, String overrideToken) { - // TODO get users token from database - String token = "fEfi8Ao_SQiqURpniIT5cF:APA91bHdfhPIpoSC4Bw7HHr4LzszBWvkyJ4sX0jkAr03gG1XTfRkVxJvLEmV0DiiYzRHN-l2LZVgHicxeWGQek-qYvAkJylfXHxn902nGZOgQ5jyNYqN58M"; - - if (overrideToken != null && !overrideToken.isEmpty()) { - token = overrideToken; - } +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()); diff --git a/src/main/java/SuMoC/backend/notification/NotificationController.java b/src/main/java/SuMoC/backend/notification/NotificationController.java index 65270c5..8571ae5 100644 --- a/src/main/java/SuMoC/backend/notification/NotificationController.java +++ b/src/main/java/SuMoC/backend/notification/NotificationController.java @@ -1,9 +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/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/models/Notification.java b/src/main/java/SuMoC/backend/notification/models/Notification.java index 5ed95fa..03fb44e 100644 --- a/src/main/java/SuMoC/backend/notification/models/Notification.java +++ b/src/main/java/SuMoC/backend/notification/models/Notification.java @@ -26,6 +26,7 @@ public class Notification { private User user; @Column(nullable = false) + @Enumerated(EnumType.STRING) private NotificationType type; @Column(columnDefinition = "TEXT") @@ -40,6 +41,7 @@ public class Notification { private LocalTime earliestTimeOfDayToSend; @Column(nullable = false) + @Enumerated(EnumType.STRING) private NotificationStatus status; @Column(nullable = false) 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..84be22a --- /dev/null +++ b/src/main/java/SuMoC/backend/notification/models/NotificationToken.java @@ -0,0 +1,25 @@ +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(nullable = false, unique = true) + private Long userId; + + @Column(nullable = false) + @Enumerated(EnumType.STRING) + private NotificationProvider provider; + + @Column(nullable = false, unique = true, length = 512) + private String token; + + +} 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/NotificationSender.java b/src/main/java/SuMoC/backend/notification/services/NotificationSender.java new file mode 100644 index 0000000..0e66a51 --- /dev/null +++ b/src/main/java/SuMoC/backend/notification/services/NotificationSender.java @@ -0,0 +1,60 @@ +package SuMoC.backend.notification.services; + +import SuMoC.backend.firebase.FirebaseMessageBuilder; +import SuMoC.backend.notification.models.Notification; +import SuMoC.backend.notification.models.NotificationToken; +import SuMoC.backend.notification.repositories.NotificationTokenRepository; +import SuMoC.backend.user.models.User; +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.NoSuchElementException; +import java.util.logging.Logger; + +@Service +public class NotificationSender { + + private final NotificationTokenRepository notificationTokenRepository; + private final FirebaseMessageBuilder firebaseMessageBuilder; + private final Logger logger = Logger.getLogger(NotificationSender.class.getName()); + private final FirebaseMessaging firebaseMessaging; + + public NotificationSender( + NotificationTokenRepository notificationTokenRepository, + FirebaseMessageBuilder firebaseMessageBuilder, + @Autowired(required = false) FirebaseMessaging firebaseMessaging + ) { + this.notificationTokenRepository = notificationTokenRepository; + this.firebaseMessageBuilder = firebaseMessageBuilder; + this.firebaseMessaging = firebaseMessaging; + } + + public void sendNotification(User user, Notification notification) { + // get users notification token + NotificationToken token; + try { + token = notificationTokenRepository.findByUserId(user.getId()).orElseThrow(); + } catch (NoSuchElementException e) { + logger.warning("No notification token found for user id, skipping send: " + user.getId()); + 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()); + + firebaseMessaging.sendAsync(message) + .addListener(() -> logger.info("Notification sent to user"), Runnable::run); + } +} 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); + } + } +} From 06aa0ce3cc39a9a5c36de3552fdd93eec25a6a9d Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Tue, 13 Jan 2026 16:42:31 +0100 Subject: [PATCH 03/61] implemented scheduled worker that processes queued notifications --- .../java/SuMoC/backend/dev/DevController.java | 42 ++++++++- .../java/SuMoC/backend/dev/DevProperties.java | 15 ++++ .../config/NotificationProperties.java | 15 ++++ .../enums/NotificationStatus.java | 9 ++ .../notification/models/Notification.java | 12 ++- .../models/NotificationToken.java | 6 +- .../repositories/NotificationRepository.java | 13 +++ .../services/NotificationSender.java | 41 ++++++--- .../services/NotificationWorker.java | 31 +++++++ .../backend/scheduling/ScheduledTasks.java | 13 +++ .../scheduling/SchedulingProperties.java | 1 + .../backend/seed/user/DevUserSeeder.java | 36 ++++++-- .../java/SuMoC/backend/user/models/User.java | 89 ++----------------- src/main/resources/application.properties | 6 +- 14 files changed, 225 insertions(+), 104 deletions(-) create mode 100644 src/main/java/SuMoC/backend/dev/DevProperties.java create mode 100644 src/main/java/SuMoC/backend/notification/config/NotificationProperties.java create mode 100644 src/main/java/SuMoC/backend/notification/services/NotificationWorker.java diff --git a/src/main/java/SuMoC/backend/dev/DevController.java b/src/main/java/SuMoC/backend/dev/DevController.java index e2eb722..7ecedc6 100644 --- a/src/main/java/SuMoC/backend/dev/DevController.java +++ b/src/main/java/SuMoC/backend/dev/DevController.java @@ -3,14 +3,19 @@ package SuMoC.backend.dev; import SuMoC.backend.firebase.FirebaseMessageBuilder; 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.scheduling.ScheduledTasks; import SuMoC.backend.trend.dto.TrendDetectionDTO; import SuMoC.backend.trend.services.StatTableUpdateService; +import SuMoC.backend.user.models.User; +import SuMoC.backend.user.repository.UserRepository; 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; @@ -18,6 +23,8 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; @RestController @RequestMapping("/dev") @@ -31,6 +38,8 @@ public class DevController { private final ForecastService forecastService; private final FirebaseMessageBuilder firebaseMessageBuilder; private final ObjectMapper objectMapper; + private final NotificationRepository notificationRepository; + private final UserRepository userRepository; public DevController( ScheduledTasks scheduledTasks, @@ -39,7 +48,8 @@ public class DevController { MeteoClient meteoClient, ForecastService forecastService, FirebaseMessageBuilder firebaseMessageBuilder, - ObjectMapper objectMapper + ObjectMapper objectMapper, + NotificationRepository notificationRepository, UserRepository userRepository ) { this.scheduledTasks = scheduledTasks; this.statTableUpdateService = statTableUpdateService; @@ -48,6 +58,8 @@ public class DevController { this.forecastService = forecastService; this.firebaseMessageBuilder = firebaseMessageBuilder; this.objectMapper = objectMapper; + this.notificationRepository = notificationRepository; + this.userRepository = userRepository; } @PostMapping("/trigger-trend-calculation") @@ -61,6 +73,7 @@ public class DevController { } @GetMapping("/test-firebase/{fcm_token}") + @Operation(description = "Immediately sends a test notification of type TREND to the provided FCM token.") public ResponseEntity testFirebaseConnection(@PathVariable("fcm_token") @NotNull String fcmToken) { if (firebaseMessaging == null) { return ResponseEntity.status(503) @@ -83,6 +96,33 @@ public class DevController { } } + @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(); + + Notification notification = Notification.builder() + .type(NotificationType.TREND) + .data(objectMapper.writeValueAsString(TrendDetectionDTO.mockTrendDetectionDTO())) + .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()); + } + } + @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/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/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/models/Notification.java b/src/main/java/SuMoC/backend/notification/models/Notification.java index 03fb44e..bc0b5db 100644 --- a/src/main/java/SuMoC/backend/notification/models/Notification.java +++ b/src/main/java/SuMoC/backend/notification/models/Notification.java @@ -42,11 +42,19 @@ public class Notification { @Column(nullable = false) @Enumerated(EnumType.STRING) - private NotificationStatus status; + 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(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 index 84be22a..3fb132a 100644 --- a/src/main/java/SuMoC/backend/notification/models/NotificationToken.java +++ b/src/main/java/SuMoC/backend/notification/models/NotificationToken.java @@ -11,15 +11,13 @@ import lombok.Setter; public class NotificationToken { @Id - @Column(nullable = false, unique = true) + @Column(name = "user_id", nullable = false, unique = true) private Long userId; @Column(nullable = false) @Enumerated(EnumType.STRING) private NotificationProvider provider; - @Column(nullable = false, unique = true, length = 512) + @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..7b5cc35 100644 --- a/src/main/java/SuMoC/backend/notification/repositories/NotificationRepository.java +++ b/src/main/java/SuMoC/backend/notification/repositories/NotificationRepository.java @@ -2,6 +2,19 @@ package SuMoC.backend.notification.repositories; import SuMoC.backend.notification.models.Notification; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +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); } diff --git a/src/main/java/SuMoC/backend/notification/services/NotificationSender.java b/src/main/java/SuMoC/backend/notification/services/NotificationSender.java index 0e66a51..abfe545 100644 --- a/src/main/java/SuMoC/backend/notification/services/NotificationSender.java +++ b/src/main/java/SuMoC/backend/notification/services/NotificationSender.java @@ -1,16 +1,17 @@ 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 SuMoC.backend.user.models.User; 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.NoSuchElementException; import java.util.logging.Logger; @Service @@ -20,24 +21,29 @@ 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 + @Autowired(required = false) FirebaseMessaging firebaseMessaging, + NotificationRepository notificationRepository, NotificationProperties notificationProperties ) { this.notificationTokenRepository = notificationTokenRepository; this.firebaseMessageBuilder = firebaseMessageBuilder; this.firebaseMessaging = firebaseMessaging; + this.notificationRepository = notificationRepository; + this.notificationProperties = notificationProperties; } - public void sendNotification(User user, Notification notification) { - // get users notification token - NotificationToken token; - try { - token = notificationTokenRepository.findByUserId(user.getId()).orElseThrow(); - } catch (NoSuchElementException e) { - logger.warning("No notification token found for user id, skipping send: " + user.getId()); + 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; } @@ -55,6 +61,19 @@ public class NotificationSender { Message message = firebaseMessageBuilder.generateMessage(notification, token.getToken()); firebaseMessaging.sendAsync(message) - .addListener(() -> logger.info("Notification sent to user"), Runnable::run); + .addListener(() -> { + try { + notification.setStatus(NotificationStatus.SENT); + notificationRepository.save(notification); + logger.info("Notification sent successfully to user: " + notification.getUser().getId()); + } catch (Exception e) { + notification.incrementFailedSendAttempts(); + if (notification.getFailedSendAttempts() >= notificationProperties.getMaxFailedSendAttempts()) { + notification.setStatus(NotificationStatus.FAILED); + } + notificationRepository.save(notification); + logger.severe("Failed to send notification: " + e.getMessage()); + } + }, Runnable::run); } } 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..4aa6916 --- /dev/null +++ b/src/main/java/SuMoC/backend/notification/services/NotificationWorker.java @@ -0,0 +1,31 @@ +package SuMoC.backend.notification.services; + +import SuMoC.backend.notification.models.Notification; +import SuMoC.backend.notification.repositories.NotificationRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.time.LocalTime; +import java.util.List; + +@Service +@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); + } + } +} diff --git a/src/main/java/SuMoC/backend/scheduling/ScheduledTasks.java b/src/main/java/SuMoC/backend/scheduling/ScheduledTasks.java index df949d5..ea17c93 100644 --- a/src/main/java/SuMoC/backend/scheduling/ScheduledTasks.java +++ b/src/main/java/SuMoC/backend/scheduling/ScheduledTasks.java @@ -1,5 +1,6 @@ package SuMoC.backend.scheduling; +import SuMoC.backend.notification.services.NotificationWorker; import SuMoC.backend.trend.services.StatTableUpdateService; import lombok.RequiredArgsConstructor; import org.slf4j.Logger; @@ -19,6 +20,8 @@ public class ScheduledTasks { private final StatTableUpdateService statTableUpdateService; + private final NotificationWorker notificationWorker; + @Scheduled(cron = "#{@schedulingProperties.calculateWeeklyMobilityStats}") public void scheduleCalculateWeeklyMobilityStats() { logger.info("Scheduled task triggered: calculateWeeklyMobilityStatsForAllUsers"); @@ -29,4 +32,14 @@ public class ScheduledTasks { logger.error("Error calculating weekly mobility stats.", e); } } + + @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); + } + } } diff --git a/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java b/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java index f6103e7..1a24ab3 100644 --- a/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java +++ b/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java @@ -12,4 +12,5 @@ import org.springframework.stereotype.Component; public class SchedulingProperties { private int poolSize = 5; private String calculateWeeklyMobilityStats = "1 30 0 * * 1"; // Once per week + private String runNotificationWorker = "0 * * * * *"; // Every minute } 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/user/models/User.java b/src/main/java/SuMoC/backend/user/models/User.java index a1b442e..f452f23 100644 --- a/src/main/java/SuMoC/backend/user/models/User.java +++ b/src/main/java/SuMoC/backend/user/models/User.java @@ -1,15 +1,20 @@ package SuMoC.backend.user.models; +import SuMoC.backend.notification.models.NotificationToken; import SuMoC.backend.trip.models.Trip; import SuMoC.backend.user.enums.RoleName; import SuMoC.backend.user.enums.VisibilityPrivacy; import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; import java.util.HashSet; import java.util.Set; @Entity @Table(name = "users") +@Getter +@Setter public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -52,6 +57,10 @@ public class User { @Column(name = "role") private Set roles; + @OneToOne + @JoinColumn(name = "id", referencedColumnName = "user_id") + private NotificationToken notificationToken; + public User() { } @@ -78,84 +87,4 @@ public class User { this.roles = new HashSet<>(); this.roles.add(RoleName.USER); } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getPublicName() { - return publicName; - } - - public void setPublicName(String publicName) { - this.publicName = publicName; - } - - public String getPrivateName() { - return privateName; - } - - public void setPrivateName(String privateName) { - this.privateName = privateName; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public VisibilityPrivacy getVisibilityPrivacy() { - return visibilityPrivacy; - } - - public void setVisibilityPrivacy(VisibilityPrivacy visibilityPrivacy) { - this.visibilityPrivacy = visibilityPrivacy; - } - - public String getFriendCode() { - return friendCode; - } - - public void setFriendCode(String friendCode) { - this.friendCode = friendCode; - } - - public Set getTrips() { - return trips; - } - - public void setTrips(Set trips) { - this.trips = trips; - } - - public Set getFriendships() { - return friendships; - } - - public void setFriendships(Set friendships) { - this.friendships = friendships; - } - - public Set getRoles() { - return roles; - } - - public void setRoles(Set roles) { - this.roles = roles; - } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 15ec039..eca34b8 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -11,6 +11,8 @@ 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 +# Scheduling settings +sumoc.scheduling.run-notification-worker=*/15 * * * * * # Disabled for development - TODO set reasonable rhythm sumoc.scheduling.calculate-trend-table-cron=- # Trend detection settings @@ -24,4 +26,6 @@ firebase.config.service-account=classpath:firebase-private-key.json # Base URL to external services carta.base-url=https://www.innamoruhr.de/c2 nominatim.base-url=http://localhost:6666 -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=eBnklYXTRNaD7d--7gQy68:APA91bGN00vqYp0LO3Xi5aikDensT7RYYckdIBLUXKdQHphRYPaFQrxYGgnpuEg7AEyLfMtZxkHvi2KEXX-a02DwAR9xC2-qaNacZ3kbR1s0xNpG-N3IYp0 \ No newline at end of file From bc3dd9b59b61fc65d4468aa2c9cc8ded488338f6 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Tue, 13 Jan 2026 16:48:18 +0100 Subject: [PATCH 04/61] correctly recognize firebase errors when sending exceptions --- .../services/NotificationSender.java | 39 ++++++++++++------- 1 file changed, 24 insertions(+), 15 deletions(-) diff --git a/src/main/java/SuMoC/backend/notification/services/NotificationSender.java b/src/main/java/SuMoC/backend/notification/services/NotificationSender.java index abfe545..a1af745 100644 --- a/src/main/java/SuMoC/backend/notification/services/NotificationSender.java +++ b/src/main/java/SuMoC/backend/notification/services/NotificationSender.java @@ -7,6 +7,10 @@ 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; @@ -60,20 +64,25 @@ public class NotificationSender { Message message = firebaseMessageBuilder.generateMessage(notification, token.getToken()); - firebaseMessaging.sendAsync(message) - .addListener(() -> { - try { - notification.setStatus(NotificationStatus.SENT); - notificationRepository.save(notification); - logger.info("Notification sent successfully to user: " + notification.getUser().getId()); - } catch (Exception e) { - notification.incrementFailedSendAttempts(); - if (notification.getFailedSendAttempts() >= notificationProperties.getMaxFailedSendAttempts()) { - notification.setStatus(NotificationStatus.FAILED); - } - notificationRepository.save(notification); - logger.severe("Failed to send notification: " + e.getMessage()); - } - }, Runnable::run); + 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(); + 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()); + } } From 521a4ba95765e1e1a059f27b529bf6267333d121 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Tue, 13 Jan 2026 17:04:17 +0100 Subject: [PATCH 05/61] add notification cleanup task --- .../java/SuMoC/backend/dev/DevController.java | 22 +++++++++++++++++++ .../repositories/NotificationRepository.java | 10 +++++++++ .../services/NotificationWorker.java | 11 ++++++++++ .../backend/scheduling/ScheduledTasks.java | 20 +++++++++++++++++ .../scheduling/SchedulingProperties.java | 1 + 5 files changed, 64 insertions(+) diff --git a/src/main/java/SuMoC/backend/dev/DevController.java b/src/main/java/SuMoC/backend/dev/DevController.java index 7ecedc6..a7d5a19 100644 --- a/src/main/java/SuMoC/backend/dev/DevController.java +++ b/src/main/java/SuMoC/backend/dev/DevController.java @@ -12,6 +12,7 @@ import SuMoC.backend.trend.dto.TrendDetectionDTO; import SuMoC.backend.trend.services.StatTableUpdateService; 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; @@ -123,6 +124,27 @@ public class DevController { } } + @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/notification/repositories/NotificationRepository.java b/src/main/java/SuMoC/backend/notification/repositories/NotificationRepository.java index 7b5cc35..1376d14 100644 --- a/src/main/java/SuMoC/backend/notification/repositories/NotificationRepository.java +++ b/src/main/java/SuMoC/backend/notification/repositories/NotificationRepository.java @@ -2,8 +2,10 @@ 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; @@ -17,4 +19,12 @@ public interface NotificationRepository extends JpaRepository 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/services/NotificationWorker.java b/src/main/java/SuMoC/backend/notification/services/NotificationWorker.java index 4aa6916..0a0a81d 100644 --- a/src/main/java/SuMoC/backend/notification/services/NotificationWorker.java +++ b/src/main/java/SuMoC/backend/notification/services/NotificationWorker.java @@ -2,13 +2,16 @@ 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 { @@ -28,4 +31,12 @@ public class NotificationWorker { 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/scheduling/ScheduledTasks.java b/src/main/java/SuMoC/backend/scheduling/ScheduledTasks.java index ea17c93..0546277 100644 --- a/src/main/java/SuMoC/backend/scheduling/ScheduledTasks.java +++ b/src/main/java/SuMoC/backend/scheduling/ScheduledTasks.java @@ -22,17 +22,24 @@ public class ScheduledTasks { private final NotificationWorker notificationWorker; + /** + * Calculate weekly mobility stats for all users and generate corresponding notifications. + */ @Scheduled(cron = "#{@schedulingProperties.calculateWeeklyMobilityStats}") public void scheduleCalculateWeeklyMobilityStats() { logger.info("Scheduled task triggered: calculateWeeklyMobilityStatsForAllUsers"); try { LocalDate dayOfLastWeek = LocalDate.now().minusDays(7); statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(dayOfLastWeek); + // TODO generate and queue notifications about new stats being available } 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"); @@ -42,4 +49,17 @@ public class ScheduledTasks { 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); + } + } } diff --git a/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java b/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java index 1a24ab3..8ffbbf3 100644 --- a/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java +++ b/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java @@ -13,4 +13,5 @@ public class SchedulingProperties { private int poolSize = 5; private String calculateWeeklyMobilityStats = "1 30 0 * * 1"; // Once per week private String runNotificationWorker = "0 * * * * *"; // Every minute + private String cleanUpOldNotifications = "0 0 3 * * *"; // Daily at 3 AM } From 11ce10a8d871744d77c366d1b7d0faf95119c7b1 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Tue, 13 Jan 2026 18:07:15 +0100 Subject: [PATCH 06/61] implemented scheduled tasks and notification scheduler so that whole chain task -> detected trends -> scheduled notification -> notification sent by worker is working --- .../java/SuMoC/backend/dev/DevController.java | 10 +++- .../factories/TrendNotificationFactory.java | 20 ------- .../interfaces/NotificationPublisher.java | 4 -- .../interfaces/NotificationSender.java | 4 -- .../notification/interfaces/Notifieable.java | 5 ++ .../NotificationSchedulerService.java | 55 +++++++++++++++++++ .../services/TrendNotificationService.java | 25 --------- .../backend/scheduling/ScheduledTasks.java | 11 ++-- .../scheduling/SchedulingProperties.java | 2 +- ...onProperties.java => TrendProperties.java} | 12 +++- .../backend/trend/dto/TrendDetectionDTO.java | 8 +-- .../trend/services/TrendDetectorService.java | 12 ++-- .../services/TrendNotificationService.java | 31 +++++++++++ .../services/TrendDetectorServiceTest.java | 14 ++--- 14 files changed, 134 insertions(+), 79 deletions(-) delete mode 100644 src/main/java/SuMoC/backend/notification/factories/TrendNotificationFactory.java delete mode 100644 src/main/java/SuMoC/backend/notification/interfaces/NotificationPublisher.java delete mode 100644 src/main/java/SuMoC/backend/notification/interfaces/NotificationSender.java create mode 100644 src/main/java/SuMoC/backend/notification/interfaces/Notifieable.java create mode 100644 src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java delete mode 100644 src/main/java/SuMoC/backend/notification/services/TrendNotificationService.java rename src/main/java/SuMoC/backend/trend/config/{TrendDetectionProperties.java => TrendProperties.java} (55%) create mode 100644 src/main/java/SuMoC/backend/trend/services/TrendNotificationService.java diff --git a/src/main/java/SuMoC/backend/dev/DevController.java b/src/main/java/SuMoC/backend/dev/DevController.java index a7d5a19..f2fca27 100644 --- a/src/main/java/SuMoC/backend/dev/DevController.java +++ b/src/main/java/SuMoC/backend/dev/DevController.java @@ -10,6 +10,7 @@ import SuMoC.backend.notification.repositories.NotificationRepository; import SuMoC.backend.scheduling.ScheduledTasks; 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; @@ -41,6 +42,7 @@ public class DevController { private final ObjectMapper objectMapper; private final NotificationRepository notificationRepository; private final UserRepository userRepository; + private final UserMapper userMapper; public DevController( ScheduledTasks scheduledTasks, @@ -50,7 +52,7 @@ public class DevController { ForecastService forecastService, FirebaseMessageBuilder firebaseMessageBuilder, ObjectMapper objectMapper, - NotificationRepository notificationRepository, UserRepository userRepository + NotificationRepository notificationRepository, UserRepository userRepository, UserMapper userMapper ) { this.scheduledTasks = scheduledTasks; this.statTableUpdateService = statTableUpdateService; @@ -61,6 +63,7 @@ public class DevController { this.objectMapper = objectMapper; this.notificationRepository = notificationRepository; this.userRepository = userRepository; + this.userMapper = userMapper; } @PostMapping("/trigger-trend-calculation") @@ -107,9 +110,12 @@ public class DevController { 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(TrendDetectionDTO.mockTrendDetectionDTO())) + .data(objectMapper.writeValueAsString(mockDTO)) .user(user) .earliestTimeOfDayToSend(LocalTime.now()) .createdAt(LocalDateTime.now()) 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 0b3140e..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.dto.TrendDetectionDTO; -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(TrendDetectionDTO 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/services/NotificationSchedulerService.java b/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java new file mode 100644 index 0000000..346d8a7 --- /dev/null +++ b/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java @@ -0,0 +1,55 @@ +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); + } +} 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 1715652..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.dto.TrendDetectionDTO; -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/scheduling/ScheduledTasks.java b/src/main/java/SuMoC/backend/scheduling/ScheduledTasks.java index 0546277..21fd388 100644 --- a/src/main/java/SuMoC/backend/scheduling/ScheduledTasks.java +++ b/src/main/java/SuMoC/backend/scheduling/ScheduledTasks.java @@ -2,6 +2,7 @@ package SuMoC.backend.scheduling; import SuMoC.backend.notification.services.NotificationWorker; import SuMoC.backend.trend.services.StatTableUpdateService; +import SuMoC.backend.trend.services.TrendNotificationService; import lombok.RequiredArgsConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -20,18 +21,20 @@ public class ScheduledTasks { private final StatTableUpdateService statTableUpdateService; + private final TrendNotificationService trendNotificationService; + private final NotificationWorker notificationWorker; /** * Calculate weekly mobility stats for all users and generate corresponding notifications. */ - @Scheduled(cron = "#{@schedulingProperties.calculateWeeklyMobilityStats}") - public void scheduleCalculateWeeklyMobilityStats() { + @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); - // TODO generate and queue notifications about new stats being available + 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); } diff --git a/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java b/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java index 8ffbbf3..c1818bf 100644 --- a/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java +++ b/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java @@ -11,7 +11,7 @@ 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 } diff --git a/src/main/java/SuMoC/backend/trend/config/TrendDetectionProperties.java b/src/main/java/SuMoC/backend/trend/config/TrendProperties.java similarity index 55% rename from src/main/java/SuMoC/backend/trend/config/TrendDetectionProperties.java rename to src/main/java/SuMoC/backend/trend/config/TrendProperties.java index 4930a6d..9af84ea 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 = "trend") +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 index eba82e4..f2c0164 100644 --- a/src/main/java/SuMoC/backend/trend/dto/TrendDetectionDTO.java +++ b/src/main/java/SuMoC/backend/trend/dto/TrendDetectionDTO.java @@ -1,7 +1,7 @@ package SuMoC.backend.trend.dto; +import SuMoC.backend.notification.interfaces.Notifieable; import SuMoC.backend.trend.enums.*; -import SuMoC.backend.user.models.User; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -9,8 +9,8 @@ import lombok.Data; @Data @Builder @AllArgsConstructor -public class TrendDetectionDTO { - private User user; +public class TrendDetectionDTO implements Notifieable { + private Long userId; private TrendTimespan timespan; private TrendType type; private StatAttribute attribute; @@ -19,7 +19,7 @@ public class TrendDetectionDTO { public static TrendDetectionDTO mockTrendDetectionDTO() { return TrendDetectionDTO.builder() - .user(null) // Replace with a mock User if needed + .userId(null) // Replace with a mock User if needed .timespan(TrendTimespan.WEEKLY) .type(TrendType.INCREASING) .attribute(StatAttribute.CAR_DISTANCE) diff --git a/src/main/java/SuMoC/backend/trend/services/TrendDetectorService.java b/src/main/java/SuMoC/backend/trend/services/TrendDetectorService.java index 7b6f004..4b777e7 100644 --- a/src/main/java/SuMoC/backend/trend/services/TrendDetectorService.java +++ b/src/main/java/SuMoC/backend/trend/services/TrendDetectorService.java @@ -1,7 +1,7 @@ package SuMoC.backend.trend.services; 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; @@ -22,7 +22,7 @@ public class TrendDetectorService { private final WeeklyMobilityStatsRepository weeklyMobilityStatsRepository; - private final TrendDetectionProperties trendDetectionProperties; + private final TrendProperties trendProperties; public List detectWeeklyTrends(Integer year, Integer weekNumber, StatAttribute attribute) { // Fetch stats for current and previous week @@ -56,18 +56,18 @@ public class TrendDetectorService { if (previousValue != 0) { double percentageChange = ((currentValue - previousValue) / previousValue) * 100.0; - if (percentageChange >= trendDetectionProperties.getPositiveThreshold()) { + if (percentageChange >= trendProperties.getPositiveThreshold()) { detectedTrends.add(new TrendDetectionDTO( - currentStats.getUser(), + currentStats.getUser().getId(), TrendTimespan.WEEKLY, TrendType.INCREASING, StatAttribute.CAR_DISTANCE, DeltaType.PERCENTAGE, percentageChange )); - } else if (percentageChange <= trendDetectionProperties.getNegativeThreshold()) { + } else if (percentageChange <= trendProperties.getNegativeThreshold()) { detectedTrends.add(new TrendDetectionDTO( - previousStats.getUser(), + previousStats.getUser().getId(), TrendTimespan.WEEKLY, TrendType.DECREASING, StatAttribute.CAR_DISTANCE, 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/test/java/SuMoC/backend/trend/services/TrendDetectorServiceTest.java b/src/test/java/SuMoC/backend/trend/services/TrendDetectorServiceTest.java index 2f5c4e3..a271961 100644 --- a/src/test/java/SuMoC/backend/trend/services/TrendDetectorServiceTest.java +++ b/src/test/java/SuMoC/backend/trend/services/TrendDetectorServiceTest.java @@ -1,7 +1,7 @@ package SuMoC.backend.trend.services; 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; @@ -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); @@ -84,7 +84,7 @@ public class TrendDetectorServiceTest { // Verify increasing trend for user1 TrendDetectionDTO user1Trend = detectedTrends.stream() - .filter(t -> t.getUser().getId().equals(user1.getId())) + .filter(t -> t.getUserId().equals(user1.getId())) .findFirst() .orElse(null); assertNotNull(user1Trend, "User 1 should have a detected trend"); @@ -96,7 +96,7 @@ public class TrendDetectorServiceTest { // Verify decreasing trend for user2 TrendDetectionDTO user2Trend = detectedTrends.stream() - .filter(t -> t.getUser().getId().equals(user2.getId())) + .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)"); } From 51c742b74677576a3bfaf7397ed52ce569f1fae4 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Tue, 13 Jan 2026 18:44:12 +0100 Subject: [PATCH 07/61] remove builder from TrendDetectionDTO so that trendConnotation can be calculated in constructor --- .../backend/trend/dto/TrendDetectionDTO.java | 26 ++++++++++--------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/src/main/java/SuMoC/backend/trend/dto/TrendDetectionDTO.java b/src/main/java/SuMoC/backend/trend/dto/TrendDetectionDTO.java index f2c0164..e05b6b3 100644 --- a/src/main/java/SuMoC/backend/trend/dto/TrendDetectionDTO.java +++ b/src/main/java/SuMoC/backend/trend/dto/TrendDetectionDTO.java @@ -2,13 +2,11 @@ package SuMoC.backend.trend.dto; import SuMoC.backend.notification.interfaces.Notifieable; import SuMoC.backend.trend.enums.*; -import lombok.AllArgsConstructor; -import lombok.Builder; import lombok.Data; +import lombok.NoArgsConstructor; @Data -@Builder -@AllArgsConstructor +@NoArgsConstructor public class TrendDetectionDTO implements Notifieable { private Long userId; private TrendTimespan timespan; @@ -16,16 +14,20 @@ public class TrendDetectionDTO implements Notifieable { 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 TrendDetectionDTO.builder() - .userId(null) // Replace with a mock User if needed - .timespan(TrendTimespan.WEEKLY) - .type(TrendType.INCREASING) - .attribute(StatAttribute.CAR_DISTANCE) - .deltaType(DeltaType.ABSOLUTE) - .changeValue(15.0) - .build(); + return new TrendDetectionDTO(null, TrendTimespan.WEEKLY, TrendType.INCREASING, StatAttribute.CAR_DISTANCE, DeltaType.ABSOLUTE, 15.0); } public TrendConnotation getTrendConnotation() { From ce665d143f723637e34193cfd4d67705cdc7241e Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Tue, 13 Jan 2026 18:44:27 +0100 Subject: [PATCH 08/61] add tests for NotificationSchedulerServiceTest --- .../trend/services/TrendMessageGenerator.java | 8 - src/main/resources/application.properties | 2 +- .../NotificationSchedulerServiceTest.java | 248 ++++++++++++++++++ 3 files changed, 249 insertions(+), 9 deletions(-) delete mode 100644 src/main/java/SuMoC/backend/trend/services/TrendMessageGenerator.java create mode 100644 src/test/java/SuMoC/backend/notification/services/NotificationSchedulerServiceTest.java 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/resources/application.properties b/src/main/resources/application.properties index eca34b8..fcc7672 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -21,7 +21,7 @@ trenddetection.positive-threshold=25.0 # Regular trip detection settings #regulartripdetection.detection-algorithm=iterative # FireBase -firebase.config.enabled=true +firebase.config.enabled=false firebase.config.service-account=classpath:firebase-private-key.json # Base URL to external services carta.base-url=https://www.innamoruhr.de/c2 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()); + } +} + From 41f04620bad5d4734fbdbefd0b1c1e17d40e6b3f Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Wed, 14 Jan 2026 14:35:32 +0100 Subject: [PATCH 09/61] added devcontroller test endpoint for sending route_adhoc notification --- .../java/SuMoC/backend/dev/DevController.java | 32 +++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/src/main/java/SuMoC/backend/dev/DevController.java b/src/main/java/SuMoC/backend/dev/DevController.java index f2fca27..8265526 100644 --- a/src/main/java/SuMoC/backend/dev/DevController.java +++ b/src/main/java/SuMoC/backend/dev/DevController.java @@ -7,6 +7,7 @@ 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.routing.dtos.RouteDTO; import SuMoC.backend.scheduling.ScheduledTasks; import SuMoC.backend.trend.dto.TrendDetectionDTO; import SuMoC.backend.trend.services.StatTableUpdateService; @@ -27,6 +28,7 @@ import org.springframework.web.bind.annotation.*; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; +import java.util.List; @RestController @RequestMapping("/dev") @@ -76,9 +78,9 @@ public class DevController { statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(day3WeeksAgo); } - @GetMapping("/test-firebase/{fcm_token}") + @GetMapping("/test-firebase-trend-notification/{fcm_token}") @Operation(description = "Immediately sends a test notification of type TREND to the provided FCM token.") - public ResponseEntity testFirebaseConnection(@PathVariable("fcm_token") @NotNull String fcmToken) { + 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)"); @@ -100,6 +102,32 @@ 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); + // Using TrendDetectionDTO as a placeholder, replace with actual AdhocAlternativeDTO when available + 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()); + } + } + @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() { From ddbf925caf7aa1cbce47e0a81799263decf18ca5 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Wed, 14 Jan 2026 15:34:29 +0100 Subject: [PATCH 10/61] log notification send fail reason in db for easier debugging --- .../java/SuMoC/backend/notification/models/Notification.java | 3 +++ .../backend/notification/services/NotificationSender.java | 3 +-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/SuMoC/backend/notification/models/Notification.java b/src/main/java/SuMoC/backend/notification/models/Notification.java index bc0b5db..52c1719 100644 --- a/src/main/java/SuMoC/backend/notification/models/Notification.java +++ b/src/main/java/SuMoC/backend/notification/models/Notification.java @@ -50,6 +50,9 @@ public class Notification { @Column(nullable = false) private int failedSendAttempts = 0; + @Column + private String lastFailureReason; + @Column(nullable = false) private LocalDateTime createdAt; diff --git a/src/main/java/SuMoC/backend/notification/services/NotificationSender.java b/src/main/java/SuMoC/backend/notification/services/NotificationSender.java index a1af745..ae0ced7 100644 --- a/src/main/java/SuMoC/backend/notification/services/NotificationSender.java +++ b/src/main/java/SuMoC/backend/notification/services/NotificationSender.java @@ -21,7 +21,6 @@ import java.util.logging.Logger; @Service public class NotificationSender { - private final NotificationTokenRepository notificationTokenRepository; private final FirebaseMessageBuilder firebaseMessageBuilder; private final Logger logger = Logger.getLogger(NotificationSender.class.getName()); private final FirebaseMessaging firebaseMessaging; @@ -34,7 +33,6 @@ public class NotificationSender { @Autowired(required = false) FirebaseMessaging firebaseMessaging, NotificationRepository notificationRepository, NotificationProperties notificationProperties ) { - this.notificationTokenRepository = notificationTokenRepository; this.firebaseMessageBuilder = firebaseMessageBuilder; this.firebaseMessaging = firebaseMessaging; this.notificationRepository = notificationRepository; @@ -76,6 +74,7 @@ public class NotificationSender { @Override public void onFailure(Throwable t) { notification.incrementFailedSendAttempts(); + notification.setLastFailureReason(t.getMessage()); if (notification.getFailedSendAttempts() >= notificationProperties.getMaxFailedSendAttempts()) { notification.setStatus(NotificationStatus.FAILED); } From 8ee6992f88d84907c99c3261056e61e43ee4afce Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Wed, 14 Jan 2026 15:34:59 +0100 Subject: [PATCH 11/61] send ad hoc alternative route notifications for recent uploaded trips --- .../NotificationSchedulerService.java | 28 +++++++++ .../services/AdHocSuggestionService.java | 57 +++++++++++++++++-- 2 files changed, 80 insertions(+), 5 deletions(-) diff --git a/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java b/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java index 346d8a7..e5bdbea 100644 --- a/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java +++ b/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java @@ -52,4 +52,32 @@ public class NotificationSchedulerService { 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/suggestion/services/AdHocSuggestionService.java b/src/main/java/SuMoC/backend/suggestion/services/AdHocSuggestionService.java index f6de03c..ad90735 100644 --- a/src/main/java/SuMoC/backend/suggestion/services/AdHocSuggestionService.java +++ b/src/main/java/SuMoC/backend/suggestion/services/AdHocSuggestionService.java @@ -1,16 +1,22 @@ 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.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 @@ -20,6 +26,8 @@ public class AdHocSuggestionService { 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 +35,53 @@ 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 + // TODO we assume default preferences, in the future we should store user preferences and use them here + RoutingPreferencesDTO preferencesDTO = new RoutingPreferencesDTO(); + 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) { From 56e594b625f83b28a0206c5f8ed31ce7e639a315 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Wed, 14 Jan 2026 17:47:35 +0100 Subject: [PATCH 12/61] add tests for regular trip detection algorithm --- .../config/DetectorConfiguration.java | 2 +- .../backend/trend/config/TrendProperties.java | 2 +- src/main/resources/application.properties | 11 +- .../RegularTripDetectionDTOFactory.java | 142 ++++++++++++++++++ .../IterativeClustererTest.java | 85 ++++++++++- 5 files changed, 231 insertions(+), 11 deletions(-) create mode 100644 src/test/java/SuMoC/backend/Factories/RegularTripDetectionDTOFactory.java 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/trend/config/TrendProperties.java b/src/main/java/SuMoC/backend/trend/config/TrendProperties.java index 9af84ea..1595da4 100644 --- a/src/main/java/SuMoC/backend/trend/config/TrendProperties.java +++ b/src/main/java/SuMoC/backend/trend/config/TrendProperties.java @@ -8,7 +8,7 @@ import java.time.LocalTime; @Data @Component -@ConfigurationProperties(prefix = "trend") +@ConfigurationProperties(prefix = "sumoc.trenddetection") public class TrendProperties { /** diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index fcc7672..6c23d93 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -13,19 +13,18 @@ spring.profiles.active=dev spring.jackson.serialization.write-dates-as-timestamps=false # Scheduling settings sumoc.scheduling.run-notification-worker=*/15 * * * * * -# Disabled for development - TODO set reasonable rhythm -sumoc.scheduling.calculate-trend-table-cron=- +sumoc.scheduling.notify-weekly-mobility-stats=1 30 0 * * 1 # Trend detection settings -trenddetection.negative-threshold=-25.0 -trenddetection.positive-threshold=25.0 +sumoc.trenddetection.positive-threshold=-25.0 +sumoc.trenddetection.negative-threshold=-25.0 # Regular trip detection settings #regulartripdetection.detection-algorithm=iterative # 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 nominatim.base-url=http://localhost:6666 meteo.base-url=https://api.open-meteo.com/v1 # Dev debug settings -sumoc.dev.fcm-key=eBnklYXTRNaD7d--7gQy68:APA91bGN00vqYp0LO3Xi5aikDensT7RYYckdIBLUXKdQHphRYPaFQrxYGgnpuEg7AEyLfMtZxkHvi2KEXX-a02DwAR9xC2-qaNacZ3kbR1s0xNpG-N3IYp0 \ No newline at end of file +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..7df273e --- /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 String h3_essen_schuetzenbahn = "8a1fa535568ffff"; + private String h3_essen_hbf = "8a1fa535020ffff"; + private 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/regulartrip/detectionapproaches/IterativeClustererTest.java b/src/test/java/SuMoC/backend/regulartrip/detectionapproaches/IterativeClustererTest.java index 7ce3749..3bcdfac 100644 --- a/src/test/java/SuMoC/backend/regulartrip/detectionapproaches/IterativeClustererTest.java +++ b/src/test/java/SuMoC/backend/regulartrip/detectionapproaches/IterativeClustererTest.java @@ -1,8 +1,87 @@ package SuMoC.backend.regulartrip.detectionapproaches; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.junit.jupiter.MockitoExtension; +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; -@ExtendWith(MockitoExtension.class) +import static org.mockito.Mockito.when; + +@SpringBootTest 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); + } } From b08d9dd22d078a2bf893aee35daed57916ab4add Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Fri, 16 Jan 2026 11:09:30 +0100 Subject: [PATCH 13/61] add code to convert safely between java's and sql indexes for day of week, verify with test --- .../common/converter/DayOfWeekConverter.java | 34 +++++++++ .../SuMoC/backend/trip/TripRepository.java | 23 ++++-- .../backend/Factories/TripTestFactory.java | 37 ++++++++++ .../backend/trip/TripRepositoryTest.java | 70 +++++++++++++++++++ 4 files changed, 159 insertions(+), 5 deletions(-) create mode 100644 src/main/java/SuMoC/backend/common/converter/DayOfWeekConverter.java create mode 100644 src/test/java/SuMoC/backend/Factories/TripTestFactory.java create mode 100644 src/test/java/SuMoC/backend/trip/TripRepositoryTest.java 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/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/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/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()); + } +} From d099909aaba42b840fb1ec24a9e506038007cb22 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Fri, 16 Jan 2026 13:19:19 +0100 Subject: [PATCH 14/61] implement full service chain where scheduled task detects regular trips every day and schedules notifications with better alternatives if available --- .../java/SuMoC/backend/dev/DevController.java | 62 ++++++++++++- .../RegularTripDetectionProperties.java | 2 +- .../dtos/DetectedRegularTripDTO.java | 58 +++++++++++- .../services/RegularTripDetectionService.java | 12 +-- .../routing/services/RoutingService.java | 32 +++++++ .../backend/scheduling/ScheduledTasks.java | 16 ++++ .../scheduling/SchedulingProperties.java | 1 + .../config/AdHocSuggestionProperties.java | 2 +- .../RegularTripSuggestionProperties.java | 17 ++++ .../RegularTripSuggestionService.java | 90 +++++++++++++++++++ .../trip/dtos/RegularTripDetectionDTO.java | 9 +- src/main/resources/application.properties | 6 +- .../RegularTripDetectionDTOFactory.java | 16 ++-- 13 files changed, 299 insertions(+), 24 deletions(-) create mode 100644 src/main/java/SuMoC/backend/suggestion/config/RegularTripSuggestionProperties.java create mode 100644 src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java diff --git a/src/main/java/SuMoC/backend/dev/DevController.java b/src/main/java/SuMoC/backend/dev/DevController.java index 8265526..0c67871 100644 --- a/src/main/java/SuMoC/backend/dev/DevController.java +++ b/src/main/java/SuMoC/backend/dev/DevController.java @@ -1,14 +1,17 @@ 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; @@ -28,6 +31,7 @@ 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 @@ -45,6 +49,8 @@ public class DevController { private final NotificationRepository notificationRepository; private final UserRepository userRepository; private final UserMapper userMapper; + private final H3Service h3Service; + private final RegularTripSuggestionService regularTripSuggestionService; public DevController( ScheduledTasks scheduledTasks, @@ -54,7 +60,7 @@ public class DevController { ForecastService forecastService, FirebaseMessageBuilder firebaseMessageBuilder, ObjectMapper objectMapper, - NotificationRepository notificationRepository, UserRepository userRepository, UserMapper userMapper + NotificationRepository notificationRepository, UserRepository userRepository, UserMapper userMapper, H3Service h3Service, RegularTripSuggestionService regularTripSuggestionService ) { this.scheduledTasks = scheduledTasks; this.statTableUpdateService = statTableUpdateService; @@ -66,6 +72,8 @@ public class DevController { this.notificationRepository = notificationRepository; this.userRepository = userRepository; this.userMapper = userMapper; + this.h3Service = h3Service; + this.regularTripSuggestionService = regularTripSuggestionService; } @PostMapping("/trigger-trend-calculation") @@ -112,7 +120,6 @@ public class DevController { try { Notification notification = new Notification(); notification.setType(NotificationType.ADHOC_ALTERNATIVE); - // Using TrendDetectionDTO as a placeholder, replace with actual AdhocAlternativeDTO when available List mockRoutes = List.of(RouteDTO.getMockRouteDTO(), RouteDTO.getMockRouteDTO()); notification.setData(objectMapper.writeValueAsString(mockRoutes)); @@ -128,6 +135,57 @@ public class DevController { } } + @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() { 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/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 21fd388..09ff888 100644 --- a/src/main/java/SuMoC/backend/scheduling/ScheduledTasks.java +++ b/src/main/java/SuMoC/backend/scheduling/ScheduledTasks.java @@ -1,6 +1,7 @@ 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; @@ -23,6 +24,8 @@ public class ScheduledTasks { private final TrendNotificationService trendNotificationService; + private final RegularTripSuggestionService regularTripSuggestionService; + private final NotificationWorker notificationWorker; /** @@ -65,4 +68,17 @@ public class ScheduledTasks { 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 c1818bf..cce5861 100644 --- a/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java +++ b/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java @@ -14,4 +14,5 @@ public class SchedulingProperties { 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/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/RegularTripSuggestionService.java b/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java new file mode 100644 index 0000000..df69c8f --- /dev/null +++ b/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java @@ -0,0 +1,90 @@ +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.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 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); + // TODO for now we use default preferences, in the future we should store user preferences and use them here + RoutingPreferencesDTO preferencesDTO = new RoutingPreferencesDTO(); + + // 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/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/resources/application.properties b/src/main/resources/application.properties index 6c23d93..e788bbe 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -11,14 +11,14 @@ 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 -# Scheduling settings +# 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 sumoc.trenddetection.positive-threshold=-25.0 sumoc.trenddetection.negative-threshold=-25.0 -# Regular trip detection settings -#regulartripdetection.detection-algorithm=iterative # FireBase firebase.config.enabled=true firebase.config.service-account=classpath:firebase-private-key.json diff --git a/src/test/java/SuMoC/backend/Factories/RegularTripDetectionDTOFactory.java b/src/test/java/SuMoC/backend/Factories/RegularTripDetectionDTOFactory.java index 7df273e..7b2ae51 100644 --- a/src/test/java/SuMoC/backend/Factories/RegularTripDetectionDTOFactory.java +++ b/src/test/java/SuMoC/backend/Factories/RegularTripDetectionDTOFactory.java @@ -18,9 +18,9 @@ public class RegularTripDetectionDTOFactory { private final Random random = new Random(); - private String h3_essen_schuetzenbahn = "8a1fa535568ffff"; - private String h3_essen_hbf = "8a1fa535020ffff"; - private String h3_essen_west = "8a1fa5356a5ffff"; + 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; @@ -29,7 +29,7 @@ public class RegularTripDetectionDTOFactory { public List regularFromAtoBwithOverlappingAndPreferredTimeWindows() { List dtos = new ArrayList<>(); - for (int i=0; i < 5; i++) { + for (int i = 0; i < 5; i++) { var startDateTime = LocalDateTime.now().minusMinutes(20 * i).minusWeeks(i); var endDateTime = startDateTime.plusMinutes(15); @@ -65,7 +65,7 @@ public class RegularTripDetectionDTOFactory { public List regularFromAtoB(int size) { List dtos = new ArrayList<>(); - for (int i=0; i < size; i++) { + for (int i = 0; i < size; i++) { var startDateTime = LocalDateTime.now().minusMinutes(30).minusWeeks(i); var endDateTime = startDateTime.plusMinutes(15); @@ -87,7 +87,7 @@ public class RegularTripDetectionDTOFactory { public List regularFromAtoBwithNeighbourCells(int size) { List dtos = new ArrayList<>(); - for (int i=0; i < size; i++) { + for (int i = 0; i < size; i++) { var startDateTime = LocalDateTime.now().minusMinutes(30).minusWeeks(i); var endDateTime = startDateTime.plusMinutes(15); @@ -98,7 +98,7 @@ public class RegularTripDetectionDTOFactory { 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 + endCell = h3_essen_hbf; // one time use the original cell - simulates some noise } dtos.add(RegularTripDetectionDTO.builder() @@ -119,7 +119,7 @@ public class RegularTripDetectionDTOFactory { public List nonRegularFromAtoC() { List dtos = new ArrayList<>(); - for (int i=0; i < 5; i++) { + for (int i = 0; i < 5; i++) { var startDateTime = LocalDateTime.now().minusMinutes(30).minusDays(i); var endDateTime = startDateTime.plusMinutes(15); From 9f854ce3ab79baf25c5dcc11f6dd7786f3e792a5 Mon Sep 17 00:00:00 2001 From: Lukas Laaser Date: Sat, 17 Jan 2026 18:04:06 +0100 Subject: [PATCH 15/61] test --- docker-compose.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-compose.yml b/docker-compose.yml index ce43a3b..989fcad 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,7 +8,7 @@ services: image: backend:latest container_name: sumoc-backend ports: - - "8080:8080" + - "80:8080" env_file: - .env depends_on: From 7098fbe8cc2b66d40d2d1f52c6063166480cc3fb Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Sat, 17 Jan 2026 18:32:32 +0100 Subject: [PATCH 16/61] revert to 8080 --- docker-compose.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-compose.yml b/docker-compose.yml index 989fcad..ce43a3b 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,7 +8,7 @@ services: image: backend:latest container_name: sumoc-backend ports: - - "80:8080" + - "8080:8080" env_file: - .env depends_on: From c8410a8231f5ba09bba0bcbc337622b2c9feaaf7 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Tue, 20 Jan 2026 10:59:06 +0100 Subject: [PATCH 17/61] update jenkinsfile to reset db --- Jenkinsfile | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Jenkinsfile b/Jenkinsfile index d0f16ca..5a550eb 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -22,6 +22,10 @@ node('built-in') { sh 'scp -i $KEYFILE docker-compose.yml pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE docker-load.sh pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE -r docker_images pg-sumoc@apps-dev.nes:~' + echo "Resetting database on server ..." + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose stop db"' + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"' + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm sumoc-backend_postgres_data"' echo "Load docker images on server ..." sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"' echo "Restarting docker containers on server ..." From 2f88a611b8b021887d917d0705a495e2ed25deec Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Tue, 20 Jan 2026 11:03:08 +0100 Subject: [PATCH 18/61] update jenkinsfile - no db reset --- Jenkinsfile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 5a550eb..8218d4b 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -22,10 +22,10 @@ node('built-in') { sh 'scp -i $KEYFILE docker-compose.yml pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE docker-load.sh pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE -r docker_images pg-sumoc@apps-dev.nes:~' - echo "Resetting database on server ..." - sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose stop db"' - sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"' - sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm sumoc-backend_postgres_data"' +// echo "Resetting database on server ..." +// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose stop db"' +// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"' +// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm sumoc-backend_postgres_data"' echo "Load docker images on server ..." sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"' echo "Restarting docker containers on server ..." From a78ebbfbb59d23ac2dd0414f13cc7df63281cf33 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Tue, 20 Jan 2026 11:07:35 +0100 Subject: [PATCH 19/61] create separate docker compose for local full dockerized execution --- docker-compose.local.yml | 41 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 docker-compose.local.yml diff --git a/docker-compose.local.yml b/docker-compose.local.yml new file mode 100644 index 0000000..5b78876 --- /dev/null +++ b/docker-compose.local.yml @@ -0,0 +1,41 @@ +volumes: + nominatim-data: + postgres_data: + +services: + backend: + build: . + image: backend:latest + container_name: sumoc-backend + ports: + - "8080:8080" + env_file: + - .env + depends_on: + - db + restart: unless-stopped + + db: + image: postgres:16.2-alpine + container_name: sumoc_db + environment: + - POSTGRES_USER=postgres + - POSTGRES_PASSWORD=admin + - POSTGRES_DB=sumoc + volumes: + - postgres_data:/var/lib/postgresql/data + ports: + - "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" From f3bd4dddc2a6e57d1fcda755b3182d0d3bf2a26c Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Tue, 20 Jan 2026 11:07:50 +0100 Subject: [PATCH 20/61] switch to folders for volumes --- docker-compose.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index ce43a3b..74fc86c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -23,7 +23,7 @@ services: - POSTGRES_PASSWORD=admin - POSTGRES_DB=sumoc volumes: - - postgres_data:/var/lib/postgresql/data + - ./postgres_data:/var/lib/postgresql/data ports: - "5432:5432" restart: always @@ -35,7 +35,7 @@ services: PBF_URL: https://download.geofabrik.de/europe/germany/nordrhein-westfalen-latest.osm.pbf REPLICATION_ENABLED: false volumes: - - nominatim-data:/var/lib/postgresql/14/main + - ./nominatim-data:/var/lib/postgresql/14/main restart: unless-stopped ports: - "6666:8080" From 2b9ce78e1c52132a565273d7c19e3f1314317af0 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Wed, 21 Jan 2026 10:27:23 +0100 Subject: [PATCH 21/61] switch to carta for geocoding but keep docker nominatim as option in case we want to use it --- docker-compose.yml | 22 ++--- .../geocoding/CartaLocationClient.java | 83 +++++++++++++++++++ .../geocoding/CartaLocationResponse.java | 22 +++++ .../backend/geocoding/GeoCodingService.java | 15 ++-- .../backend/geocoding/GeocodingClient.java | 7 ++ .../backend/geocoding/GeocodingConfig.java | 41 +++++++++ .../geocoding/GeocodingProperties.java | 21 +++++ .../backend/geocoding/GeocodingResponse.java | 9 ++ .../NominatimClient.java | 16 ++-- .../ReverseResponse.java | 3 +- .../nominatim/NominatimClientConfig.java | 18 ---- .../nominatim/NominatimProperties.java | 9 -- src/main/resources/application.properties | 5 +- 13 files changed, 216 insertions(+), 55 deletions(-) create mode 100644 src/main/java/SuMoC/backend/geocoding/CartaLocationClient.java create mode 100644 src/main/java/SuMoC/backend/geocoding/CartaLocationResponse.java create mode 100644 src/main/java/SuMoC/backend/geocoding/GeocodingClient.java create mode 100644 src/main/java/SuMoC/backend/geocoding/GeocodingConfig.java create mode 100644 src/main/java/SuMoC/backend/geocoding/GeocodingProperties.java create mode 100644 src/main/java/SuMoC/backend/geocoding/GeocodingResponse.java rename src/main/java/SuMoC/backend/{nominatim => geocoding}/NominatimClient.java (57%) rename src/main/java/SuMoC/backend/{nominatim => geocoding}/ReverseResponse.java (92%) delete mode 100644 src/main/java/SuMoC/backend/nominatim/NominatimClientConfig.java delete mode 100644 src/main/java/SuMoC/backend/nominatim/NominatimProperties.java diff --git a/docker-compose.yml b/docker-compose.yml index ce43a3b..3675edc 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -28,14 +28,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/geocoding/CartaLocationClient.java b/src/main/java/SuMoC/backend/geocoding/CartaLocationClient.java new file mode 100644 index 0000000..9031f3d --- /dev/null +++ b/src/main/java/SuMoC/backend/geocoding/CartaLocationClient.java @@ -0,0 +1,83 @@ +package SuMoC.backend.geocoding; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +import java.util.HashMap; +import java.util.Map; + +public class CartaLocationClient implements GeocodingClient { + + private static final Logger logger = LoggerFactory.getLogger(CartaLocationClient.class); + + private final WebClient cartaLocationClient; + + public CartaLocationClient(WebClient cartaLocationClient) { + this.cartaLocationClient = cartaLocationClient; + } + + @Override + public Mono reverse(double lat, double lon) { + String query = lat + "," + lon; + logger.debug("Calling Carta location API with query: {}, type: BUILDING, limit: 3", query); + + return cartaLocationClient.get() + .uri(uriBuilder -> { + var uri = uriBuilder.path("/location/search") + .queryParam("q", query) + .queryParam("type", "BUILDING") + .queryParam("limit", 3) + .build(); + logger.debug("Full Carta location API URL: {}", uri); + return uri; + }) + .retrieve() + .bodyToMono(CartaLocationResponse[].class) + .doOnNext(responses -> logger.debug("Received {} results from Carta location API", + responses != null ? responses.length : 0)) + .map(responses -> { + if (responses == null || responses.length == 0) { + logger.error("Carta location API returned empty response for coordinates: lat={}, lon={}", lat, lon); + return new GeocodingResponse(null); + } + logger.debug("Using first result: {}", responses[0]); + return mapToGeocodingResponse(responses[0]); + }) + .onErrorResume(error -> { + logger.error("Error calling Carta location API for coordinates: lat={}, lon={}", lat, lon, error); + return Mono.just(new GeocodingResponse(null)); + }); + } + + private GeocodingResponse mapToGeocodingResponse(CartaLocationResponse response) { + Map addressMap = new HashMap<>(); + + // Map Carta fields to Nominatim-style address format + if (response.building() != null) { + addressMap.put("house_number", response.building()); + } + if (response.street() != null) { + addressMap.put("road", response.street()); + } + if (response.suburb() != null) { + addressMap.put("suburb", response.suburb()); + } + if (response.city() != null) { + addressMap.put("city", response.city()); + } + if (response.state() != null) { + addressMap.put("state", response.state()); + } + if (response.postcode() != null) { + addressMap.put("postcode", response.postcode()); + } + if (response.country() != null) { + addressMap.put("country", response.country()); + } + + return new GeocodingResponse(addressMap); + } +} + diff --git a/src/main/java/SuMoC/backend/geocoding/CartaLocationResponse.java b/src/main/java/SuMoC/backend/geocoding/CartaLocationResponse.java new file mode 100644 index 0000000..c9c4c6b --- /dev/null +++ b/src/main/java/SuMoC/backend/geocoding/CartaLocationResponse.java @@ -0,0 +1,22 @@ +package SuMoC.backend.geocoding; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public record CartaLocationResponse( + Double longitude, + Double latitude, + String country, + String state, + String county, + String city, + String suburb, + String neighborhood, + String locality, + String street, + String building, + String postcode, + String name +) { +} + diff --git a/src/main/java/SuMoC/backend/geocoding/GeoCodingService.java b/src/main/java/SuMoC/backend/geocoding/GeoCodingService.java index b2eaa2b..3322afa 100644 --- a/src/main/java/SuMoC/backend/geocoding/GeoCodingService.java +++ b/src/main/java/SuMoC/backend/geocoding/GeoCodingService.java @@ -1,26 +1,27 @@ package SuMoC.backend.geocoding; -import SuMoC.backend.nominatim.NominatimClient; -import SuMoC.backend.nominatim.ReverseResponse; import org.springframework.stereotype.Service; import reactor.core.publisher.Mono; @Service public class GeoCodingService { - private final NominatimClient nominatimClient; + private final GeocodingClient geocodingClient; - public GeoCodingService(NominatimClient nominatimClient) { - this.nominatimClient = nominatimClient; + public GeoCodingService(GeocodingClient geocodingClient) { + this.geocodingClient = geocodingClient; } public Mono getAddress(double lat, double lon) { - return nominatimClient.reverse(lat, lon) + return geocodingClient.reverse(lat, lon) .map(this::mapToAddressDTO); } - private AddressDTO mapToAddressDTO(ReverseResponse response) { + private AddressDTO mapToAddressDTO(GeocodingResponse response) { var addressMap = response.address(); + if (addressMap == null) { + return new AddressDTO(null, null, null, null, null, null, null, null, null, null); + } return new AddressDTO( addressMap.get("house_number"), addressMap.get("road"), diff --git a/src/main/java/SuMoC/backend/geocoding/GeocodingClient.java b/src/main/java/SuMoC/backend/geocoding/GeocodingClient.java new file mode 100644 index 0000000..5a9cd17 --- /dev/null +++ b/src/main/java/SuMoC/backend/geocoding/GeocodingClient.java @@ -0,0 +1,7 @@ +package SuMoC.backend.geocoding; + +import reactor.core.publisher.Mono; + +public interface GeocodingClient { + Mono reverse(double lat, double lon); +} diff --git a/src/main/java/SuMoC/backend/geocoding/GeocodingConfig.java b/src/main/java/SuMoC/backend/geocoding/GeocodingConfig.java new file mode 100644 index 0000000..65b7484 --- /dev/null +++ b/src/main/java/SuMoC/backend/geocoding/GeocodingConfig.java @@ -0,0 +1,41 @@ +package SuMoC.backend.geocoding; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.reactive.function.client.WebClient; + +@Configuration +@EnableConfigurationProperties(GeocodingProperties.class) +public class GeocodingConfig { + + @Bean + @ConditionalOnProperty(name = "geocoding.provider", havingValue = "docker", matchIfMissing = true) + public WebClient nominatimWebClient(GeocodingProperties properties) { + return WebClient.builder() + .baseUrl(properties.nominatim().baseUrl()) + .build(); + } + + @Bean(name = "geocodingClient") + @ConditionalOnProperty(name = "geocoding.provider", havingValue = "docker", matchIfMissing = true) + public GeocodingClient nominatimClient(WebClient nominatimWebClient) { + return new NominatimClient(nominatimWebClient); + } + + @Bean + @ConditionalOnProperty(name = "geocoding.provider", havingValue = "carta") + public WebClient cartaLocationWebClient(GeocodingProperties properties) { + return WebClient.builder() + .baseUrl(properties.carta().baseUrl()) + .build(); + } + + @Bean(name = "geocodingClient") + @ConditionalOnProperty(name = "geocoding.provider", havingValue = "carta") + public GeocodingClient cartaLocationClient(WebClient cartaLocationWebClient) { + return new CartaLocationClient(cartaLocationWebClient); + } +} + diff --git a/src/main/java/SuMoC/backend/geocoding/GeocodingProperties.java b/src/main/java/SuMoC/backend/geocoding/GeocodingProperties.java new file mode 100644 index 0000000..0c7a93a --- /dev/null +++ b/src/main/java/SuMoC/backend/geocoding/GeocodingProperties.java @@ -0,0 +1,21 @@ +package SuMoC.backend.geocoding; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "geocoding") +public record GeocodingProperties( + String provider, + NominatimConfig nominatim, + CartaConfig carta +) { + public record NominatimConfig( + String baseUrl + ) { + } + + public record CartaConfig( + String baseUrl + ) { + } +} + diff --git a/src/main/java/SuMoC/backend/geocoding/GeocodingResponse.java b/src/main/java/SuMoC/backend/geocoding/GeocodingResponse.java new file mode 100644 index 0000000..e6ee55e --- /dev/null +++ b/src/main/java/SuMoC/backend/geocoding/GeocodingResponse.java @@ -0,0 +1,9 @@ +package SuMoC.backend.geocoding; + +import java.util.Map; + +public record GeocodingResponse( + Map address +) { +} + diff --git a/src/main/java/SuMoC/backend/nominatim/NominatimClient.java b/src/main/java/SuMoC/backend/geocoding/NominatimClient.java similarity index 57% rename from src/main/java/SuMoC/backend/nominatim/NominatimClient.java rename to src/main/java/SuMoC/backend/geocoding/NominatimClient.java index 1042c7e..9ce9093 100644 --- a/src/main/java/SuMoC/backend/nominatim/NominatimClient.java +++ b/src/main/java/SuMoC/backend/geocoding/NominatimClient.java @@ -1,20 +1,18 @@ -package SuMoC.backend.nominatim; +package SuMoC.backend.geocoding; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; -@Service -public class NominatimClient { +public class NominatimClient implements GeocodingClient { private final WebClient nominatimClient; - public NominatimClient(@Qualifier("nominatimWebClient") WebClient nominatimClient) { + public NominatimClient(WebClient nominatimClient) { this.nominatimClient = nominatimClient; } - public Mono reverse(double lat, double lon) { + @Override + public Mono reverse(double lat, double lon) { return nominatimClient.get() .uri(uriBuilder -> uriBuilder.path("/reverse") .queryParam("lat", lat) @@ -22,6 +20,8 @@ public class NominatimClient { .queryParam("format", "jsonv2") .build()) .retrieve() - .bodyToMono(ReverseResponse.class); + .bodyToMono(ReverseResponse.class) + .map(response -> new GeocodingResponse(response.address())); } } + diff --git a/src/main/java/SuMoC/backend/nominatim/ReverseResponse.java b/src/main/java/SuMoC/backend/geocoding/ReverseResponse.java similarity index 92% rename from src/main/java/SuMoC/backend/nominatim/ReverseResponse.java rename to src/main/java/SuMoC/backend/geocoding/ReverseResponse.java index f1ce461..69d714b 100644 --- a/src/main/java/SuMoC/backend/nominatim/ReverseResponse.java +++ b/src/main/java/SuMoC/backend/geocoding/ReverseResponse.java @@ -1,4 +1,4 @@ -package SuMoC.backend.nominatim; +package SuMoC.backend.geocoding; import com.fasterxml.jackson.annotation.JsonProperty; @@ -15,3 +15,4 @@ public record ReverseResponse( @JsonProperty("address") Map address ) { } + diff --git a/src/main/java/SuMoC/backend/nominatim/NominatimClientConfig.java b/src/main/java/SuMoC/backend/nominatim/NominatimClientConfig.java deleted file mode 100644 index fd6066b..0000000 --- a/src/main/java/SuMoC/backend/nominatim/NominatimClientConfig.java +++ /dev/null @@ -1,18 +0,0 @@ -package SuMoC.backend.nominatim; - -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.reactive.function.client.WebClient; - -@Configuration -@EnableConfigurationProperties(NominatimProperties.class) -public class NominatimClientConfig { - - @Bean - public WebClient nominatimWebClient(NominatimProperties properties) { - return WebClient.builder() - .baseUrl(properties.baseUrl()) - .build(); - } -} diff --git a/src/main/java/SuMoC/backend/nominatim/NominatimProperties.java b/src/main/java/SuMoC/backend/nominatim/NominatimProperties.java deleted file mode 100644 index 12a6653..0000000 --- a/src/main/java/SuMoC/backend/nominatim/NominatimProperties.java +++ /dev/null @@ -1,9 +0,0 @@ -package SuMoC.backend.nominatim; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -@ConfigurationProperties(prefix = "nominatim") -public record NominatimProperties( - String baseUrl -) { -} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 8d8181f..bc4a192 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -23,5 +23,8 @@ firebase.config.enabled=false firebase.config.service-account=classpath:firebase-private-key.json # Base URL to external services carta.base-url=https://www.innamoruhr.de/c2 -nominatim.base-url=http://localhost:6666 +# Geocoding configuration +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 From 3a1752573ec607642c17a49e7068d4279ea27ac9 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Wed, 21 Jan 2026 10:34:13 +0100 Subject: [PATCH 22/61] merge fixes --- docker-compose.dev.yml | 22 ++++++------ .../java/SuMoC/backend/user/models/User.java | 35 +++++++++++++------ 2 files changed, 36 insertions(+), 21 deletions(-) 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/user/models/User.java b/src/main/java/SuMoC/backend/user/models/User.java index dfdd4ab..bf99b70 100644 --- a/src/main/java/SuMoC/backend/user/models/User.java +++ b/src/main/java/SuMoC/backend/user/models/User.java @@ -1,13 +1,16 @@ package SuMoC.backend.user.models; import SuMoC.backend.gamification.badges.models.UserBadge; +import SuMoC.backend.notification.models.NotificationToken; 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,6 +50,7 @@ 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")) @@ -57,15 +61,14 @@ public class User { @JoinColumn(name = "id", referencedColumnName = "user_id") private NotificationToken notificationToken; - public User() { - } @OneToMany(mappedBy = "user", cascade = CascadeType.ALL) private Set badges = new HashSet<>(); @OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true) private StatsList statsList; - public User() {} + 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; @@ -168,15 +171,27 @@ 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; + } } From c70059b3663a2ef39f65c72d65ad61854ec9cdcf Mon Sep 17 00:00:00 2001 From: Elias Harb Date: Tue, 20 Jan 2026 00:16:25 +0100 Subject: [PATCH 23/61] Badges and states added --- .../gamification/badges/BadgeController.java | 25 +++++++- .../gamification/badges/BadgeService.java | 3 +- .../user/controller/UserController.java | 36 ++++++++++- .../backend/user/dtos/AddStatRequestDTO.java | 32 ++++++++++ .../SuMoC/backend/user/dtos/StatScope.java | 8 +++ .../backend/user/stats/StatsService.java | 60 +++++++++++++++++++ .../user/service/BadgeServiceTest.java | 4 +- 7 files changed, 163 insertions(+), 5 deletions(-) create mode 100644 src/main/java/SuMoC/backend/user/dtos/AddStatRequestDTO.java create mode 100644 src/main/java/SuMoC/backend/user/dtos/StatScope.java diff --git a/src/main/java/SuMoC/backend/gamification/badges/BadgeController.java b/src/main/java/SuMoC/backend/gamification/badges/BadgeController.java index 33539d1..50d14d5 100644 --- a/src/main/java/SuMoC/backend/gamification/badges/BadgeController.java +++ b/src/main/java/SuMoC/backend/gamification/badges/BadgeController.java @@ -1,6 +1,9 @@ package SuMoC.backend.gamification.badges; import SuMoC.backend.gamification.badges.models.Badge; +import SuMoC.backend.gamification.badges.models.UserBadgeDTO; +import SuMoC.backend.user.models.User; +import SuMoC.backend.user.service.UserService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; @@ -24,7 +27,6 @@ public class BadgeController { } - @Operation(summary = "Create a new badge") @ApiResponses(value = { @ApiResponse(responseCode = "201", description = "Badge created successfully"), @@ -88,4 +90,25 @@ public class BadgeController { List badges = badgeService.getAllBadges(); return ResponseEntity.status(HttpStatus.OK).body(badges); } + + @Operation(summary = "Get Badges by user") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Badges retrieved successfully"), + @ApiResponse(responseCode = "404", description = "No badges found for user") + }) + @GetMapping("/getBadges/{userId}") + public ResponseEntity> getBadgesByUser(@PathVariable("userId") Long userId) { + List badges = badgeService.getUserBadges(userId); + return ResponseEntity.ok(badges); + } + + @Operation(summary = "Check badges for current user and award newly unlocked ones") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Check successful") + }) + @PostMapping("/checkBadgeAndAward") + public ResponseEntity checkAndAwardBadges() { + badgeService.checkAndAwardBadges(); + return ResponseEntity.ok().build(); + } } diff --git a/src/main/java/SuMoC/backend/gamification/badges/BadgeService.java b/src/main/java/SuMoC/backend/gamification/badges/BadgeService.java index 3c6b66e..330ad63 100644 --- a/src/main/java/SuMoC/backend/gamification/badges/BadgeService.java +++ b/src/main/java/SuMoC/backend/gamification/badges/BadgeService.java @@ -44,7 +44,8 @@ public class BadgeService { } - public void checkAndAwardBadges(User user) { + public void checkAndAwardBadges() { + User user = currentUser.get(); List badges = badgeRepository.findAll(); for (Badge badge : badges) { diff --git a/src/main/java/SuMoC/backend/user/controller/UserController.java b/src/main/java/SuMoC/backend/user/controller/UserController.java index 34b3566..d797d6c 100644 --- a/src/main/java/SuMoC/backend/user/controller/UserController.java +++ b/src/main/java/SuMoC/backend/user/controller/UserController.java @@ -1,15 +1,20 @@ package SuMoC.backend.user.controller; import SuMoC.backend.security.dtos.LoginResponseDTO; +import SuMoC.backend.user.dtos.AddStatRequestDTO; import SuMoC.backend.user.dtos.MaximalUserDTO; import SuMoC.backend.user.dtos.MinimalUserDTO; +import SuMoC.backend.user.dtos.StatScope; import SuMoC.backend.user.enums.VisibilityPrivacy; import SuMoC.backend.user.service.UserService; +import SuMoC.backend.user.stats.StatsService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; +import jakarta.annotation.security.RolesAllowed; +import jakarta.validation.Valid; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import org.springframework.beans.factory.annotation.Autowired; @@ -23,10 +28,12 @@ import org.springframework.web.bind.annotation.*; @RequestMapping("/user") public class UserController { private final UserService userService; + private final StatsService statsService; @Autowired - public UserController(UserService userService) { + public UserController(UserService userService, StatsService statsService) { this.userService = userService; + this.statsService = statsService; } @Operation(summary = "Nutzer fragt ein fremdes Nutzerprofil an", description = "Ein Nutzer kann das Profil eines anderen Nutzers anfragen, um dessen öffentliche Informationen einzusehen.") @@ -141,4 +148,31 @@ public class UserController { this.userService.setVisibilityPrivacy(visibilityPrivacy); return ResponseEntity.ok().build(); } + + @Operation(summary = "Add stats to the current user", + description = "Adds a value to a stat field for the current user. Optionally checks and awards badges afterwards.") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Stats updated successfully"), + @ApiResponse(responseCode = "400", description = "Invalid stat field / invalid input", + content = @Content(mediaType = "application/json")), + @ApiResponse(responseCode = "403", description = "Not authorized", + content = @Content(mediaType = "application/json")) + }) + @RolesAllowed({"USER", "ADMIN"}) + @PostMapping("/stats/add") + public ResponseEntity addStats(@RequestBody @Valid AddStatRequestDTO body) { + + StatScope scope = body.getScope(); + boolean awardBadges = body.getAwardBadges() == null || body.getAwardBadges(); + + this.statsService.addStatsToCurrentUser( + body.getStat(), + body.getValue(), + scope, + awardBadges + ); + + return ResponseEntity.ok().build(); + } + } diff --git a/src/main/java/SuMoC/backend/user/dtos/AddStatRequestDTO.java b/src/main/java/SuMoC/backend/user/dtos/AddStatRequestDTO.java new file mode 100644 index 0000000..fb7cafc --- /dev/null +++ b/src/main/java/SuMoC/backend/user/dtos/AddStatRequestDTO.java @@ -0,0 +1,32 @@ +package SuMoC.backend.user.dtos; + +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; + +public class AddStatRequestDTO { + + @NotBlank + private String stat; + + @NotNull + @Min(0) + private Long value; + + private StatScope scope; + + private Boolean awardBadges; + + public String getStat() { return stat; } + public void setStat(String stat) { this.stat = stat; } + + public Long getValue() { return value; } + public void setValue(Long value) { this.value = value; } + + + public Boolean getAwardBadges() { return awardBadges; } + public void setAwardBadges(Boolean awardBadges) { this.awardBadges = awardBadges; } + public StatScope getScope() { return scope; } + public void setScope(StatScope scope) { this.scope = scope; } +} + diff --git a/src/main/java/SuMoC/backend/user/dtos/StatScope.java b/src/main/java/SuMoC/backend/user/dtos/StatScope.java new file mode 100644 index 0000000..e9b9614 --- /dev/null +++ b/src/main/java/SuMoC/backend/user/dtos/StatScope.java @@ -0,0 +1,8 @@ +package SuMoC.backend.user.dtos; + +public enum StatScope { + TOTAL, + MONTHLY, + WEEKLY, + ALL +} diff --git a/src/main/java/SuMoC/backend/user/stats/StatsService.java b/src/main/java/SuMoC/backend/user/stats/StatsService.java index 267b33a..04c2128 100644 --- a/src/main/java/SuMoC/backend/user/stats/StatsService.java +++ b/src/main/java/SuMoC/backend/user/stats/StatsService.java @@ -1,16 +1,35 @@ package SuMoC.backend.user.stats; import SuMoC.backend.gamification.Timeframe; +import SuMoC.backend.gamification.badges.BadgeService; +import SuMoC.backend.user.dtos.StatScope; +import SuMoC.backend.user.models.User; import SuMoC.backend.user.repository.UserRepository; +import SuMoC.backend.user.service.CurrentUserService; +import jakarta.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; +import org.springframework.web.server.ResponseStatusException; + +import java.util.Set; @Service public class StatsService { @Autowired private UserRepository userRepository; + private final BadgeService badgeService; + private final CurrentUserService currentUserService; + + public StatsService(CurrentUserService currentUserService, + UserRepository userRepository, + BadgeService badgeService) { + this.currentUserService = currentUserService; + this.userRepository = userRepository; + this.badgeService = badgeService; + } @Scheduled(cron = "0 0 0 ? * MON") public void resetWeeklyStats() { @@ -29,4 +48,45 @@ public class StatsService { System.out.println("###### Monthly stats have been reset. ######"); } + + private static final Set ALLOWED_STATS = Set.of( + "XP", + "CO2_SAVED", + "KM_CYCLED", + "KM_WALKED", + "KM_PUBLIC_TRANSPORT", + "KM_DRIVEN" + ); + + @Transactional + public void addStatsToCurrentUser(String statField, long value, StatScope scope, boolean awardBadges) { + if (!ALLOWED_STATS.contains(statField)) { + throw new ResponseStatusException( + HttpStatus.BAD_REQUEST, + "Unknown stat field: " + statField + " (allowed: " + ALLOWED_STATS + ")" + ); + } + + User user = currentUserService.get(); + + + if (user.getStats() == null) { + user.setStats(new StatsList(user)); + } + + StatScope effectiveScope = (scope == null) ? StatScope.ALL : scope; + + switch (effectiveScope) { + case ALL -> user.getStats().addToAllStats(statField, value); + case TOTAL -> user.getStats().addToStat(Timeframe.TOTAL, statField, value); + case MONTHLY -> user.getStats().addToStat(Timeframe.MONTHLY, statField, value); + case WEEKLY -> user.getStats().addToStat(Timeframe.WEEKLY, statField, value); + } + + userRepository.save(user); + + if (awardBadges) { + badgeService.checkAndAwardBadges(); + } + } } diff --git a/src/test/java/SuMoC/backend/user/service/BadgeServiceTest.java b/src/test/java/SuMoC/backend/user/service/BadgeServiceTest.java index 1b2f4a3..7ec761f 100644 --- a/src/test/java/SuMoC/backend/user/service/BadgeServiceTest.java +++ b/src/test/java/SuMoC/backend/user/service/BadgeServiceTest.java @@ -203,7 +203,7 @@ public class BadgeServiceTest { // Award first Badge sender.getStats().addToAllStats("XP", 50); - badgeService.checkAndAwardBadges(sender); + badgeService.checkAndAwardBadges(); badgeList = badgeService.getUserBadges(sender.getId()); assertNotNull(badgeList); @@ -211,7 +211,7 @@ public class BadgeServiceTest { // Raise XP and award two more sender.getStats().addToAllStats("XP", 20); - badgeService.checkAndAwardBadges(sender); + badgeService.checkAndAwardBadges(); badgeList = badgeService.getUserBadges(sender.getId()); assertNotNull(badgeList); From 72828c9a0d46f2bf12723863a24f968504cc5265 Mon Sep 17 00:00:00 2001 From: Elias Harb Date: Tue, 20 Jan 2026 00:42:26 +0100 Subject: [PATCH 24/61] added MobilityScore --- src/main/java/SuMoC/backend/user/stats/Stats.java | 13 +++++++++++++ .../java/SuMoC/backend/user/stats/StatsService.java | 3 ++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/main/java/SuMoC/backend/user/stats/Stats.java b/src/main/java/SuMoC/backend/user/stats/Stats.java index 3c8d45f..b6db343 100644 --- a/src/main/java/SuMoC/backend/user/stats/Stats.java +++ b/src/main/java/SuMoC/backend/user/stats/Stats.java @@ -34,6 +34,8 @@ public class Stats { @Schema(description = "Total kilometers driven by the user in timeframe.", example = "300", required = true) private Long KM_DRIVEN; + @Schema(description = "Total Mobility score", example = "45", required = true) + private Long MOBILITY_SCORE; // Constructors @@ -41,6 +43,8 @@ public class Stats { } + + public Stats(StatsList statsList) { this.statsList = statsList; this.XP = 0L; @@ -49,6 +53,7 @@ public class Stats { this.KM_WALKED = 0L; this.KM_PUBLIC_TRANSPORT = 0L; this.KM_DRIVEN = 0L; + this.MOBILITY_SCORE = 0L; } @@ -110,4 +115,12 @@ public class Stats { public void setKM_DRIVEN(Long KM_DRIVEN) { this.KM_DRIVEN = KM_DRIVEN; } + + public Long getMobility_SCORE() { + return MOBILITY_SCORE; + } + + public void setMobility_SCORE(Long mobility_SCORE) { + MOBILITY_SCORE = mobility_SCORE; + } } diff --git a/src/main/java/SuMoC/backend/user/stats/StatsService.java b/src/main/java/SuMoC/backend/user/stats/StatsService.java index 04c2128..35dd35f 100644 --- a/src/main/java/SuMoC/backend/user/stats/StatsService.java +++ b/src/main/java/SuMoC/backend/user/stats/StatsService.java @@ -55,7 +55,8 @@ public class StatsService { "KM_CYCLED", "KM_WALKED", "KM_PUBLIC_TRANSPORT", - "KM_DRIVEN" + "KM_DRIVEN", + "MOBILITY_SCORE" ); @Transactional From 14e77cbf0fc8208fff5eee7fd9b4b249a32663aa Mon Sep 17 00:00:00 2001 From: Elias Harb Date: Tue, 20 Jan 2026 22:11:53 +0100 Subject: [PATCH 25/61] JWT available after restart --- .gitignore | 1 + docker-compose.yml | 6 ++ .../security/utils/RSAKeyProperties.java | 88 ++++++++++++++++--- src/main/resources/application.properties | 2 +- 4 files changed, 82 insertions(+), 15 deletions(-) diff --git a/.gitignore b/.gitignore index f8f383a..d136912 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,4 @@ build/ ### Secrets ### src/main/resources/firebase-private-key.json src/main/resources/firebase-private-key_disable.json +/secrets/ \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 3675edc..5d7f3b5 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,6 +1,7 @@ volumes: nominatim-data: postgres_data: + jwt_keys: services: backend: @@ -11,6 +12,11 @@ services: - "8080:8080" env_file: - .env + environment: + RSA_PRIVATE_KEY_PATH: /data/keys/jwt-private.pem + RSA_PUBLIC_KEY_PATH: /data/keys/jwt-public.pem + volumes: + - jwt_keys:/data/keys depends_on: - db restart: unless-stopped diff --git a/src/main/java/SuMoC/backend/security/utils/RSAKeyProperties.java b/src/main/java/SuMoC/backend/security/utils/RSAKeyProperties.java index 9011c58..3b27aa1 100644 --- a/src/main/java/SuMoC/backend/security/utils/RSAKeyProperties.java +++ b/src/main/java/SuMoC/backend/security/utils/RSAKeyProperties.java @@ -1,36 +1,96 @@ package SuMoC.backend.security.utils; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.security.KeyFactory; import java.security.KeyPair; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.util.Base64; @Component public class RSAKeyProperties { - private RSAPublicKey publicKey; - private RSAPrivateKey privateKey; + private final RSAPublicKey publicKey; + private final RSAPrivateKey privateKey; - public RSAKeyProperties(){ - KeyPair pair = KeyGeneratorUtility.generateRsaKey(); - this.publicKey = (RSAPublicKey) pair.getPublic(); - this.privateKey = (RSAPrivateKey) pair.getPrivate(); + public RSAKeyProperties( + @Value("${RSA_PUBLIC_KEY_PATH:/data/keys/jwt-public.pem}") String publicKeyPath, + @Value("${RSA_PRIVATE_KEY_PATH:/data/keys/jwt-private.pem}") String privateKeyPath + ) { + try { + Path pubPath = Paths.get(publicKeyPath); + Path privPath = Paths.get(privateKeyPath); + + if (pubPath.getParent() != null) Files.createDirectories(pubPath.getParent()); + if (privPath.getParent() != null) Files.createDirectories(privPath.getParent()); + + if (Files.exists(pubPath) && Files.exists(privPath)) { + this.publicKey = readPublicKey(pubPath); + this.privateKey = readPrivateKey(privPath); + return; + } + + KeyPair pair = KeyGeneratorUtility.generateRsaKey(); + RSAPublicKey pub = (RSAPublicKey) pair.getPublic(); + RSAPrivateKey priv = (RSAPrivateKey) pair.getPrivate(); + + writePublicKey(pubPath, pub); + writePrivateKey(privPath, priv); + + this.publicKey = pub; + this.privateKey = priv; + + } catch (Exception e) { + throw new IllegalStateException("Failed to load or generate RSA keys", e); + } } - public RSAPublicKey getPublicKey() { - return publicKey; + public RSAPublicKey getPublicKey() { return publicKey; } + public RSAPrivateKey getPrivateKey() { return privateKey; } + + // ---------- Read ---------- + private static RSAPublicKey readPublicKey(Path path) throws Exception { + String pem = Files.readString(path, StandardCharsets.UTF_8) + .replace("-----BEGIN PUBLIC KEY-----", "") + .replace("-----END PUBLIC KEY-----", "") + .replaceAll("\\s", ""); + byte[] der = Base64.getDecoder().decode(pem); + return (RSAPublicKey) KeyFactory.getInstance("RSA") + .generatePublic(new X509EncodedKeySpec(der)); } - public void setPublicKey(RSAPublicKey publicKey) { - this.publicKey = publicKey; + private static RSAPrivateKey readPrivateKey(Path path) throws Exception { + String pem = Files.readString(path, StandardCharsets.UTF_8) + .replace("-----BEGIN PRIVATE KEY-----", "") + .replace("-----END PRIVATE KEY-----", "") + .replaceAll("\\s", ""); + byte[] der = Base64.getDecoder().decode(pem); + return (RSAPrivateKey) KeyFactory.getInstance("RSA") + .generatePrivate(new PKCS8EncodedKeySpec(der)); } - public RSAPrivateKey getPrivateKey() { - return privateKey; + // ---------- Write ---------- + private static void writePublicKey(Path path, RSAPublicKey key) throws Exception { + writePem(path, "PUBLIC KEY", key.getEncoded()); } - public void setPrivateKey(RSAPrivateKey privateKey) { - this.privateKey = privateKey; + private static void writePrivateKey(Path path, RSAPrivateKey key) throws Exception { + writePem(path, "PRIVATE KEY", key.getEncoded()); + } + + private static void writePem(Path path, String type, byte[] derBytes) throws Exception { + String base64 = Base64.getMimeEncoder(64, new byte[]{'\n'}).encodeToString(derBytes); + String pem = "-----BEGIN " + type + "-----\n" + + base64 + "\n" + + "-----END " + type + "-----\n"; + Path tmp = Paths.get(path.toString() + ".tmp"); + Files.writeString(tmp, pem, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); + Files.move(tmp, path, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index bc4a192..3566bcf 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -3,7 +3,7 @@ spring.datasource.url=jdbc:postgresql://localhost:5432/sumoc spring.datasource.username=postgres spring.datasource.password=admin spring.datasource.driver-class-name=org.postgresql.Driver -spring.jpa.hibernate.ddl-auto=create +spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect logging.level.org.springframework.security=Trace From abb8211e16f904e48a0af211fb82dd8da3ba796c Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Thu, 22 Jan 2026 14:24:48 +0100 Subject: [PATCH 26/61] implement endpoint to request friendships by friendcode --- .../backend/user/controller/FriendshipController.java | 10 ++++++++++ src/main/java/SuMoC/backend/user/models/User.java | 2 +- .../SuMoC/backend/user/repository/UserRepository.java | 2 ++ 3 files changed, 13 insertions(+), 1 deletion(-) 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 bf99b70..a9450c3 100644 --- a/src/main/java/SuMoC/backend/user/models/User.java +++ b/src/main/java/SuMoC/backend/user/models/User.java @@ -41,7 +41,7 @@ public class User { @Column(nullable = false) private VisibilityPrivacy visibilityPrivacy; - @Column(nullable = false) + @Column(nullable = false, unique = true) private String friendCode; @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true) 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); From 4c1476944adb452755e4d1ba76090300f9029194 Mon Sep 17 00:00:00 2001 From: Lukas Laaser Date: Thu, 22 Jan 2026 14:44:19 +0100 Subject: [PATCH 27/61] Bugfix: 1. /data/ is readonly on macOS -> changed to ./keys/ 2. Changed Friendcode Annotation to unique --- docker-compose.yml | 6 +++--- .../SuMoC/backend/security/utils/RSAKeyProperties.java | 4 ++-- src/main/java/SuMoC/backend/user/models/User.java | 9 ++++++++- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 5d7f3b5..917ec49 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -13,10 +13,10 @@ services: env_file: - .env environment: - RSA_PRIVATE_KEY_PATH: /data/keys/jwt-private.pem - RSA_PUBLIC_KEY_PATH: /data/keys/jwt-public.pem + RSA_PRIVATE_KEY_PATH: ./keys/jwt-private.pem + RSA_PUBLIC_KEY_PATH: ./keys/jwt-public.pem volumes: - - jwt_keys:/data/keys + - jwt_keys:./keys depends_on: - db restart: unless-stopped diff --git a/src/main/java/SuMoC/backend/security/utils/RSAKeyProperties.java b/src/main/java/SuMoC/backend/security/utils/RSAKeyProperties.java index 3b27aa1..e492317 100644 --- a/src/main/java/SuMoC/backend/security/utils/RSAKeyProperties.java +++ b/src/main/java/SuMoC/backend/security/utils/RSAKeyProperties.java @@ -20,8 +20,8 @@ public class RSAKeyProperties { private final RSAPrivateKey privateKey; public RSAKeyProperties( - @Value("${RSA_PUBLIC_KEY_PATH:/data/keys/jwt-public.pem}") String publicKeyPath, - @Value("${RSA_PRIVATE_KEY_PATH:/data/keys/jwt-private.pem}") String privateKeyPath + @Value("${RSA_PUBLIC_KEY_PATH:./keys/jwt-public.pem}") String publicKeyPath, + @Value("${RSA_PRIVATE_KEY_PATH:./keys/jwt-private.pem}") String privateKeyPath ) { try { Path pubPath = Paths.get(publicKeyPath); diff --git a/src/main/java/SuMoC/backend/user/models/User.java b/src/main/java/SuMoC/backend/user/models/User.java index a659fae..1e36955 100644 --- a/src/main/java/SuMoC/backend/user/models/User.java +++ b/src/main/java/SuMoC/backend/user/models/User.java @@ -38,7 +38,7 @@ public class User { @Column(nullable = false) private VisibilityPrivacy visibilityPrivacy; - @Column(nullable = false) + @Column(nullable = false, unique = true, length = 36) private String friendCode; @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true) @@ -86,6 +86,13 @@ public class User { this.statsList = new StatsList(this); } + @PrePersist + private void ensureFriendCode() { + if (this.friendCode == null) { + this.friendCode = UUID.randomUUID().toString(); + } + } + public Long getId() { return id; } From fb9276ca15709e22adbed6555c5f2d7bf55f0d90 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Thu, 22 Jan 2026 15:59:38 +0100 Subject: [PATCH 28/61] store routingpreferences for each user in database, get and update via service, create with default for new users --- .../{ => controller}/RoutingController.java | 2 +- .../RoutingPreferencesController.java | 36 +++++++++++++++ .../mapper/RoutingPreferencesMapper.java | 13 ++++++ .../routing/models/RoutingPreferences.java | 40 +++++++++++++++++ .../RoutingPreferencesRepository.java | 10 +++++ .../services/RoutingPreferencesService.java | 44 +++++++++++++++++++ .../security/SecurityConfiguration.java | 1 + .../java/SuMoC/backend/user/models/User.java | 14 ++++++ 8 files changed, 159 insertions(+), 1 deletion(-) rename src/main/java/SuMoC/backend/routing/{ => controller}/RoutingController.java (98%) create mode 100644 src/main/java/SuMoC/backend/routing/controller/RoutingPreferencesController.java create mode 100644 src/main/java/SuMoC/backend/routing/mapper/RoutingPreferencesMapper.java create mode 100644 src/main/java/SuMoC/backend/routing/models/RoutingPreferences.java create mode 100644 src/main/java/SuMoC/backend/routing/repository/RoutingPreferencesRepository.java create mode 100644 src/main/java/SuMoC/backend/routing/services/RoutingPreferencesService.java diff --git a/src/main/java/SuMoC/backend/routing/RoutingController.java b/src/main/java/SuMoC/backend/routing/controller/RoutingController.java similarity index 98% rename from src/main/java/SuMoC/backend/routing/RoutingController.java rename to src/main/java/SuMoC/backend/routing/controller/RoutingController.java index e06bd5e..8a8e4d7 100644 --- a/src/main/java/SuMoC/backend/routing/RoutingController.java +++ b/src/main/java/SuMoC/backend/routing/controller/RoutingController.java @@ -1,4 +1,4 @@ -package SuMoC.backend.routing; +package SuMoC.backend.routing.controller; import SuMoC.backend.routing.dtos.RouteDTO; import SuMoC.backend.routing.dtos.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..6056ce7 --- /dev/null +++ b/src/main/java/SuMoC/backend/routing/services/RoutingPreferencesService.java @@ -0,0 +1,44 @@ +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 lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.Optional; + +@Service +@RequiredArgsConstructor +public class RoutingPreferencesService { + + private final RoutingPreferencesRepository routingPreferencesRepository; + + private final RoutingPreferencesMapper routingPreferencesMapper; + + 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); + } + + 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; + } +} diff --git a/src/main/java/SuMoC/backend/security/SecurityConfiguration.java b/src/main/java/SuMoC/backend/security/SecurityConfiguration.java index fda4666..efd98ae 100644 --- a/src/main/java/SuMoC/backend/security/SecurityConfiguration.java +++ b/src/main/java/SuMoC/backend/security/SecurityConfiguration.java @@ -98,6 +98,7 @@ 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"); diff --git a/src/main/java/SuMoC/backend/user/models/User.java b/src/main/java/SuMoC/backend/user/models/User.java index a9450c3..315d169 100644 --- a/src/main/java/SuMoC/backend/user/models/User.java +++ b/src/main/java/SuMoC/backend/user/models/User.java @@ -2,6 +2,7 @@ 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; @@ -67,6 +68,10 @@ public class User { @OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true) private StatsList statsList; + @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true) + @JoinColumn(name = "routing_preferences_id", unique = true) + private RoutingPreferences routingPreferences; + public User() { } @@ -90,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); @@ -194,4 +200,12 @@ public class User { public void setNotificationToken(NotificationToken notificationToken) { this.notificationToken = notificationToken; } + + public RoutingPreferences getRoutingPreferences() { + return routingPreferences; + } + + public void setRoutingPreferences(RoutingPreferences routingPreferences) { + this.routingPreferences = routingPreferences; + } } From 76e925100195889c4256382ce1e56a68ea5803a3 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Thu, 22 Jan 2026 16:29:56 +0100 Subject: [PATCH 29/61] switch to using stored users routing preferences in all routing services --- .../routing/controller/RoutingController.java | 17 +++++++---------- .../services/RoutingPreferencesService.java | 18 ++++++++++++++++++ .../services/AdHocSuggestionService.java | 11 ++++++----- .../services/RegularTripSuggestionService.java | 6 ++++-- .../user/service/CurrentUserService.java | 5 +++++ 5 files changed, 40 insertions(+), 17 deletions(-) diff --git a/src/main/java/SuMoC/backend/routing/controller/RoutingController.java b/src/main/java/SuMoC/backend/routing/controller/RoutingController.java index 8a8e4d7..ca642d8 100644 --- a/src/main/java/SuMoC/backend/routing/controller/RoutingController.java +++ b/src/main/java/SuMoC/backend/routing/controller/RoutingController.java @@ -2,11 +2,11 @@ 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/services/RoutingPreferencesService.java b/src/main/java/SuMoC/backend/routing/services/RoutingPreferencesService.java index 6056ce7..558ac21 100644 --- a/src/main/java/SuMoC/backend/routing/services/RoutingPreferencesService.java +++ b/src/main/java/SuMoC/backend/routing/services/RoutingPreferencesService.java @@ -5,6 +5,7 @@ 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; @@ -18,6 +19,8 @@ public class RoutingPreferencesService { private final RoutingPreferencesMapper routingPreferencesMapper; + private final CurrentUserService currentUserService; + public void updateUserRoutingPreferences(Long userId, RoutingPreferencesDTO newPreferencesDTO) { Optional optionalPreferences = routingPreferencesRepository.findByUserId(userId); @@ -29,6 +32,9 @@ public class RoutingPreferencesService { routingPreferencesRepository.save(preferences); } + /** + * Get routing preferences for a specific user. + */ public RoutingPreferencesDTO getUserRoutingPreferences(Long userId) { Optional optionalPreferences = routingPreferencesRepository.findByUserId(userId); @@ -41,4 +47,16 @@ public class RoutingPreferencesService { } 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/suggestion/services/AdHocSuggestionService.java b/src/main/java/SuMoC/backend/suggestion/services/AdHocSuggestionService.java index ad90735..be623a8 100644 --- a/src/main/java/SuMoC/backend/suggestion/services/AdHocSuggestionService.java +++ b/src/main/java/SuMoC/backend/suggestion/services/AdHocSuggestionService.java @@ -6,6 +6,7 @@ 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; @@ -24,6 +25,8 @@ public class AdHocSuggestionService { private final RoutingService routingService; + private final RoutingPreferencesService routingPreferencesService; + private final AdHocSuggestionProperties adHocSuggestionProperties; private final NotificationSchedulerService notificationSchedulerService; @@ -36,15 +39,14 @@ public class AdHocSuggestionService { 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 + return; // only suggest alternatives for trips mainly done by car, motorcycle or taxi } var viableAlternatives = routingService.determineAlternativeRoutesAdHoc(alternativeRequestFromTrip(newTrip)); if (!viableAlternatives.isEmpty()) { // Since notification bodies have a size limit, we only send the best alternative - // TODO we assume default preferences, in the future we should store user preferences and use them here - RoutingPreferencesDTO preferencesDTO = new RoutingPreferencesDTO(); + RoutingPreferencesDTO preferencesDTO = routingPreferencesService.getUserRoutingPreferences(newTrip.getUser().getId()); List bestAlternatives = pickBestAlternatives(viableAlternatives, preferencesDTO); notificationSchedulerService.schedule( @@ -90,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 index df69c8f..3ffc48b 100644 --- a/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java +++ b/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java @@ -7,6 +7,7 @@ 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; @@ -26,6 +27,8 @@ public class RegularTripSuggestionService { private final RoutingService routingService; + private final RoutingPreferencesService routingPreferencesService; + private final RegularTripSuggestionProperties properties; private final NotificationSchedulerService notificationSchedulerService; @@ -46,8 +49,7 @@ public class RegularTripSuggestionService { public void checkAlternativesAndNotify(HashMap> detectedRegularTripsByUser) { for (Long userId : detectedRegularTripsByUser.keySet()) { var detectedRegularTrips = detectedRegularTripsByUser.get(userId); - // TODO for now we use default preferences, in the future we should store user preferences and use them here - RoutingPreferencesDTO preferencesDTO = new RoutingPreferencesDTO(); + RoutingPreferencesDTO preferencesDTO = routingPreferencesService.getUserRoutingPreferences(userId); // For each detected regular trip, determine alternatives and notify the user if applicable for (var detectedRegularTrip : detectedRegularTrips) { 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 From 1a15dd5a60701d6709a532cdfef26720e5bb6065 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Thu, 22 Jan 2026 18:57:16 +0100 Subject: [PATCH 30/61] fix test by providing properties - ugly but works --- .../IterativeClustererTest.java | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/test/java/SuMoC/backend/regulartrip/detectionapproaches/IterativeClustererTest.java b/src/test/java/SuMoC/backend/regulartrip/detectionapproaches/IterativeClustererTest.java index 3bcdfac..99042d9 100644 --- a/src/test/java/SuMoC/backend/regulartrip/detectionapproaches/IterativeClustererTest.java +++ b/src/test/java/SuMoC/backend/regulartrip/detectionapproaches/IterativeClustererTest.java @@ -11,7 +11,10 @@ import org.springframework.boot.test.context.SpringBootTest; import static org.mockito.Mockito.when; -@SpringBootTest +@SpringBootTest(properties = { + "geocoding.provider=carta", + "geocoding.carta.base-url=https://mobydex.locoslab.com/carta" +}) public class IterativeClustererTest { @Mock(lenient = true) @@ -45,8 +48,8 @@ public class IterativeClustererTest { var result = iterativeClusterer.detectRegularTrips(dtos); // Assert - assert(result.size() == 1); - assert(result.get(0).getSupportingTrips().size() == 5); + assert (result.size() == 1); + assert (result.get(0).getSupportingTrips().size() == 5); } /** @@ -64,8 +67,8 @@ public class IterativeClustererTest { var result = iterativeClusterer.detectRegularTrips(dtos); // Assert - assert(result.size() == 1); - assert(result.get(0).getSupportingTrips().size() == 4); + assert (result.size() == 1); + assert (result.get(0).getSupportingTrips().size() == 4); } /** @@ -81,7 +84,7 @@ public class IterativeClustererTest { var result = iterativeClusterer.detectRegularTrips(dtos); // Assert - assert(result.size() == 1); - assert(result.get(0).getSupportingTrips().size() == 5); + assert (result.size() == 1); + assert (result.get(0).getSupportingTrips().size() == 5); } } From 6f407a26fdee0d72600a99f6d317f2d7c5ceee2a Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Thu, 22 Jan 2026 19:34:13 +0100 Subject: [PATCH 31/61] test: deploy fcm messaging key on server --- Jenkinsfile | 7 ++++++- src/main/resources/application.properties | 4 ++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 8218d4b..b8c2bac 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -16,12 +16,17 @@ node('built-in') { // deploy the build output on the server stage ('Deploy') { if (env.BRANCH_NAME == "deploy") { - withCredentials([sshUserPrivateKey(credentialsId: "sumoc-server-key", keyFileVariable: "KEYFILE")]) { + withCredentials([ + sshUserPrivateKey(credentialsId: "sumoc-server-key", keyFileVariable: "KEYFILE"), + file(credentialsId: "firebase-messaging-key", variable: "FIREBASE_MESSAGING_KEYFILE") + ]) { echo "Copy docker images to server ..." sh 'scp -i $KEYFILE .env pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE docker-compose.yml pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE docker-load.sh pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE -r docker_images pg-sumoc@apps-dev.nes:~' + echo "Copy firebase messaging key to server ..." + sh 'scp -i $KEYFILE $FIREBASE_MESSAGING_KEYFILE pg-sumoc@apps-dev.nes:~ // echo "Resetting database on server ..." // sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose stop db"' // sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"' diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 8d8181f..00d7ce0 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -19,8 +19,8 @@ trenddetection.positive-threshold=25.0 # Regular trip detection settings #regulartripdetection.detection-algorithm=iterative # FireBase -firebase.config.enabled=false -firebase.config.service-account=classpath:firebase-private-key.json +firebase.config.enabled=true +firebase.config.service-account=classpath:fcm-key.json # Base URL to external services carta.base-url=https://www.innamoruhr.de/c2 nominatim.base-url=http://localhost:6666 From 923a123f33aa2b36b482acfa2cc69dfa4bff8325 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Thu, 22 Jan 2026 19:37:16 +0100 Subject: [PATCH 32/61] fix error in jenkinsfile --- Jenkinsfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index b8c2bac..a3b99ee 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -26,7 +26,7 @@ node('built-in') { sh 'scp -i $KEYFILE docker-load.sh pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE -r docker_images pg-sumoc@apps-dev.nes:~' echo "Copy firebase messaging key to server ..." - sh 'scp -i $KEYFILE $FIREBASE_MESSAGING_KEYFILE pg-sumoc@apps-dev.nes:~ + sh 'scp -i $KEYFILE $FIREBASE_MESSAGING_KEYFILE pg-sumoc@apps-dev.nes:~' // echo "Resetting database on server ..." // sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose stop db"' // sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"' From 90a3297873769311604859f584794d11e0688d30 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Thu, 22 Jan 2026 21:28:35 +0100 Subject: [PATCH 33/61] reset db + dont copy fcm key until deployed on jenkins credentials --- Jenkinsfile | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index a3b99ee..c851c34 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -17,20 +17,20 @@ node('built-in') { stage ('Deploy') { if (env.BRANCH_NAME == "deploy") { withCredentials([ - sshUserPrivateKey(credentialsId: "sumoc-server-key", keyFileVariable: "KEYFILE"), - file(credentialsId: "firebase-messaging-key", variable: "FIREBASE_MESSAGING_KEYFILE") + sshUserPrivateKey(credentialsId: "sumoc-server-key", keyFileVariable: "KEYFILE") +// file(credentialsId: "firebase-messaging-key", variable: "FIREBASE_MESSAGING_KEYFILE") ]) { echo "Copy docker images to server ..." sh 'scp -i $KEYFILE .env pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE docker-compose.yml pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE docker-load.sh pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE -r docker_images pg-sumoc@apps-dev.nes:~' - echo "Copy firebase messaging key to server ..." - sh 'scp -i $KEYFILE $FIREBASE_MESSAGING_KEYFILE pg-sumoc@apps-dev.nes:~' -// echo "Resetting database on server ..." -// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose stop db"' -// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"' -// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm sumoc-backend_postgres_data"' +// echo "Copy firebase messaging key to server ..." +// sh 'scp -i $KEYFILE $FIREBASE_MESSAGING_KEYFILE pg-sumoc@apps-dev.nes:~' + echo "Resetting database on server ..." + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose stop db"' + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"' + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm sumoc-backend_postgres_data"' echo "Load docker images on server ..." sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"' echo "Restarting docker containers on server ..." From 6c4a2f71768dd1871153989904aae4d7db9fec8f Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Thu, 22 Jan 2026 22:00:21 +0100 Subject: [PATCH 34/61] using folder instead of docker volumes --- Jenkinsfile | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index c851c34..73445ea 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -28,9 +28,7 @@ node('built-in') { // echo "Copy firebase messaging key to server ..." // sh 'scp -i $KEYFILE $FIREBASE_MESSAGING_KEYFILE pg-sumoc@apps-dev.nes:~' echo "Resetting database on server ..." - sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose stop db"' - sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"' - sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm sumoc-backend_postgres_data"' + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "rm -rf ./postgres-data' echo "Load docker images on server ..." sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"' echo "Restarting docker containers on server ..." From 94858282dad220a8d8f6884c066ac9d21ecc799a Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Thu, 22 Jan 2026 22:20:48 +0100 Subject: [PATCH 35/61] fix typo --- Jenkinsfile | 2 +- src/main/java/SuMoC/backend/user/models/User.java | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index 73445ea..8b54cfd 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -28,7 +28,7 @@ node('built-in') { // echo "Copy firebase messaging key to server ..." // sh 'scp -i $KEYFILE $FIREBASE_MESSAGING_KEYFILE pg-sumoc@apps-dev.nes:~' echo "Resetting database on server ..." - sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "rm -rf ./postgres-data' + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "rm -rf ./postgres-data"' echo "Load docker images on server ..." sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"' echo "Restarting docker containers on server ..." diff --git a/src/main/java/SuMoC/backend/user/models/User.java b/src/main/java/SuMoC/backend/user/models/User.java index 0865f11..307415e 100644 --- a/src/main/java/SuMoC/backend/user/models/User.java +++ b/src/main/java/SuMoC/backend/user/models/User.java @@ -12,6 +12,7 @@ import lombok.Setter; import java.util.HashSet; import java.util.Set; +import java.util.UUID; @Entity @Table(name = "users") From f39d24e2d173f6f280844373d3277431d1a45c10 Mon Sep 17 00:00:00 2001 From: Elias Harb Date: Wed, 21 Jan 2026 21:07:15 +0100 Subject: [PATCH 36/61] Badge Seeder for initial Badges --- .../gamification/badges/DevBadgeSeeder.java | 127 ++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 src/main/java/SuMoC/backend/gamification/badges/DevBadgeSeeder.java diff --git a/src/main/java/SuMoC/backend/gamification/badges/DevBadgeSeeder.java b/src/main/java/SuMoC/backend/gamification/badges/DevBadgeSeeder.java new file mode 100644 index 0000000..5262c52 --- /dev/null +++ b/src/main/java/SuMoC/backend/gamification/badges/DevBadgeSeeder.java @@ -0,0 +1,127 @@ +package SuMoC.backend.gamification.badges; + +import SuMoC.backend.gamification.badges.models.Badge; +import jakarta.transaction.Transactional; +import kotlin.collections.ArrayDeque; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.context.annotation.Profile; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +import java.util.*; + +@Component +@Profile("dev") +@Order(3) +public class DevBadgeSeeder implements CommandLineRunner { + + private final BadgeService badgeService; + private final BadgeRepository badgeRepository; + + @Autowired + public DevBadgeSeeder(BadgeService badgeService, BadgeRepository badgeRepository) { + this.badgeService = badgeService; + this.badgeRepository = badgeRepository; + } + + @Override + @Transactional + public void run(String... args) { + List seeds = generateSeeds(); + + + for (Seed seed : seeds) { + var existing = badgeRepository.findByName(seed.name()).orElse(null); + if (existing == null) { + badgeService.createBadge(new Badge(seed.name(), seed.description(), new HashMap<>(seed.criteria()))); + } else { + boolean changed = + !Objects.equals(existing.getDescription(), seed.description()) || + !Objects.equals(existing.getCriteria(), seed.criteria()); + if (changed) { + existing.setDescription(seed.description()); + existing.setCriteria(new HashMap<>(seed.criteria())); + badgeService.modifyBadge(existing); + } + } + } + } + + private static Seed seed(String name, String desc, Map criteria) { + return new Seed(name, desc, criteria); + } + + private record Seed(String name, String description, Map criteria) {} + + private ArrayList generateSeeds() { + ArrayList seeds = new ArrayList<>(); + seeds.add(seed("Eröffnung", "Ein kleiner Schritt für einen Menschen, aber ein großer für die Umwelt", Map.of())); + //---------------- Mobility Score ---------------- + seeds.add(seed("Mobility Score I", "Sammle 100 Mobility-Score-Punkte", Map.of("MOBILITY_SCORE", 100))); + seeds.add(seed("Mobility Score II", "Sammle 250 Mobility-Score-Punkte", Map.of("MOBILITY_SCORE", 250))); + seeds.add(seed("Mobility Score III", "Sammle 500 Mobility-Score-Punkte", Map.of("MOBILITY_SCORE", 500))); + seeds.add(seed("Mobility Score IV", "Sammle 750 Mobility-Score-Punkte", Map.of("MOBILITY_SCORE", 750))); + seeds.add(seed("Mobility Score V", "Sammle 1.000 Mobility-Score-Punkte", Map.of("MOBILITY_SCORE", 1000))); + seeds.add(seed("Mobility Score VI", "Sammle 1.500 Mobility-Score-Punkte", Map.of("MOBILITY_SCORE", 1500))); + seeds.add(seed("Mobility Score VII", "Sammle 2.000 Mobility-Score-Punkte", Map.of("MOBILITY_SCORE", 2000))); + seeds.add(seed("Mobility Score VIII","Sammle 3.000 Mobility-Score-Punkte", Map.of("MOBILITY_SCORE", 3000))); + seeds.add(seed("Mobility Score IX", "Sammle 4.000 Mobility-Score-Punkte", Map.of("MOBILITY_SCORE", 4000))); + seeds.add(seed("Mobility Score X", "Sammle 5.000 Mobility-Score-Punkte", Map.of("MOBILITY_SCORE", 5000))); + seeds.add(seed("Mobility Score XI", "Sammle 6.500 Mobility-Score-Punkte", Map.of("MOBILITY_SCORE", 6500))); + seeds.add(seed("Mobility Score XII", "Sammle 8.000 Mobility-Score-Punkte", Map.of("MOBILITY_SCORE", 8000))); + seeds.add(seed("Over 9000! Mobility Score", "Erreiche 9000 Mobility Score-Punkte", Map.of("MOBILITY_SCORE", 9000))); + seeds.add(seed("Mobilitätspunkte XIII","Sammle 10.000 Mobility-Score-Punkte", Map.of("MOBILITY_SCORE", 10000))); + // ---------------- Public Transport ---------------- + seeds.add(seed("ÖPNV-Fan I", "Fahre 20 km mit ÖPNV", Map.of("KM_PUBLIC_TRANSPORT", 20))); + seeds.add(seed("ÖPNV-Fan II", "Fahre 50 km mit ÖPNV", Map.of("KM_PUBLIC_TRANSPORT", 50))); + seeds.add(seed("ÖPNV-Fan III", "Fahre 100 km mit ÖPNV", Map.of("KM_PUBLIC_TRANSPORT", 100))); + seeds.add(seed("ÖPNV-Fan IV", "Fahre 150 km mit ÖPNV", Map.of("KM_PUBLIC_TRANSPORT", 150))); + seeds.add(seed("ÖPNV-Fan V", "Fahre 200 km mit ÖPNV", Map.of("KM_PUBLIC_TRANSPORT", 200))); + seeds.add(seed("ÖPNV-Fan VI", "Fahre 300 km mit ÖPNV", Map.of("KM_PUBLIC_TRANSPORT", 300))); + seeds.add(seed("ÖPNV-Fan VII", "Fahre 400 km mit ÖPNV", Map.of("KM_PUBLIC_TRANSPORT", 400))); + seeds.add(seed("ÖPNV-Fan VIII","Fahre 500 km mit ÖPNV", Map.of("KM_PUBLIC_TRANSPORT", 500))); + seeds.add(seed("ÖPNV-Fan IX", "Fahre 750 km mit ÖPNV", Map.of("KM_PUBLIC_TRANSPORT", 750))); + seeds.add(seed("ÖPNV-Fan X", "Fahre 1.000 km mit ÖPNV", Map.of("KM_PUBLIC_TRANSPORT", 1_000))); + // ---------------- Walking ---------------- + seeds.add(seed("Walker I", "Gehe 5 km zu Fuß", Map.of("KM_WALKED", 5))); + seeds.add(seed("Walker II", "Gehe 10 km zu Fuß", Map.of("KM_WALKED", 10))); + seeds.add(seed("Walker III", "Gehe 20 km zu Fuß", Map.of("KM_WALKED", 20))); + seeds.add(seed("Walker IV", "Gehe 30 km zu Fuß", Map.of("KM_WALKED", 30))); + seeds.add(seed("Walker V", "Gehe 50 km zu Fuß", Map.of("KM_WALKED", 50))); + seeds.add(seed("Walker VI", "Gehe 75 km zu Fuß", Map.of("KM_WALKED", 75))); + seeds.add(seed("Walker VII", "Gehe 100 km zu Fuß", Map.of("KM_WALKED", 100))); + seeds.add(seed("Walker VIII","Gehe 150 km zu Fuß", Map.of("KM_WALKED", 150))); + seeds.add(seed("Walker IX", "Gehe 200 km zu Fuß", Map.of("KM_WALKED", 200))); + seeds.add(seed("Walker X", "Gehe 300 km zu Fuß", Map.of("KM_WALKED", 300))); + //---------------- Cycling ---------------- + seeds.add(seed("Bike Commuter I", "Fahre 10 km mit dem Rad", Map.of("KM_CYCLED", 10))); + seeds.add(seed("Bike Commuter II", "Fahre 25 km mit dem Rad", Map.of("KM_CYCLED", 25))); + seeds.add(seed("Bike Commuter III", "Fahre 50 km mit dem Rad", Map.of("KM_CYCLED", 50))); + seeds.add(seed("Bike Commuter IV", "Fahre 75 km mit dem Rad", Map.of("KM_CYCLED", 75))); + seeds.add(seed("Bike Commuter V", "Fahre 100 km mit dem Rad", Map.of("KM_CYCLED", 100))); + seeds.add(seed("Bike Commuter VI", "Fahre 150 km mit dem Rad", Map.of("KM_CYCLED", 150))); + seeds.add(seed("Bike Commuter VII", "Fahre 200 km mit dem Rad", Map.of("KM_CYCLED", 200))); + seeds.add(seed("Bike Commuter VIII","Fahre 300 km mit dem Rad", Map.of("KM_CYCLED", 300))); + seeds.add(seed("Bike Commuter IX", "Fahre 400 km mit dem Rad", Map.of("KM_CYCLED", 400))); + seeds.add(seed("Bike Commuter X", "Fahre 500 km mit dem Rad", Map.of("KM_CYCLED", 500))); + //---------------- XP ---------------- + seeds.add(seed("Silber-Pendler", "Erreiche 500 XP", Map.of("XP", 500))); + seeds.add(seed("Gold-Pendler", "Erreiche 1.000 XP", Map.of("XP", 1_000))); + seeds.add(seed("Platin-Pendler", "Erreiche 2.000 XP", Map.of("XP", 2_000))); + seeds.add(seed("Diamant-Pendler", "Erreiche 3.000 XP", Map.of("XP", 3_000))); + seeds.add(seed("XP-Jäger I", "Erreiche 5.000 XP", Map.of("XP", 5_000))); + seeds.add(seed("XP-Jäger II", "Erreiche 7.500 XP", Map.of("XP", 7_500))); + seeds.add(seed("XP-Jäger III", "Erreiche 10.000 XP", Map.of("XP", 10_000))); + seeds.add(seed("XP-Meister I", "Erreiche 12.500 XP", Map.of("XP", 12_500))); + seeds.add(seed("XP-Meister II", "Erreiche 15.000 XP", Map.of("XP", 15_000))); + seeds.add(seed("XP-Meister III", "Erreiche 20.000 XP", Map.of("XP", 20_000))); + seeds.add(seed("XP-Champion I", "Erreiche 25.000 XP", Map.of("XP", 25_000))); + seeds.add(seed("XP-Champion II", "Erreiche 30.000 XP", Map.of("XP", 30_000))); + seeds.add(seed("XP-Champion III", "Erreiche 40.000 XP", Map.of("XP", 40_000))); + seeds.add(seed("XP-Legende I", "Erreiche 50.000 XP", Map.of("XP", 50_000))); + seeds.add(seed("XP-Legende II", "Erreiche 75.000 XP", Map.of("XP", 75_000))); + seeds.add(seed("XP-Legende III", "Erreiche 100.000 XP", Map.of("XP", 100_000))); + return seeds; + } +} \ No newline at end of file From a0a3dd4e28ab221ba3888c3c7a36a295bf075104 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Thu, 22 Jan 2026 22:29:00 +0100 Subject: [PATCH 37/61] fix typo --- Jenkinsfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index 8b54cfd..0345967 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -28,7 +28,7 @@ node('built-in') { // echo "Copy firebase messaging key to server ..." // sh 'scp -i $KEYFILE $FIREBASE_MESSAGING_KEYFILE pg-sumoc@apps-dev.nes:~' echo "Resetting database on server ..." - sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "rm -rf ./postgres-data"' +// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "rm -rf ./postgres-data"' echo "Load docker images on server ..." sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"' echo "Restarting docker containers on server ..." From 7253576a5322dc871df3d94348e60481035e62a5 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Thu, 22 Jan 2026 22:36:35 +0100 Subject: [PATCH 38/61] fix missing import --- src/main/java/SuMoC/backend/user/models/User.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/SuMoC/backend/user/models/User.java b/src/main/java/SuMoC/backend/user/models/User.java index 0865f11..307415e 100644 --- a/src/main/java/SuMoC/backend/user/models/User.java +++ b/src/main/java/SuMoC/backend/user/models/User.java @@ -12,6 +12,7 @@ import lombok.Setter; import java.util.HashSet; import java.util.Set; +import java.util.UUID; @Entity @Table(name = "users") From 2af94e6b658570396efe65a69752cd182b86a539 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Thu, 22 Jan 2026 22:37:47 +0100 Subject: [PATCH 39/61] deploy --- Jenkinsfile | 1 + 1 file changed, 1 insertion(+) diff --git a/Jenkinsfile b/Jenkinsfile index 0345967..4b45923 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -28,6 +28,7 @@ node('built-in') { // echo "Copy firebase messaging key to server ..." // sh 'scp -i $KEYFILE $FIREBASE_MESSAGING_KEYFILE pg-sumoc@apps-dev.nes:~' echo "Resetting database on server ..." + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "mkdir -p ./postgres-data"' // sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "rm -rf ./postgres-data"' echo "Load docker images on server ..." sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"' From 98d940625b6452d07d207995d8dcf06e08a3e981 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Thu, 22 Jan 2026 22:43:20 +0100 Subject: [PATCH 40/61] deploy --- src/main/resources/application.properties | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 16f0d90..e62fb21 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -3,7 +3,7 @@ spring.datasource.url=jdbc:postgresql://localhost:5432/sumoc spring.datasource.username=postgres spring.datasource.password=admin spring.datasource.driver-class-name=org.postgresql.Driver -spring.jpa.hibernate.ddl-auto=update +spring.jpa.hibernate.ddl-auto=create spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect logging.level.org.springframework.security=Trace @@ -20,8 +20,9 @@ sumoc.scheduling.notify-regular-route-alternatives=0 0 4 * * * sumoc.trenddetection.positive-threshold=-25.0 sumoc.trenddetection.negative-threshold=-25.0 # FireBase -firebase.config.enabled=false -firebase.config.service-account=classpath:firebase-private-key.json +firebase.config.enabled=true +firebase.config.encrypted-key-path=classpath:fcm-key.json.enc +firebase.config.service-account=classpath:fcm-key.json # Base URL to external services carta.base-url=https://www.innamoruhr.de/c2 # Geocoding configuration From 6b56ecb5cbdef36fb580399abc0a0bd90def5586 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Thu, 22 Jan 2026 23:05:40 +0100 Subject: [PATCH 41/61] deploy --- Jenkinsfile | 4 ++-- src/main/resources/application.properties | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 4b45923..54872f0 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -28,8 +28,8 @@ node('built-in') { // echo "Copy firebase messaging key to server ..." // sh 'scp -i $KEYFILE $FIREBASE_MESSAGING_KEYFILE pg-sumoc@apps-dev.nes:~' echo "Resetting database on server ..." - sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "mkdir -p ./postgres-data"' -// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "rm -rf ./postgres-data"' +// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "mkdir -p ./postgres-data"' + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "rm -rf ./postgres_data"' echo "Load docker images on server ..." sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"' echo "Restarting docker containers on server ..." diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index e62fb21..a70f4a8 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -21,7 +21,6 @@ sumoc.trenddetection.positive-threshold=-25.0 sumoc.trenddetection.negative-threshold=-25.0 # FireBase firebase.config.enabled=true -firebase.config.encrypted-key-path=classpath:fcm-key.json.enc firebase.config.service-account=classpath:fcm-key.json # Base URL to external services carta.base-url=https://www.innamoruhr.de/c2 From 3c83274d4f414fd1b9003642ce66f1631ab5ce43 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Thu, 22 Jan 2026 23:12:19 +0100 Subject: [PATCH 42/61] switch back to docker volumes for db for drop access --- Jenkinsfile | 5 ----- docker-compose.yml | 2 +- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 54872f0..dad8622 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -25,11 +25,6 @@ node('built-in') { sh 'scp -i $KEYFILE docker-compose.yml pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE docker-load.sh pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE -r docker_images pg-sumoc@apps-dev.nes:~' -// echo "Copy firebase messaging key to server ..." -// sh 'scp -i $KEYFILE $FIREBASE_MESSAGING_KEYFILE pg-sumoc@apps-dev.nes:~' - echo "Resetting database on server ..." -// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "mkdir -p ./postgres-data"' - sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "rm -rf ./postgres_data"' echo "Load docker images on server ..." sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"' echo "Restarting docker containers on server ..." diff --git a/docker-compose.yml b/docker-compose.yml index 847b2ad..b3ddd89 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -29,7 +29,7 @@ services: - POSTGRES_PASSWORD=admin - POSTGRES_DB=sumoc volumes: - - ./postgres_data:/var/lib/postgresql/data + - postgres_volume:/var/lib/postgresql/data ports: - "5432:5432" restart: always From e7b6295dadb361e1a6581348fdeb75428eef83fd Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Thu, 22 Jan 2026 23:19:26 +0100 Subject: [PATCH 43/61] deploy with logs --- Jenkinsfile | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Jenkinsfile b/Jenkinsfile index dad8622..0b439ad 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -29,6 +29,12 @@ node('built-in') { sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"' echo "Restarting docker containers on server ..." sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "sudo systemctl restart sumoc-docker"' + echo "Waiting for containers to start..." + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "sleep 10 && docker ps"' + echo "Database logs:" + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker logs sumoc_db"' + echo "Backend logs:" + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker logs sumoc-backend"' } } else { echo "Skipping deployment for non-deploy branch." From 0cdf4a09f355ad3f2c9869c4cb648a03fcc758c0 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Thu, 22 Jan 2026 23:25:50 +0100 Subject: [PATCH 44/61] deploy with logs --- Jenkinsfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index 0b439ad..37d16a3 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -32,7 +32,7 @@ node('built-in') { echo "Waiting for containers to start..." sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "sleep 10 && docker ps"' echo "Database logs:" - sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker logs sumoc_db"' + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker logs sumoc-db"' echo "Backend logs:" sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker logs sumoc-backend"' } From b18878fcb27c9c2470bb203286e16197c1e4e13a Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Thu, 22 Jan 2026 23:39:41 +0100 Subject: [PATCH 45/61] fix db volume name --- Jenkinsfile | 6 +++++- docker-compose.yml | 4 ++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 37d16a3..6ade4d0 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -25,6 +25,10 @@ node('built-in') { sh 'scp -i $KEYFILE docker-compose.yml pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE docker-load.sh pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE -r docker_images pg-sumoc@apps-dev.nes:~' + echo "Resetting database..." + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose stop db"' + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"' + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm sumoc-backend_postgres_data"' echo "Load docker images on server ..." sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"' echo "Restarting docker containers on server ..." @@ -32,7 +36,7 @@ node('built-in') { echo "Waiting for containers to start..." sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "sleep 10 && docker ps"' echo "Database logs:" - sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker logs sumoc-db"' + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker logs sumoc_db"' echo "Backend logs:" sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker logs sumoc-backend"' } diff --git a/docker-compose.yml b/docker-compose.yml index b3ddd89..bdf7892 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,7 +1,7 @@ volumes: - nominatim-data: postgres_data: jwt_keys: +# nominatim-data: services: backend: @@ -29,7 +29,7 @@ services: - POSTGRES_PASSWORD=admin - POSTGRES_DB=sumoc volumes: - - postgres_volume:/var/lib/postgresql/data + - postgres_data:/var/lib/postgresql/data ports: - "5432:5432" restart: always From 321b7c80357e3465f4486119ab1879a53bed4013 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Thu, 22 Jan 2026 23:43:39 +0100 Subject: [PATCH 46/61] fix db volume name --- Jenkinsfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index 6ade4d0..2f4d2a8 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -28,7 +28,7 @@ node('built-in') { echo "Resetting database..." sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose stop db"' sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"' - sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm sumoc-backend_postgres_data"' + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm -f sumoc-backend_postgres_data"' echo "Load docker images on server ..." sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"' echo "Restarting docker containers on server ..." From 8e0c2cfc3e2646b183abbd7f98bf56fbbbd01c89 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Fri, 23 Jan 2026 00:01:47 +0100 Subject: [PATCH 47/61] try fix db --- Jenkinsfile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 2f4d2a8..0b39a4f 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -25,10 +25,10 @@ node('built-in') { sh 'scp -i $KEYFILE docker-compose.yml pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE docker-load.sh pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE -r docker_images pg-sumoc@apps-dev.nes:~' - echo "Resetting database..." - sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose stop db"' - sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"' - sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm -f sumoc-backend_postgres_data"' +// echo "Resetting database..." +// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose stop db"' +// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"' +// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm -f sumoc-backend_postgres_data"' echo "Load docker images on server ..." sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"' echo "Restarting docker containers on server ..." From d56bdd97d76aef1c4ac6469e01e57c0b5f91a8d5 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Fri, 23 Jan 2026 00:08:12 +0100 Subject: [PATCH 48/61] deactivate firebase --- src/main/resources/application.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index a70f4a8..4667344 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -20,7 +20,7 @@ sumoc.scheduling.notify-regular-route-alternatives=0 0 4 * * * sumoc.trenddetection.positive-threshold=-25.0 sumoc.trenddetection.negative-threshold=-25.0 # FireBase -firebase.config.enabled=true +firebase.config.enabled=false firebase.config.service-account=classpath:fcm-key.json # Base URL to external services carta.base-url=https://www.innamoruhr.de/c2 From c61d8701737350cc4342bff2f9baf000cf24b628 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Fri, 23 Jan 2026 00:14:29 +0100 Subject: [PATCH 49/61] fix docker compose --- docker-compose.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index bdf7892..4c42d2c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -13,10 +13,10 @@ services: env_file: - .env environment: - RSA_PRIVATE_KEY_PATH: ./keys/jwt-private.pem - RSA_PUBLIC_KEY_PATH: ./keys/jwt-public.pem + RSA_PRIVATE_KEY_PATH: /keys/jwt-private.pem + RSA_PUBLIC_KEY_PATH: /keys/jwt-public.pem volumes: - - jwt_keys:./keys + - jwt_keys:/keys depends_on: - db restart: unless-stopped From c117b7a04946bd6c9b6d9e57f79f9481c45bf02f Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Fri, 23 Jan 2026 00:19:55 +0100 Subject: [PATCH 50/61] now wipe db volume again --- Jenkinsfile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 0b39a4f..2f4d2a8 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -25,10 +25,10 @@ node('built-in') { sh 'scp -i $KEYFILE docker-compose.yml pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE docker-load.sh pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE -r docker_images pg-sumoc@apps-dev.nes:~' -// echo "Resetting database..." -// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose stop db"' -// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"' -// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm -f sumoc-backend_postgres_data"' + echo "Resetting database..." + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose stop db"' + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"' + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm -f sumoc-backend_postgres_data"' echo "Load docker images on server ..." sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"' echo "Restarting docker containers on server ..." From ebc5de34cd4a34ac94ce64eae1e37e5f8f7363cc Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Fri, 23 Jan 2026 00:29:11 +0100 Subject: [PATCH 51/61] try to get rid of postgres15 db --- Jenkinsfile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 2f4d2a8..8d5e82e 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -26,9 +26,9 @@ node('built-in') { sh 'scp -i $KEYFILE docker-load.sh pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE -r docker_images pg-sumoc@apps-dev.nes:~' echo "Resetting database..." - sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose stop db"' - sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"' - sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm -f sumoc-backend_postgres_data"' + sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose down -v"' +// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"' +// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm -f sumoc-backend_postgres_data"' echo "Load docker images on server ..." sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"' echo "Restarting docker containers on server ..." From 0d7f97af5e3eff8282494e48ad26cf6813efcbee Mon Sep 17 00:00:00 2001 From: Lukas Laaser Date: Fri, 23 Jan 2026 10:05:46 +0100 Subject: [PATCH 52/61] Bugfix: keysave should work now on docker and device --- docker-compose.yml | 6 ++--- .../security/utils/RSAKeyProperties.java | 25 ++++++++++--------- .../java/SuMoC/backend/user/models/User.java | 1 + 3 files changed, 17 insertions(+), 15 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 917ec49..5d7f3b5 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -13,10 +13,10 @@ services: env_file: - .env environment: - RSA_PRIVATE_KEY_PATH: ./keys/jwt-private.pem - RSA_PUBLIC_KEY_PATH: ./keys/jwt-public.pem + RSA_PRIVATE_KEY_PATH: /data/keys/jwt-private.pem + RSA_PUBLIC_KEY_PATH: /data/keys/jwt-public.pem volumes: - - jwt_keys:./keys + - jwt_keys:/data/keys depends_on: - db restart: unless-stopped diff --git a/src/main/java/SuMoC/backend/security/utils/RSAKeyProperties.java b/src/main/java/SuMoC/backend/security/utils/RSAKeyProperties.java index e492317..84da7ba 100644 --- a/src/main/java/SuMoC/backend/security/utils/RSAKeyProperties.java +++ b/src/main/java/SuMoC/backend/security/utils/RSAKeyProperties.java @@ -20,15 +20,14 @@ public class RSAKeyProperties { private final RSAPrivateKey privateKey; public RSAKeyProperties( - @Value("${RSA_PUBLIC_KEY_PATH:./keys/jwt-public.pem}") String publicKeyPath, - @Value("${RSA_PRIVATE_KEY_PATH:./keys/jwt-private.pem}") String privateKeyPath + @Value("${security.rsa.public-key-path}") String publicKeyPath, + @Value("${security.rsa.private-key-path}") String privateKeyPath ) { try { Path pubPath = Paths.get(publicKeyPath); Path privPath = Paths.get(privateKeyPath); - if (pubPath.getParent() != null) Files.createDirectories(pubPath.getParent()); - if (privPath.getParent() != null) Files.createDirectories(privPath.getParent()); + Files.createDirectories(pubPath.getParent()); if (Files.exists(pubPath) && Files.exists(privPath)) { this.publicKey = readPublicKey(pubPath); @@ -36,21 +35,23 @@ public class RSAKeyProperties { return; } + if (!Files.isWritable(pubPath.getParent())) { + throw new IllegalStateException("Key directory not writable: " + pubPath.getParent()); + } + KeyPair pair = KeyGeneratorUtility.generateRsaKey(); - RSAPublicKey pub = (RSAPublicKey) pair.getPublic(); - RSAPrivateKey priv = (RSAPrivateKey) pair.getPrivate(); + this.publicKey = (RSAPublicKey) pair.getPublic(); + this.privateKey = (RSAPrivateKey) pair.getPrivate(); - writePublicKey(pubPath, pub); - writePrivateKey(privPath, priv); - - this.publicKey = pub; - this.privateKey = priv; + writePublicKey(pubPath, this.publicKey); + writePrivateKey(privPath, this.privateKey); } catch (Exception e) { throw new IllegalStateException("Failed to load or generate RSA keys", e); } } + public RSAPublicKey getPublicKey() { return publicKey; } public RSAPrivateKey getPrivateKey() { return privateKey; } @@ -91,6 +92,6 @@ public class RSAKeyProperties { "-----END " + type + "-----\n"; Path tmp = Paths.get(path.toString() + ".tmp"); Files.writeString(tmp, pem, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); - Files.move(tmp, path, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + Files.move(tmp, path, StandardCopyOption.REPLACE_EXISTING); } } diff --git a/src/main/java/SuMoC/backend/user/models/User.java b/src/main/java/SuMoC/backend/user/models/User.java index 0865f11..307415e 100644 --- a/src/main/java/SuMoC/backend/user/models/User.java +++ b/src/main/java/SuMoC/backend/user/models/User.java @@ -12,6 +12,7 @@ import lombok.Setter; import java.util.HashSet; import java.util.Set; +import java.util.UUID; @Entity @Table(name = "users") From cc1524568039ea7736f2b340017017393463ef18 Mon Sep 17 00:00:00 2001 From: Lukas Laaser Date: Fri, 23 Jan 2026 10:29:56 +0100 Subject: [PATCH 53/61] Forgot to upload --- src/main/resources/application.properties | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 808e46c..ede5695 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -30,4 +30,8 @@ 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 # Dev debug settings -sumoc.dev.fcm-key=dmydW4a_RjKCDjcBLZ9Kl8:APA91bFjBIjw8NcjeMIsNkfPuW9jhMlK3n_LHoG5UBW0E_76nTp1yV6jkdiBIvle7Txj_mLY3W9e9gy_op6YWyxJksqZrJFgapruCdBdg9ACYDJAANGTWJk \ No newline at end of file +sumoc.dev.fcm-key=dmydW4a_RjKCDjcBLZ9Kl8:APA91bFjBIjw8NcjeMIsNkfPuW9jhMlK3n_LHoG5UBW0E_76nTp1yV6jkdiBIvle7Txj_mLY3W9e9gy_op6YWyxJksqZrJFgapruCdBdg9ACYDJAANGTWJk + +# RSA key paths (file paths, not directories) +security.rsa.private-key-path=${RSA_PRIVATE_KEY_PATH:${user.home}/.sumoc/keys/jwt-private.pem} +security.rsa.public-key-path=${RSA_PUBLIC_KEY_PATH:${user.home}/.sumoc/keys/jwt-public.pem} From a2be274ca3cd4d7a33dff3e82488d5642207e319 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Fri, 23 Jan 2026 10:34:22 +0100 Subject: [PATCH 54/61] add encrypted fcm key for messaging service account --- fcm-key.json.enc | Bin 0 -> 2400 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 fcm-key.json.enc diff --git a/fcm-key.json.enc b/fcm-key.json.enc new file mode 100644 index 0000000000000000000000000000000000000000..01817998e20f568e47029663865df8d0fbd5a94e GIT binary patch literal 2400 zcmV-m37_^;VQh3|WM5xq5S^^mInyvoTAYEMR(@@X$-zilpY`gkXDJ;VJfs#O+a2q6 zof=<+dpzEsw#Hv2M5D1wrJ< z;zJ0?s#OJJ&Br)CgjIJ&M2iGvCxlJ23Mk~MhJYPg<%fcS>p_jxz$*?}iFc5&--3A! ztFMyP84}BXPM`}En!;Ki&P(P*tV*|+q{bpd9$2O?$qPK3Vk+za6xo*mxtyd!2mlAa zW_yjU`pVre2fm0y!wz@vzdg}n%rmnmHAm_MlKKHKT>1ssdYB)hDDRhoVfk7TK7Xx= zo|hKtqdWaB>igK3CnV6zrqH7yYdvCHK=$0TZ!A4(kMqwFaHvtLju>XmpEK9*djbuM zzg-IqRPomnz|GI+6))If-IqzOF^?8pSJ@5lRb-2SYZx?LfH@Yc>)8nk(cH)8 zeT^f|qfP+C1sA5dlhBmQ`hK;913^|FUa8JAd-zCEmP;pkQvLMb@t0;^lRB<%PHFwu z(-FqphV8$Yy&Op$SF&S{C6h$%!4qTO3~o0E0gfeIOI6`0SU-P05t68 z8^P1Yg~_&v&qExGowaVV+|pHxXhjMA%2y;XQi7Q5t|5W>C3Zu~oD4#ne4ADPd{slJ?JQ&%aSkaY>LY=+r)eu(4Gwr^R#~ z{nnM8ET+n8dvY`}Eowazn7-3|M|SLA|3dcmUoOv4gPKQmsWTwi8qYX6cxw8_jCEyV z$nM$)sYWW-h%{&9{Xn8 zSwMWjXj6QCnnTu6=3Nu^`&t0t3oGzm$@%wMT8M_AJ3^^G!s=GHTqAcy)|1(`F zv%a;i4DDQS+nPZ|hPrDXiaRmjmFV-H06aCa?#0CmP$&BD;? z2hQ#?KsBvxnp!QFsm2v@{l>m=S>jLOGsJ*voY~}*d%KA4*1m9qLa6-kqfIn9|5~zC z{m?uq`QkwDh|Ys6E0OL_1FqFb%0d7U*KAd&nkA0k$e_(R{7PTNKo2X?EzO{Le`bQ- zl(!n4UUr^qFjWa75UafINimA?>QXCvj09v-4VnUp^(87$)tv@~H@q z!u(?ox=|sazd>S+C37~@cK@sqBL7-1uESF$5#BCwLMAz!PY1|L@6z`sU&upMhfze; z**;rw#0!kTLE$tp=O$b5$qEZp`xA$z60N}^eT`Dw=ux5&=SG_6dOl%p5@ExzE zb6_q2zbEkCr1{zLCB1m5VW1le*Sl;U>5@2#U+j0#C_Yenp1CT}*4U~!)TUVgPhJvP zNkcVFq|{o_pPQ?k(dG#fBe3j$w{x#Fg=Jvt1BgD6CC;T>nq8o?eU)%WezApI<=F#w zY#fkb!f^3OURJ`U@=QRvs1oU9+iv``{u-11MP8yq6m$#J{Zzw)upTRO=1DC}<@KIi z{Hx%JEe781pd~+R6;Pfj8<1;JI)~=fv>pF$zR|p%(Rl?M4uA6JpQ#^_YQvw~Rpk|U zIDK}{sO6t7w5~VU$859idY-OT6}7UnY`b$umYl%Aky=xDC(hH;Ma zAa#w8z4}XcYZGd?i^F>}Ii2iWJV((MOYv&S`Ho2B<7v6xne_ete`68_059}!x#-@8sDgjG6abNzVzcX} zC)EOCriwZ~K(o9H%>~CLIAf^9>Q=uR#5I(&X9ET1c;Fg)9M8E)f7Vwn@M6oD3m+Fz zA5??1G6Wc(0tKGFlgsvR&f(-QQwU}pZ@(TpE0lylLdX5itEk8G;J5o6-(xBXYwGjY z!9KcN+Cew#v?G1IqG=t#I98!dly+0;w@E+0#>V}YM+)k!{Cm9-{%Eh0onj8&ElG$$ ztq?0QkK5koCJP7)T5Vdeuf7A>?~>abK33-A{a?dmW|BZZ=oo$Kc&lzlyQu=lTYf%3 z2~Iia+RWQakP%1?iysjtA`$T Date: Fri, 23 Jan 2026 12:32:53 +0100 Subject: [PATCH 55/61] add entrypoint script to decrypt secrets on application startup with key provided as env --- .gitignore | 2 +- Dockerfile | 11 +++++++++-- docker-compose.yml | 1 + entrypoint.sh | 16 ++++++++++++++++ fcm-key.json.enc | Bin 2400 -> 0 bytes secrets/README.MD | 9 +++++++++ secrets/fcm-key.json.enc | Bin 0 -> 2400 bytes src/main/resources/application.properties | 4 ++-- 8 files changed, 38 insertions(+), 5 deletions(-) create mode 100644 entrypoint.sh delete mode 100644 fcm-key.json.enc create mode 100644 secrets/README.MD create mode 100644 secrets/fcm-key.json.enc diff --git a/.gitignore b/.gitignore index d136912..96ea90d 100644 --- a/.gitignore +++ b/.gitignore @@ -41,4 +41,4 @@ build/ ### Secrets ### src/main/resources/firebase-private-key.json src/main/resources/firebase-private-key_disable.json -/secrets/ \ No newline at end of file +/secrets/fcm-key.json \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 32baa4c..878bf61 100644 --- a/Dockerfile +++ b/Dockerfile @@ -17,5 +17,12 @@ COPY --from=build /app/target/*SNAPSHOT.jar app.jar # Port freigeben EXPOSE 8080 -# App starten -CMD ["java", "-jar", "app.jar"] +# Copy entrypoint script +COPY entrypoint.sh . +RUN chmod +x entrypoint.sh + +# Copy secrets +COPY secrets/ ./secrets/ + +# Start entrypoint first for key decryption +ENTRYPOINT ["./entrypoint.sh"] \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 4c42d2c..8de8634 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -13,6 +13,7 @@ services: env_file: - .env environment: + FCM_DECRYPTION_KEY: ${FCM_DECRYPTION_KEY} RSA_PRIVATE_KEY_PATH: /keys/jwt-private.pem RSA_PUBLIC_KEY_PATH: /keys/jwt-public.pem volumes: diff --git a/entrypoint.sh b/entrypoint.sh new file mode 100644 index 0000000..5a5f39b --- /dev/null +++ b/entrypoint.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +# Decrypt secrets if key is provided +if [ -z "$FCM_DECRYPTION_KEY" ]; then + echo "No decryption key provided, skipping decryption." +else + echo "Decryption key provided, decrypting secrets..." + openssl enc -d -aes-256-cbc -pbkdf2 -in ./secrets/fcm-key.json.enc -out ./secrets/fcm-key.json -k "$FCM_DECRYPTION_KEY" + if [ $? -ne 0 ]; then + echo "Decryption failed!" + exit 1 + fi + echo "Decryption successful." +fi + +exec java -jar app.jar \ No newline at end of file diff --git a/fcm-key.json.enc b/fcm-key.json.enc deleted file mode 100644 index 01817998e20f568e47029663865df8d0fbd5a94e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2400 zcmV-m37_^;VQh3|WM5xq5S^^mInyvoTAYEMR(@@X$-zilpY`gkXDJ;VJfs#O+a2q6 zof=<+dpzEsw#Hv2M5D1wrJ< z;zJ0?s#OJJ&Br)CgjIJ&M2iGvCxlJ23Mk~MhJYPg<%fcS>p_jxz$*?}iFc5&--3A! ztFMyP84}BXPM`}En!;Ki&P(P*tV*|+q{bpd9$2O?$qPK3Vk+za6xo*mxtyd!2mlAa zW_yjU`pVre2fm0y!wz@vzdg}n%rmnmHAm_MlKKHKT>1ssdYB)hDDRhoVfk7TK7Xx= zo|hKtqdWaB>igK3CnV6zrqH7yYdvCHK=$0TZ!A4(kMqwFaHvtLju>XmpEK9*djbuM zzg-IqRPomnz|GI+6))If-IqzOF^?8pSJ@5lRb-2SYZx?LfH@Yc>)8nk(cH)8 zeT^f|qfP+C1sA5dlhBmQ`hK;913^|FUa8JAd-zCEmP;pkQvLMb@t0;^lRB<%PHFwu z(-FqphV8$Yy&Op$SF&S{C6h$%!4qTO3~o0E0gfeIOI6`0SU-P05t68 z8^P1Yg~_&v&qExGowaVV+|pHxXhjMA%2y;XQi7Q5t|5W>C3Zu~oD4#ne4ADPd{slJ?JQ&%aSkaY>LY=+r)eu(4Gwr^R#~ z{nnM8ET+n8dvY`}Eowazn7-3|M|SLA|3dcmUoOv4gPKQmsWTwi8qYX6cxw8_jCEyV z$nM$)sYWW-h%{&9{Xn8 zSwMWjXj6QCnnTu6=3Nu^`&t0t3oGzm$@%wMT8M_AJ3^^G!s=GHTqAcy)|1(`F zv%a;i4DDQS+nPZ|hPrDXiaRmjmFV-H06aCa?#0CmP$&BD;? z2hQ#?KsBvxnp!QFsm2v@{l>m=S>jLOGsJ*voY~}*d%KA4*1m9qLa6-kqfIn9|5~zC z{m?uq`QkwDh|Ys6E0OL_1FqFb%0d7U*KAd&nkA0k$e_(R{7PTNKo2X?EzO{Le`bQ- zl(!n4UUr^qFjWa75UafINimA?>QXCvj09v-4VnUp^(87$)tv@~H@q z!u(?ox=|sazd>S+C37~@cK@sqBL7-1uESF$5#BCwLMAz!PY1|L@6z`sU&upMhfze; z**;rw#0!kTLE$tp=O$b5$qEZp`xA$z60N}^eT`Dw=ux5&=SG_6dOl%p5@ExzE zb6_q2zbEkCr1{zLCB1m5VW1le*Sl;U>5@2#U+j0#C_Yenp1CT}*4U~!)TUVgPhJvP zNkcVFq|{o_pPQ?k(dG#fBe3j$w{x#Fg=Jvt1BgD6CC;T>nq8o?eU)%WezApI<=F#w zY#fkb!f^3OURJ`U@=QRvs1oU9+iv``{u-11MP8yq6m$#J{Zzw)upTRO=1DC}<@KIi z{Hx%JEe781pd~+R6;Pfj8<1;JI)~=fv>pF$zR|p%(Rl?M4uA6JpQ#^_YQvw~Rpk|U zIDK}{sO6t7w5~VU$859idY-OT6}7UnY`b$umYl%Aky=xDC(hH;Ma zAa#w8z4}XcYZGd?i^F>}Ii2iWJV((MOYv&S`Ho2B<7v6xne_ete`68_059}!x#-@8sDgjG6abNzVzcX} zC)EOCriwZ~K(o9H%>~CLIAf^9>Q=uR#5I(&X9ET1c;Fg)9M8E)f7Vwn@M6oD3m+Fz zA5??1G6Wc(0tKGFlgsvR&f(-QQwU}pZ@(TpE0lylLdX5itEk8G;J5o6-(xBXYwGjY z!9KcN+Cew#v?G1IqG=t#I98!dly+0;w@E+0#>V}YM+)k!{Cm9-{%Eh0onj8&ElG$$ ztq?0QkK5koCJP7)T5Vdeuf7A>?~>abK33-A{a?dmW|BZZ=oo$Kc&lzlyQu=lTYf%3 z2~Iia+RWQakP%1?iysjtA`$TE&Q;-~-ZG zxZcFq!lYt)s1lHMrOYDPxNQq@NTd307q!B>CckT+eI#Ej7+A(xl7@hwxT=7z)^5^< zX3ylgfYI(TZK4q)UFP-!>i9`;^Z|bc_gjX@`)Eo{t%S*--Bq~ue?O7Qz`(`Pi7ln~ z9lF-J$+FpX3y5V=D<4l< z8B?(sQlg1?K37LP%_+C%E%;lCWrsNa{2H1uaQ>v;HU&K7$bXO{6}l-+*>NX8g71P_ zCk#NfWKH)iNZM_LGOJ=qz9x^9fujH>9s0>hofHJg?2(l8cGMt(xptg5NGPC2c2A%x=mRB1GwrSVL#SeE@+_MF8=ZSiF|sUk`LJ>M@)6VAt{ z5}fAaxChq`r)M>|y4AS>wzfhkbYJciKP!zg-ysav#b55#yWp!R2{OfI_jMW(M?_(ub(^ zwj^=Ew6sD&mhQm(J30g^&Y?|~tA97pn!V7Ya=<&Z8SW%%7DWj(D#1B2o5ta$p@$+a z+<`{OJpZJ6B!;jWD3`aBk|hI94p*_YB!t8BY-Lt$BC25txlNJS5gel$ES~Sg#R4&; zmJhvx7gf%(=jZpn74R6$$UDP0Px2Qk60AIH>z1GkaH&!d_}B@`80f1iE}g^0jmiP+ zD(CXMi0$9M$-u(uwz{8Syj)c(B8k&G_KH_!J#fY(K=86jMnWy0_Hw`Y8#pnYkJx( zmBfldqR{OKmY2<)wTQD8uGQHn5g^L|@$}Jr>l%g^Mrk;rbdB)I(N-Q!9=zXmvy9-| z7YY`-rGQS?!9JtJTq(Kb>DItKP4{_-K5Dwtl=bTr8x`4A@KPuT7=MRXBCt;n0G7P- z28R6<9KXxh|CNCv+fb1*mj#&C`R^w zUc1XCozZ64We{;Flm0N3FOL3Uf%z|uPI4Qh+?uSQ?Z}6%9aQqrLfc7AgHbO%sXk*N zwGK6?)MG2Lf8@+%zWoJ%(Ef>|tC13$2)=6v{iQ{6dQf!7MEpl0x~eOJ)n}(N>h6hq z*f|FfbbExgNxMM}%ZPL>CduK3mLkWfg$0HBUDp{EeU!bXUZi;Qbz0ZdkrAFPPdLF- z;3sz0)DA}%Lw#0Uoj*LR5NHofC&gDnv6i+x9=&j@MOB9uZwa@kHI*i2 zY}X3l_QhK9h1Hx?4r<}Iv3fqv{;LA^nJwvuVWxYJ8_MBz5Hd{pkrNmqr7u%are?9zczxA#U*H5V^Kkq6I?^)Is@UJ+P;HPV!XExmyF*jXce@J=%g9aWnixtrMnx4>|oo2P~4G*p@Gbm>Iz;fP?nz5$vu_iy Date: Fri, 23 Jan 2026 14:24:01 +0100 Subject: [PATCH 56/61] Totally unsave loggingpage --- .gitignore | 5 +- generateStuds.sh | 2 +- openapi.yaml | 1331 ++++++++++++++++- pom.xml | 4 + .../backend/logger/LogPageController.java | 20 + .../security/SecurityConfiguration.java | 1 + src/main/resources/application.properties | 2 + src/main/resources/templates/logs.html | 62 + 8 files changed, 1344 insertions(+), 83 deletions(-) create mode 100644 src/main/java/SuMoC/backend/logger/LogPageController.java create mode 100644 src/main/resources/templates/logs.html diff --git a/.gitignore b/.gitignore index d136912..2e49a38 100644 --- a/.gitignore +++ b/.gitignore @@ -41,4 +41,7 @@ build/ ### Secrets ### src/main/resources/firebase-private-key.json src/main/resources/firebase-private-key_disable.json -/secrets/ \ No newline at end of file +/secrets/ +/data/keys/jwt-public.pem +/data/keys/jwt-private.pem +/logs/app.log diff --git a/generateStuds.sh b/generateStuds.sh index 01f650d..0c8b255 100644 --- a/generateStuds.sh +++ b/generateStuds.sh @@ -19,7 +19,7 @@ curl http://localhost:8080/v3/api-docs.yaml -o openapi.yaml # 3. Swift-Client generieren echo "Generiere Swift-Client..." -openapi-generator-cli generate -i openapi.yaml -g swift5 -o app/ios-api +openapi-generator-cli generate -i openapi.yaml -g swift5 -o app/ios-api --additional-properties=useClasses=true # 4. Kotlin-Client generieren echo "Generiere Kotlin-Client..." diff --git a/openapi.yaml b/openapi.yaml index ddcf1c3..9381955 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -36,6 +36,14 @@ paths: description: Ungültige Eingabedaten content: application/json: {} + "403": + description: Ungültige Eingabedaten + content: + application/json: {} + "409": + description: Ungültige Eingabedaten + content: + application/json: {} /user/setPrivateName/{id}: put: tags: @@ -57,7 +65,21 @@ paths: type: string responses: "200": - description: OK + description: Passwort erfolgreich geändert + content: + application/json: {} + "400": + description: Ungültige Eingabedaten + content: + application/json: {} + "403": + description: Nur autorisierte Personen dürfen das Passwort ändern + content: + application/json: {} + "404": + description: Der Nutzer existiert nicht + content: + application/json: {} /user/setPassword/{id}: put: tags: @@ -82,11 +104,21 @@ paths: "200": description: Passwort erfolgreich geändert content: - application/json: {} + application/json: + schema: + $ref: "#/components/schemas/LoginResponseDTO" "400": description: Ungültige Eingabedaten content: application/json: {} + "403": + description: Nur autorisierte Personen dürfen das Passwort ändern + content: + application/json: {} + "404": + description: Der Nutzer existiert nicht + content: + application/json: {} /user/setEmail/{id}: put: tags: @@ -111,11 +143,146 @@ paths: "200": description: E-Mail-Adresse erfolgreich geändert content: - application/json: {} + application/json: + schema: + $ref: "#/components/schemas/LoginResponseDTO" "400": description: Ungültige Eingabedaten content: application/json: {} + "403": + description: Nur autorisierte Personen dürfen die Email ändern + content: + application/json: {} + "404": + description: Der Nutzer existiert nicht + content: + application/json: {} + "409": + description: Die Email wurde bereits vergeben + content: + application/json: {} + /trip/validateTrip/{tripId}: + put: + tags: + - trip-controller + summary: Validate a trip for the authenticated user. + operationId: validateTrip + parameters: + - name: tripId + in: path + required: true + schema: + type: integer + format: int64 + responses: + "200": + description: OK + /trip/invalidateTrip/{tripId}: + put: + tags: + - trip-controller + summary: Invalidate a trip for the authenticated user. + operationId: invalidateTrip + parameters: + - name: tripId + in: path + required: true + schema: + type: integer + format: int64 + responses: + "200": + description: OK + /routing/preferences/update: + put: + tags: + - routing-preferences-controller + summary: Update the routing preferences of the current user + description: Updates the routing preferences for the authenticated user with + the provided settings. + operationId: updateRoutingPreferences + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/RoutingPreferencesDTO" + required: true + responses: + "200": + description: OK + /notifications/register-device-token: + put: + tags: + - notification-controller + summary: Registers a device token for push notifications for the authenticated + user. + operationId: registerDeviceToken + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/RegisterDeviceTokenRequest" + required: true + responses: + "200": + description: OK + /badges/modifyBadge: + put: + tags: + - badge-controller + summary: Modify a badge by ID + operationId: modifyBadgeById + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/Badge" + required: true + responses: + "200": + description: Badge modified successfully + content: + '*/*': + schema: + $ref: "#/components/schemas/Badge" + "404": + description: Badge not found + content: + '*/*': + schema: + $ref: "#/components/schemas/Badge" + "400": + description: Invalid input data + content: + '*/*': + schema: + $ref: "#/components/schemas/Badge" + /user/stats/add: + post: + tags: + - user-controller + summary: Add stats to the current user + description: Adds a value to a stat field for the current user. Optionally checks + and awards badges afterwards. + operationId: addStats + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/AddStatRequestDTO" + required: true + responses: + "200": + description: Stats updated successfully + "400": + description: Invalid stat field / invalid input + content: + application/json: {} + "403": + description: Not authorized + content: + application/json: {} /trip/uploadTrip: post: tags: @@ -134,13 +301,13 @@ paths: /routing/alternative/request: post: tags: - - routing-alternative-controller + - routing-controller operationId: requestAlternativeRoutes requestBody: content: application/json: schema: - $ref: "#/components/schemas/RouteAlternativeRequestDTO" + $ref: "#/components/schemas/RoutingAlternativeRequestDTO" required: true responses: "200": @@ -150,7 +317,7 @@ paths: schema: type: array items: - $ref: "#/components/schemas/RouteAlternativeDTO" + $ref: "#/components/schemas/RouteDTO" /friendship/unblock/{friendId}: post: tags: @@ -185,6 +352,23 @@ paths: responses: "200": description: OK + /friendship/request/by-friendcode/{friendCode}: + post: + tags: + - friendship-controller + 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. + operationId: requestFriendshipByFriendcode + parameters: + - name: friendCode + in: path + required: true + schema: + type: string + responses: + "200": + description: OK /friendship/reject/{friendId}: post: tags: @@ -238,6 +422,54 @@ paths: responses: "200": description: OK + /dev/trigger-trend-calculation: + post: + tags: + - dev-controller + operationId: triggerTrendCalculation + responses: + "200": + description: OK + /badges/createBadge: + post: + tags: + - badge-controller + summary: Create a new badge + operationId: createBadge + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/Badge" + required: true + responses: + "201": + description: Badge created successfully + content: + '*/*': + schema: + $ref: "#/components/schemas/Badge" + "400": + description: Invalid input data + content: + '*/*': + schema: + $ref: "#/components/schemas/Badge" + "409": + description: Badge already exists + content: + '*/*': + schema: + $ref: "#/components/schemas/Badge" + /badges/checkBadgeAndAward: + post: + tags: + - badge-controller + summary: Check badges for current user and award newly unlocked ones + operationId: checkAndAwardBadges + responses: + "200": + description: Check successful /auth/user/registration: post: tags: @@ -257,7 +489,7 @@ paths: content: application/json: schema: - $ref: "#/components/schemas/LoginResponseDTO" + $ref: "#/components/schemas/RegistrationResponseDTO" "400": description: Ungültige Eingabedaten content: @@ -300,9 +532,9 @@ paths: content: application/json: schema: - $ref: "#/components/schemas/MinimalUserDTO" + $ref: "#/components/schemas/MaximalUserDTO" "404": - description: Nutzerprofil nicht gefunden + description: Der Nutzer existiert nicht content: application/json: {} /user/profile/{id}: @@ -327,6 +559,10 @@ paths: application/json: schema: $ref: "#/components/schemas/MinimalUserDTO" + "403": + description: Nutzerprofil darf nicht aufgerufen werden + content: + application/json: {} "404": description: Nutzerprofil nicht gefunden content: @@ -346,6 +582,114 @@ paths: type: array items: $ref: "#/components/schemas/TripDTO" + /routing/preferences/get: + get: + tags: + - routing-preferences-controller + summary: Get the routing preferences of the current user + description: Retrieves the routing preferences set by the authenticated user. + operationId: getRoutingPreferences + responses: + "200": + description: OK + content: + '*/*': + schema: + $ref: "#/components/schemas/RoutingPreferencesDTO" + /leaderboard/getLeaderboard: + get: + tags: + - leaderboard-controller + summary: Get the global score table + operationId: getLeaderboard + parameters: + - name: timeframe + in: query + required: true + schema: + type: string + enum: + - TOTAL + - MONTHLY + - WEEKLY + - name: field + in: query + required: true + schema: + type: string + responses: + "200": + description: Successfully retrieved global score table + content: + '*/*': + schema: + $ref: "#/components/schemas/Leaderboard" + "400": + description: Bad request + content: + '*/*': + schema: + $ref: "#/components/schemas/Leaderboard" + /leaderboard/getFriendLeaderboard: + get: + tags: + - leaderboard-controller + summary: Get the friend score table + operationId: getFriendLeaderboard + parameters: + - name: timeframe + in: query + required: true + schema: + type: string + enum: + - TOTAL + - MONTHLY + - WEEKLY + - name: field + in: query + required: true + schema: + type: string + responses: + "200": + description: Successfully retrieved friend score table + content: + '*/*': + schema: + $ref: "#/components/schemas/Leaderboard" + "400": + description: Bad request + content: + '*/*': + schema: + $ref: "#/components/schemas/Leaderboard" + /geocoding/reverse: + get: + tags: + - geocoding-controller + description: Returns the address at the given lat / lon. + operationId: reverse + parameters: + - name: lat + in: query + required: true + schema: + type: number + format: double + - name: lon + in: query + required: true + schema: + type: number + format: double + responses: + "200": + description: OK + content: + '*/*': + schema: + $ref: "#/components/schemas/AddressDTO" /friendship/blocked: get: tags: @@ -404,6 +748,190 @@ paths: type: array items: $ref: "#/components/schemas/FriendshipDTO" + /dev/test-notification-from-detected-regular-trip: + get: + tags: + - dev-controller + description: Testing endpoint that mocks the detection of regular trips and + then tests the alternative calculation and notification scheduling. + operationId: testNotificationFromDetectedRegularTrip + responses: + "200": + description: OK + content: + '*/*': + schema: + type: string + /dev/test-meteo: + get: + tags: + - dev-controller + operationId: testMeteoClient + responses: + "200": + description: OK + /dev/test-firebase-trend-notification/{fcm_token}: + get: + tags: + - dev-controller + description: Immediately sends a test notification of type TREND to the provided + FCM token. + operationId: SendTestTrendNotificationFirebase + parameters: + - name: fcm_token + in: path + required: true + schema: + type: string + responses: + "200": + description: OK + content: + '*/*': + schema: + type: string + /dev/test-firebase-regular-trip-notification/{fcm_token}: + get: + tags: + - dev-controller + description: Immediately sends a test notification of type REGULAR_TRIP_ALTERNATIVE + to the provided FCM token. + operationId: SendTestRegularTripAlternativeNotificationFirebase + parameters: + - name: fcm_token + in: path + required: true + schema: + type: string + responses: + "200": + description: OK + content: + '*/*': + schema: + type: string + /dev/test-firebase-adhoc-route-notification/{fcm_token}: + get: + tags: + - dev-controller + description: Immediately sends a test notification of type ADHOC_ALTERNATIVE + to the provided FCM token. + operationId: SendTestAdhocRouteNotificationFirebase + parameters: + - name: fcm_token + in: path + required: true + schema: + type: string + responses: + "200": + description: OK + content: + '*/*': + schema: + type: string + /dev/test-clean-old-notifications: + get: + tags: + - dev-controller + description: Tests the method cleaning old notifications from the database. + operationId: testCleanOldNotifications + responses: + "200": + description: OK + /dev/queue-test-notification: + get: + tags: + - dev-controller + description: Immediately queues a notification to the fcm key specified in application-dev.properties + to be processed by the notification queue. + operationId: queueTestNotification + responses: + "200": + description: OK + content: + '*/*': + schema: + type: string + /badges/getBadges/{userId}: + get: + tags: + - badge-controller + summary: Get Badges by user + operationId: getBadgesByUser + parameters: + - name: userId + in: path + required: true + schema: + type: integer + format: int64 + responses: + "200": + description: Badges retrieved successfully + content: + '*/*': + schema: + type: array + items: + $ref: "#/components/schemas/UserBadgeDTO" + "404": + description: No badges found for user + content: + '*/*': + schema: + type: array + items: + $ref: "#/components/schemas/UserBadgeDTO" + /badges/getBadge/{badgeId}: + get: + tags: + - badge-controller + summary: Get a badge by ID + operationId: getBadgeById + parameters: + - name: badgeId + in: path + required: true + schema: + type: integer + format: int64 + responses: + "200": + description: Badge retrieved successfully + content: + '*/*': + schema: + $ref: "#/components/schemas/Badge" + "404": + description: Badge not found + content: + '*/*': + schema: + $ref: "#/components/schemas/Badge" + /badges/getAllBadges: + get: + tags: + - badge-controller + summary: Get all badges + operationId: getAllBadges + responses: + "200": + description: Badges retrieved successfully + content: + '*/*': + schema: + type: array + items: + $ref: "#/components/schemas/Badge" + "404": + description: No badges found + content: + '*/*': + schema: + type: array + items: + $ref: "#/components/schemas/Badge" /user/delete/{id}: delete: tags: @@ -423,11 +951,21 @@ paths: "200": description: Nutzerprofil erfolgreich gelöscht content: - application/json: {} - "404": - description: Nutzerprofil nicht gefunden + '*/*': + schema: + type: object + "403": + description: "Keine Berechtigung, fremdes Profil zu löschen" content: - application/json: {} + '*/*': + schema: + type: object + "404": + description: Der Nutzer existiert nicht + content: + '*/*': + schema: + type: object /friendship/unfriend/{friendId}: delete: tags: @@ -446,74 +984,26 @@ paths: responses: "200": description: OK + /badges/deleteBadge/{badgeId}: + delete: + tags: + - badge-controller + summary: Delete a badge by ID + operationId: deleteBadgeById + parameters: + - name: badgeId + in: path + required: true + schema: + type: integer + format: int64 + responses: + "200": + description: Badge deleted successfully + "404": + description: Badge not found components: schemas: - NewTripDTO: - type: object - description: DTO for creating a new Trip - properties: - startPlace: - type: string - endPlace: - type: string - startTime: - type: string - format: date-time - endTime: - type: string - format: date-time - mobilityScore: - type: number - format: float - tripSegments: - type: array - items: - $ref: "#/components/schemas/NewTripSegmentDTO" - maxItems: 2147483647 - minItems: 1 - uniqueItems: true - required: - - tripSegments - NewTripSegmentDTO: - type: object - properties: - modality: - type: string - enum: - - IDLE - - WALKING - - BIKE - - ESCOOTER - - BUS - - TRAM - - TRAIN - - CAR - startTime: - type: string - format: date-time - distanceMeters: - type: number - format: float - RouteAlternativeRequestDTO: - type: object - RouteAlternativeDTO: - type: object - UserRegistrationDTO: - type: object - properties: - privateName: - type: string - publicName: - type: string - email: - type: string - password: - type: string - required: - - email - - password - - privateName - - publicName LoginResponseDTO: type: object properties: @@ -542,6 +1032,322 @@ components: id: type: integer format: int64 + RoutingPreferencesDTO: + type: object + description: This DTO represents the user preferences for routing / alternative + route suggestions. + properties: + preferPhysicalActivity: + type: boolean + considerWeatherConditions: + type: boolean + modalitiesToConsider: + type: array + items: + type: string + enum: + - IDLE + - WALKING + - BICYCLE + - ESCOOTER + - BUS + - TRAM + - TRAIN + - CAR + - MOTORCYCLE + - TAXI + RegisterDeviceTokenRequest: + type: object + properties: + token: + type: string + provider: + type: string + enum: + - FIREBASE + Badge: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + description: + type: string + criteria: + type: object + additionalProperties: + type: integer + format: int32 + AddStatRequestDTO: + type: object + properties: + stat: + type: string + value: + type: integer + format: int64 + minimum: 0 + scope: + type: string + enum: + - TOTAL + - MONTHLY + - WEEKLY + - ALL + awardBadges: + type: boolean + required: + - stat + - value + NewTripDTO: + type: object + description: DTO for creating a new Trip + properties: + startPlace: + type: string + description: High level description of the trip's starting location + startLatitude: + type: number + format: double + startLongitude: + type: number + format: double + endPlace: + type: string + description: High level description of the trip's ending location + endLatitude: + type: number + format: double + endLongitude: + type: number + format: double + startTime: + type: string + format: date-time + endTime: + type: string + format: date-time + mobilityScore: + type: number + format: double + co2Emissions: + type: number + format: double + tripSegments: + type: array + items: + $ref: "#/components/schemas/NewTripSegmentDTO" + maxItems: 2147483647 + minItems: 1 + uniqueItems: true + required: + - tripSegments + NewTripSegmentDTO: + type: object + properties: + modality: + type: string + enum: + - IDLE + - WALKING + - BICYCLE + - ESCOOTER + - BUS + - TRAM + - TRAIN + - CAR + - MOTORCYCLE + - TAXI + startTime: + type: string + format: date-time + distanceMeters: + type: number + format: float + RoutingAlternativeRequestDTO: + type: object + description: This DTO represents a request for alternative routes between an + origin and a destination. + properties: + originLat: + type: number + format: double + originLon: + type: number + format: double + destinationLat: + type: number + format: double + destinationLon: + type: number + format: double + arrivalTime: + type: string + format: date-time + departureTime: + type: string + format: date-time + routingPreferencesDTO: + $ref: "#/components/schemas/RoutingPreferencesDTO" + required: + - arrivalTime + - departureTime + - destinationLat + - destinationLon + - originLat + - originLon + AddressDTO: + type: object + properties: + houseNumber: + type: string + road: + type: string + suburb: + type: string + cityDistrict: + type: string + city: + type: string + state: + type: string + iso3166_2_lvl4: + type: string + postcode: + type: string + country: + type: string + countryCode: + type: string + RouteDTO: + type: object + description: This DTO represents a suggested route as a response to a requested + alternative route. + properties: + startAddress: + $ref: "#/components/schemas/AddressDTO" + description: The actual address of the start location. + firstStopName: + type: string + description: The name of the first stop if the route uses public transport. + E.g. "Essen West" if the route starts with a footpath to the first train + leaving there. + startLat: + type: number + format: double + description: The latitude of the start address. + startLon: + type: number + format: double + description: The longitude of the start address. + endAddress: + $ref: "#/components/schemas/AddressDTO" + description: The actual address of the end location. + lastStopName: + type: string + description: The name of the last stop if the route uses public transport. + E.g. "Essen Hbf" if the route ends with a train arriving there (might + still contain a footpath afterwards). + endLat: + type: number + format: double + description: The latitude of the end address. + endLon: + type: number + format: double + description: The longitude of the end address. + startDateTime: + type: string + format: date-time + description: The start date and time of the route. + endDateTime: + type: string + format: date-time + description: The end date and time of the route. + steps: + type: array + description: The steps the route consists of. + items: + $ref: "#/components/schemas/StepDTO" + co2Savings: + type: number + format: double + description: Amount of CO2e savings in gramm compared to a car trip for + the same route. + co2Emissions: + type: number + format: double + description: CO2e emission of this route. + timeDifferenceSeconds: + type: number + format: double + description: The temporal difference in minutes compared to the original + route the user requested alternatives for. + durationSeconds: + type: integer + format: int64 + physicalActivity: + type: boolean + cyclingRoute: + type: boolean + walkingRoute: + type: boolean + StepDTO: + type: object + description: A single step within a suggested alternative route. + properties: + modality: + type: string + enum: + - IDLE + - WALKING + - BICYCLE + - ESCOOTER + - BUS + - TRAM + - TRAIN + - CAR + - MOTORCYCLE + - TAXI + lineNumber: + type: string + distanceMeters: + type: number + format: double + UserRegistrationDTO: + type: object + properties: + privateName: + type: string + publicName: + type: string + email: + type: string + password: + type: string + required: + - email + - password + - privateName + - publicName + RegistrationResponseDTO: + type: object + properties: + userDTO: + $ref: "#/components/schemas/UserDTO" + jwt: + type: string + status: + type: string + enum: + - SUCCESS + - EMAIL_EXISTS + - EMAIL_INVALID + - PUBLIC_NAME_EXISTS + - PUBLIC_NAME_FORBIDDEN + - UNKNOWN_ERROR UserAuthenticationPairDTO: type: object properties: @@ -552,6 +1358,298 @@ components: required: - email - password + Friendship: + type: object + properties: + id: + type: integer + format: int64 + user: + $ref: "#/components/schemas/User" + friend: + $ref: "#/components/schemas/User" + status: + type: string + enum: + - REQUESTED + - PENDING + - ACCEPTED + - REJECTED + - BLOCKED + createdAt: + type: string + format: date-time + MaximalUserDTO: + type: object + properties: + id: + type: integer + format: int64 + publicName: + type: string + privateName: + type: string + email: + type: string + visibilityPrivacy: + type: string + enum: + - NONE + - FRIENDS_ONLY + - PUBLIC + trips: + type: array + items: + $ref: "#/components/schemas/Trip" + uniqueItems: true + friendships: + type: array + items: + $ref: "#/components/schemas/Friendship" + uniqueItems: true + NotificationToken: + type: object + properties: + userId: + type: integer + format: int64 + provider: + type: string + enum: + - FIREBASE + token: + type: string + RoutingPreferences: + type: object + properties: + id: + type: integer + format: int64 + user: + $ref: "#/components/schemas/User" + preferPhysicalActivity: + type: boolean + considerWeatherConditions: + type: boolean + modalitiesToConsider: + type: array + items: + type: string + enum: + - IDLE + - WALKING + - BICYCLE + - ESCOOTER + - BUS + - TRAM + - TRAIN + - CAR + - MOTORCYCLE + - TAXI + Stats: + type: object + properties: + statsList: + $ref: "#/components/schemas/StatsList" + description: The StatsList to which these stats belong. + xp: + type: integer + format: int64 + co2_SAVED: + type: integer + format: int64 + km_CYCLED: + type: integer + format: int64 + km_WALKED: + type: integer + format: int64 + km_PUBLIC_TRANSPORT: + type: integer + format: int64 + km_DRIVEN: + type: integer + format: int64 + mobility_SCORE: + type: integer + format: int64 + required: + - statsList + StatsList: + type: object + properties: + id: + type: integer + format: int64 + description: Unique identifier of the StatsList. + example: 1 + user: + $ref: "#/components/schemas/User" + description: The User to whom this StatsList belongs. + totalStats: + $ref: "#/components/schemas/Stats" + description: Total stats of the user. + monthlyStats: + $ref: "#/components/schemas/Stats" + description: Monthly stats of the user. + weeklyStats: + $ref: "#/components/schemas/Stats" + description: Weekly stats of the user. + Trip: + type: object + properties: + id: + type: integer + format: int64 + user: + $ref: "#/components/schemas/User" + startPlace: + type: string + startLatitude: + type: number + format: double + startLongitude: + type: number + format: double + startH3Cell: + type: string + endPlace: + type: string + endLatitude: + type: number + format: double + endLongitude: + type: number + format: double + endH3Cell: + type: string + startTime: + type: string + format: date-time + endTime: + type: string + format: date-time + mobilityScore: + type: number + format: double + co2Emissions: + type: number + format: double + cost: + type: number + format: float + invalidated: + type: boolean + mainModality: + type: string + description: Main modality by distance. + enum: + - IDLE + - WALKING + - BICYCLE + - ESCOOTER + - BUS + - TRAM + - TRAIN + - CAR + - MOTORCYCLE + - TAXI + tripSegments: + type: array + items: + $ref: "#/components/schemas/TripSegment" + uniqueItems: true + TripSegment: + type: object + properties: + id: + type: integer + format: int64 + trip: + $ref: "#/components/schemas/Trip" + modality: + type: string + enum: + - IDLE + - WALKING + - BICYCLE + - ESCOOTER + - BUS + - TRAM + - TRAIN + - CAR + - MOTORCYCLE + - TAXI + startTime: + type: string + format: date-time + distanceMeters: + type: integer + format: int64 + User: + type: object + properties: + id: + type: integer + format: int64 + publicName: + type: string + privateName: + type: string + email: + type: string + password: + type: string + visibilityPrivacy: + type: string + enum: + - NONE + - FRIENDS_ONLY + - PUBLIC + friendCode: + type: string + trips: + type: array + items: + $ref: "#/components/schemas/Trip" + uniqueItems: true + friendships: + type: array + items: + $ref: "#/components/schemas/Friendship" + uniqueItems: true + roles: + type: array + items: + type: string + enum: + - USER + - ADMIN + uniqueItems: true + notificationToken: + $ref: "#/components/schemas/NotificationToken" + badges: + type: array + items: + $ref: "#/components/schemas/UserBadge" + uniqueItems: true + routingPreferences: + $ref: "#/components/schemas/RoutingPreferences" + stats: + $ref: "#/components/schemas/StatsList" + UserBadge: + type: object + properties: + id: + type: integer + format: int64 + user: + $ref: "#/components/schemas/User" + badge: + $ref: "#/components/schemas/Badge" + awardedAt: + type: string + format: date-time MinimalUserDTO: type: object properties: @@ -562,6 +1660,8 @@ components: type: string TripDTO: type: object + description: Represents a trip uploaded to the backend by a user that is already + stored in the DB. properties: tripId: type: integer @@ -571,8 +1671,20 @@ components: format: int32 startPlace: type: string + startLatitude: + type: number + format: double + startLongitude: + type: number + format: double endPlace: type: string + endLatitude: + type: number + format: double + endLongitude: + type: number + format: double startTime: type: string format: date-time @@ -581,11 +1693,16 @@ components: format: date-time mobilityScore: type: number - format: float + format: double + co2Emissions: + type: number + format: double tripSegments: type: array items: $ref: "#/components/schemas/TripSegmentDTO" + invalidated: + type: boolean TripSegmentDTO: type: object properties: @@ -600,18 +1717,52 @@ components: enum: - IDLE - WALKING - - BIKE + - BICYCLE - ESCOOTER - BUS - TRAM - TRAIN - CAR + - MOTORCYCLE + - TAXI startTime: type: string format: date-time distanceMeters: type: number format: float + Leaderboard: + type: object + properties: + timeframe: + type: string + enum: + - TOTAL + - MONTHLY + - WEEKLY + entries: + type: array + items: + $ref: "#/components/schemas/LeaderboardEntry" + scoreType: + type: string + enum: + - XP + - CO2 + - KM + LeaderboardEntry: + type: object + properties: + userId: + type: integer + format: int64 + username: + type: string + isFriend: + type: boolean + score: + type: integer + format: int64 FriendshipDTO: type: object properties: @@ -634,6 +1785,24 @@ components: createdAt: type: string format: date-time + UserBadgeDTO: + type: object + properties: + badgeId: + type: integer + format: int64 + name: + type: string + description: + type: string + criteria: + type: object + additionalProperties: + type: integer + format: int32 + awardedAt: + type: string + format: date-time securitySchemes: bearerAuth: type: http diff --git a/pom.xml b/pom.xml index 97d5e66..ca765aa 100644 --- a/pom.xml +++ b/pom.xml @@ -54,6 +54,10 @@ org.springframework.boot spring-boot-starter-validation + + org.springframework.boot + spring-boot-starter-thymeleaf + com.h2database h2 diff --git a/src/main/java/SuMoC/backend/logger/LogPageController.java b/src/main/java/SuMoC/backend/logger/LogPageController.java new file mode 100644 index 0000000..5e5555c --- /dev/null +++ b/src/main/java/SuMoC/backend/logger/LogPageController.java @@ -0,0 +1,20 @@ +package SuMoC.backend.logger; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +@Controller +public class LogPageController { + + @GetMapping("/logs") + public String logs(Model model) throws IOException { + String content = Files.readString(Path.of("logs/app.log")); + model.addAttribute("logs", content); + return "logs"; + } +} \ No newline at end of file diff --git a/src/main/java/SuMoC/backend/security/SecurityConfiguration.java b/src/main/java/SuMoC/backend/security/SecurityConfiguration.java index efd98ae..717d643 100644 --- a/src/main/java/SuMoC/backend/security/SecurityConfiguration.java +++ b/src/main/java/SuMoC/backend/security/SecurityConfiguration.java @@ -91,6 +91,7 @@ public class SecurityConfiguration { auth.requestMatchers(AUTH_WHITELIST).permitAll(); auth.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll(); auth.requestMatchers("/dev/**").permitAll(); + auth.requestMatchers("/logs").permitAll(); auth.requestMatchers("/routing/alternative/**").permitAll(); auth.requestMatchers("/auth/user/**").permitAll(); auth.requestMatchers("/admin/**").hasRole("ADMIN"); //looks for "ROLE_ADMIN" //alternative: hasAuthoritiy("ADMIN") diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index ede5695..bf0c224 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -35,3 +35,5 @@ sumoc.dev.fcm-key=dmydW4a_RjKCDjcBLZ9Kl8:APA91bFjBIjw8NcjeMIsNkfPuW9jhMlK3n_LHoG # RSA key paths (file paths, not directories) security.rsa.private-key-path=${RSA_PRIVATE_KEY_PATH:${user.home}/.sumoc/keys/jwt-private.pem} security.rsa.public-key-path=${RSA_PUBLIC_KEY_PATH:${user.home}/.sumoc/keys/jwt-public.pem} + +logging.file.name=logs/app.log diff --git a/src/main/resources/templates/logs.html b/src/main/resources/templates/logs.html new file mode 100644 index 0000000..0ea9ae5 --- /dev/null +++ b/src/main/resources/templates/logs.html @@ -0,0 +1,62 @@ + + + + + Server Logs + + + +
📝 Server Logs
+
+

+
+ + From edabef4fb3cdb15613f6a88c7ab35d2ec76b378e Mon Sep 17 00:00:00 2001 From: Lukas Laaser Date: Fri, 23 Jan 2026 15:09:22 +0100 Subject: [PATCH 57/61] Manually auth for Leaderboard --- .../scoretable/LeaderboardController.java | 10 ++++---- .../scoretable/LeaderboardService.java | 24 ++++++++++--------- .../user/service/LeaderboardServiceTest.java | 8 +++---- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/main/java/SuMoC/backend/gamification/scoretable/LeaderboardController.java b/src/main/java/SuMoC/backend/gamification/scoretable/LeaderboardController.java index 87f59c2..7e3c58b 100644 --- a/src/main/java/SuMoC/backend/gamification/scoretable/LeaderboardController.java +++ b/src/main/java/SuMoC/backend/gamification/scoretable/LeaderboardController.java @@ -32,10 +32,9 @@ class LeaderboardController { }) @GetMapping("/getLeaderboard") - public ResponseEntity getLeaderboard(@AuthenticationPrincipal User user, - @RequestParam Timeframe timeframe, + public ResponseEntity getLeaderboard(@RequestParam Timeframe timeframe, @RequestParam String field) { - Leaderboard leaderboard = this.leaderboardService.getLeaderboard(user, timeframe, field); + Leaderboard leaderboard = this.leaderboardService.getLeaderboard(timeframe, field); return ResponseEntity.status(HttpStatus.OK).body(leaderboard); } @@ -45,10 +44,9 @@ class LeaderboardController { @ApiResponse(responseCode = "400", description = "Bad request") }) @GetMapping("/getFriendLeaderboard") - public ResponseEntity getFriendLeaderboard(@AuthenticationPrincipal User user, - @RequestParam Timeframe timeframe, + public ResponseEntity getFriendLeaderboard(@RequestParam Timeframe timeframe, @RequestParam String field) { - Leaderboard leaderboard = this.leaderboardService.getFriendLeaderboard(user, timeframe, field); + Leaderboard leaderboard = this.leaderboardService.getFriendLeaderboard(timeframe, field); return ResponseEntity.status(HttpStatus.OK).body(leaderboard); } } diff --git a/src/main/java/SuMoC/backend/gamification/scoretable/LeaderboardService.java b/src/main/java/SuMoC/backend/gamification/scoretable/LeaderboardService.java index 44dc2d6..e3bc930 100644 --- a/src/main/java/SuMoC/backend/gamification/scoretable/LeaderboardService.java +++ b/src/main/java/SuMoC/backend/gamification/scoretable/LeaderboardService.java @@ -4,6 +4,7 @@ import SuMoC.backend.gamification.scoretable.models.Leaderboard; import SuMoC.backend.gamification.Timeframe; import SuMoC.backend.gamification.scoretable.models.LeaderboardEntry; import SuMoC.backend.user.models.User; +import SuMoC.backend.user.service.CurrentUserService; import SuMoC.backend.user.service.FriendshipService; import SuMoC.backend.user.stats.*; import org.springframework.data.domain.PageRequest; @@ -21,36 +22,37 @@ import java.util.stream.Collectors; public class LeaderboardService { private final FriendshipService friendshipService; private final StatsListRepository statsListRepository; + private final CurrentUserService currentUser; public LeaderboardService( FriendshipService friendshipService, - StatsListRepository statsListRepository - ) { + StatsListRepository statsListRepository, + CurrentUserService currentUserService) { this.friendshipService = friendshipService; this.statsListRepository = statsListRepository; + this.currentUser = currentUserService; } /** * Method Overload to get the score table with a default limit of 30. - * @param user * @param timeframe * @param field * @return */ - public Leaderboard getLeaderboard(User user, Timeframe timeframe, String field) { - return getLeaderboard(user, timeframe, field, 30); + public Leaderboard getLeaderboard(Timeframe timeframe, String field) { + return getLeaderboard(timeframe, field, 30); } /** * Get the global score table for a given user, timeframe, score type, and limit. - * @param user * @param timeframe * @param field * @param limit * @return */ - public Leaderboard getLeaderboard(User user, Timeframe timeframe, String field, int limit) { + public Leaderboard getLeaderboard(Timeframe timeframe, String field, int limit) { + User user = currentUser.get(); List topStats = getTopStats(timeframe, field, limit); List topUserIds = topStats.stream() @@ -108,20 +110,20 @@ public class LeaderboardService { * @param field * @return */ - public Leaderboard getFriendLeaderboard(User user, Timeframe timeframe, String field) { - return getFriendLeaderboard(user, timeframe, field, 30); + public Leaderboard getFriendLeaderboard(Timeframe timeframe, String field) { + return getFriendLeaderboard(timeframe, field, 30); } /** * Get the friend score table for a given user, timeframe, score type, and limit. - * @param user * @param timeframe * @param field * @param limit * @return */ - public Leaderboard getFriendLeaderboard(User user, Timeframe timeframe, String field, int limit) { + public Leaderboard getFriendLeaderboard(Timeframe timeframe, String field, int limit) { + User user = currentUser.get(); List friends = friendshipService.getAcceptedFriends(user); Leaderboard leaderboard = new Leaderboard(); diff --git a/src/test/java/SuMoC/backend/user/service/LeaderboardServiceTest.java b/src/test/java/SuMoC/backend/user/service/LeaderboardServiceTest.java index b4d9638..9efd84d 100644 --- a/src/test/java/SuMoC/backend/user/service/LeaderboardServiceTest.java +++ b/src/test/java/SuMoC/backend/user/service/LeaderboardServiceTest.java @@ -89,7 +89,7 @@ public class LeaderboardServiceTest { @Test @WithMockUser(username = "test1@test.de", roles = {"USER"}) public void testGetLeaderboard() { - Leaderboard xpLeaderboard = leaderboardService.getLeaderboard(sender, Timeframe.TOTAL, "XP"); + Leaderboard xpLeaderboard = leaderboardService.getLeaderboard(Timeframe.TOTAL, "XP"); assertNotNull(xpLeaderboard); assertEquals(10, xpLeaderboard.getEntries().size()); @@ -136,8 +136,8 @@ public class LeaderboardServiceTest { // Test the weekly reset statsService.resetWeeklyStats(); - Leaderboard totalStats = leaderboardService.getLeaderboard(sender, Timeframe.TOTAL, "XP"); - Leaderboard weeklyStats = leaderboardService.getLeaderboard(sender, Timeframe.WEEKLY, "XP"); + Leaderboard totalStats = leaderboardService.getLeaderboard(Timeframe.TOTAL, "XP"); + Leaderboard weeklyStats = leaderboardService.getLeaderboard(Timeframe.WEEKLY, "XP"); for (LeaderboardEntry entry : totalStats.getEntries()) { assertEquals(entry.getScore(), xpLeaderboard.getEntries().stream() @@ -158,7 +158,7 @@ public class LeaderboardServiceTest { @Test @WithMockUser(username = "test1@test.de", roles = {"USER"}) public void testGetFriendLeaderboard() { - Leaderboard friendLeaderboard = leaderboardService.getFriendLeaderboard(sender, Timeframe.TOTAL, "XP"); + Leaderboard friendLeaderboard = leaderboardService.getFriendLeaderboard(Timeframe.TOTAL, "XP"); assertNotNull(friendLeaderboard); assertEquals(5, friendLeaderboard.getEntries().size()); assertEquals(friendLeaderboard.getEntries().getFirst().getUserId(), sender.getId()); From fb49fa2130575f2b09b4b6e2aa65ebef7fea5e64 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Sun, 25 Jan 2026 18:22:17 +0100 Subject: [PATCH 58/61] prevent error when firebase is already inited --- .../backend/firebase/FirebaseConfiguration.java | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/main/java/SuMoC/backend/firebase/FirebaseConfiguration.java b/src/main/java/SuMoC/backend/firebase/FirebaseConfiguration.java index 36bd219..6f60364 100644 --- a/src/main/java/SuMoC/backend/firebase/FirebaseConfiguration.java +++ b/src/main/java/SuMoC/backend/firebase/FirebaseConfiguration.java @@ -28,13 +28,18 @@ public class FirebaseConfiguration { @Bean FirebaseApp firebaseApp(GoogleCredentials credentials) { - FirebaseOptions options = FirebaseOptions.builder() - .setCredentials(credentials) - .build(); - - return FirebaseApp.initializeApp(options); + try { + return FirebaseApp.getInstance(); + } catch (IllegalStateException e) { + // App doesn't exist yet, create it + FirebaseOptions options = FirebaseOptions.builder() + .setCredentials(credentials) + .build(); + return FirebaseApp.initializeApp(options); + } } + @Bean GoogleCredentials googleCredentials(FirebaseProperties firebaseProperties) throws IOException { if (firebaseProperties.serviceAccount() != null) { From 607ce804da5c0dd55637452ea4a3115c0ee33dd0 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Mon, 26 Jan 2026 16:24:03 +0100 Subject: [PATCH 59/61] seed davids test user --- .../java/SuMoC/backend/seed/user/DevUserSeeder.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java b/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java index 1e58d73..e695098 100644 --- a/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java +++ b/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java @@ -62,5 +62,18 @@ public class DevUserSeeder implements CommandLineRunner { NotificationProvider.FIREBASE, devProperties.getFcmKey() ); + UserRegistrationDTO user3dto = UserRegistrationDTO.builder() + .email("david@test.com") + .publicName("David N. Public") + .privateName("David N. Privat") + .password("davidsPassword") + .build(); + authenticationService.registerUser(user3dto); + User user3 = userRepository.findByEmail("david@test.com").orElseThrow(); + notificationTokenService.registerDeviceToken( + user3, + NotificationProvider.FIREBASE, + devProperties.getFcmKey() + ); } } From fb0989ef95d2d9bec345e6f5559e35db28c2d18e Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Mon, 26 Jan 2026 16:24:15 +0100 Subject: [PATCH 60/61] run application in berlin timezone --- docker-compose.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docker-compose.yml b/docker-compose.yml index 6505e9e..71852c7 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -13,6 +13,7 @@ services: env_file: - .env environment: + TZ: Europe/Berlin FCM_DECRYPTION_KEY: ${FCM_DECRYPTION_KEY} RSA_PRIVATE_KEY_PATH: /data/keys/jwt-private.pem RSA_PUBLIC_KEY_PATH: /data/keys/jwt-public.pem @@ -26,6 +27,7 @@ services: image: postgres:16.2-alpine container_name: sumoc_db environment: + - TZ=Europe/Berlin - POSTGRES_USER=postgres - POSTGRES_PASSWORD=admin - POSTGRES_DB=sumoc From c6fe80145b6822fdb925fbad1325984bab118e93 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Tue, 27 Jan 2026 11:15:18 +0100 Subject: [PATCH 61/61] add test user for all pg members --- .../backend/seed/user/DevUserSeeder.java | 117 ++++++++++++++++++ 1 file changed, 117 insertions(+) diff --git a/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java b/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java index e695098..e50ac89 100644 --- a/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java +++ b/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java @@ -75,5 +75,122 @@ public class DevUserSeeder implements CommandLineRunner { NotificationProvider.FIREBASE, devProperties.getFcmKey() ); + UserRegistrationDTO user4dto = UserRegistrationDTO.builder() + .email("davidm@test.com") + .publicName("David M Public") + .privateName("David M Private") + .password("password") + .build(); + authenticationService.registerUser(user4dto); + User user4 = userRepository.findByEmail("davidm@test.com").orElseThrow(); + notificationTokenService.registerDeviceToken( + user4, + NotificationProvider.FIREBASE, + devProperties.getFcmKey() + ); + UserRegistrationDTO user5dto = UserRegistrationDTO.builder() + .email("freddie@test.com") + .publicName("Freddie Public") + .privateName("Freddie Private") + .password("password") + .build(); + authenticationService.registerUser(user5dto); + User user5 = userRepository.findByEmail("freddie@test.com").orElseThrow(); + notificationTokenService.registerDeviceToken( + user5, + NotificationProvider.FIREBASE, + devProperties.getFcmKey() + ); + UserRegistrationDTO user6dto = UserRegistrationDTO.builder() + .email("elias@test.com") + .publicName("Elias Public") + .privateName("Elias Private") + .password("password") + .build(); + authenticationService.registerUser(user6dto); + User user6 = userRepository.findByEmail("elias@test.com").orElseThrow(); + notificationTokenService.registerDeviceToken( + user6, + NotificationProvider.FIREBASE, + devProperties.getFcmKey() + ); + UserRegistrationDTO user7dto = UserRegistrationDTO.builder() + .email("ibrahim@test.com") + .publicName("Ibrahim Public") + .privateName("Ibrahim Private") + .password("password") + .build(); + authenticationService.registerUser(user7dto); + User user7 = userRepository.findByEmail("ibrahim@test.com").orElseThrow(); + notificationTokenService.registerDeviceToken( + user7, + NotificationProvider.FIREBASE, + devProperties.getFcmKey() + ); + UserRegistrationDTO user8dto = UserRegistrationDTO.builder() + .email("lukas@test.com") + .publicName("Lukas Public") + .privateName("Lukas Private") + .password("password") + .build(); + authenticationService.registerUser(user8dto); + User user8 = userRepository.findByEmail("lukas@test.com").orElseThrow(); + notificationTokenService.registerDeviceToken( + user8, + NotificationProvider.FIREBASE, + devProperties.getFcmKey() + ); + UserRegistrationDTO user9dto = UserRegistrationDTO.builder() + .email("dennis@test.com") + .publicName("Dennis Public") + .privateName("Dennis Private") + .password("password") + .build(); + authenticationService.registerUser(user9dto); + User user9 = userRepository.findByEmail("dennis@test.com").orElseThrow(); + notificationTokenService.registerDeviceToken( + user9, + NotificationProvider.FIREBASE, + devProperties.getFcmKey() + ); + UserRegistrationDTO user10dto = UserRegistrationDTO.builder() + .email("daniel@test.com") + .publicName("Daniel Public") + .privateName("Daniel Private") + .password("password") + .build(); + authenticationService.registerUser(user10dto); + User user10 = userRepository.findByEmail("daniel@test.com").orElseThrow(); + notificationTokenService.registerDeviceToken( + user10, + NotificationProvider.FIREBASE, + devProperties.getFcmKey() + ); + UserRegistrationDTO user11dto = UserRegistrationDTO.builder() + .email("markus@test.com") + .publicName("Markus Public") + .privateName("Markus Private") + .password("password") + .build(); + authenticationService.registerUser(user11dto); + User user11 = userRepository.findByEmail("markus@test.com").orElseThrow(); + notificationTokenService.registerDeviceToken( + user11, + NotificationProvider.FIREBASE, + devProperties.getFcmKey() + ); + UserRegistrationDTO user12dto = UserRegistrationDTO.builder() + .email("piet@test.com") + .publicName("Piet Public") + .privateName("Piet Private") + .password("password") + .build(); + authenticationService.registerUser(user12dto); + User user12 = userRepository.findByEmail("piet@test.com").orElseThrow(); + notificationTokenService.registerDeviceToken( + user12, + NotificationProvider.FIREBASE, + devProperties.getFcmKey() + ); } }