Author SHA1 Message Date
neuhauss e3b218637b WIP - upload shelf from work computer
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-03 18:37:31 +01:00
9 changed files with 293 additions and 23 deletions
@@ -13,6 +13,8 @@ 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.enums.DeltaType;
import SuMoC.backend.trend.enums.StatAttribute;
import SuMoC.backend.trend.services.StatTableUpdateService;
import SuMoC.backend.user.dtos.FriendshipDTO;
import SuMoC.backend.user.dtos.MinimalUserDTO;
@@ -38,6 +40,8 @@ import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import static SuMoC.backend.trend.enums.StatAttribute.MOBILITY_SCORE_PER_KM;
@RestController
@RequestMapping("/dev")
@Profile("dev")
@@ -90,9 +94,9 @@ public class DevController {
statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(day3WeeksAgo);
}
@GetMapping("/test-firebase-trend-notification/{fcm_token}")
@Operation(description = "Immediately sends a test notification of type TREND to the provided FCM token.")
public ResponseEntity<String> SendTestTrendNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
@GetMapping("/test-firebase-trend-notification-car-km/{fcm_token}")
@Operation(description = "Immediately sends a test notification of type TREND for CAR KM to the provided FCM token.")
public ResponseEntity<String> SendTestTrendNotificationCarKmFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
if (firebaseMessaging == null) {
return ResponseEntity.status(503)
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
@@ -114,6 +118,60 @@ public class DevController {
}
}
@GetMapping("/test-firebase-trend-notification-mobilityscore-per-km/{fcm_token}")
@Operation(description = "Immediately sends a test notification of type TREND for MOBILITY_SCORE_PER_KM to the provided FCM token.")
public ResponseEntity<String> SendTestTrendNotificationMobilityScoreFirebase(@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);
TrendDetectionDTO dto = TrendDetectionDTO.mockTrendDetectionDTO();
dto.setDeltaType(DeltaType.PERCENTAGE);
dto.setAttribute(MOBILITY_SCORE_PER_KM);
notification.setData(objectMapper.writeValueAsString(dto));
Message mockTrendMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
// Send to a topic (no device registration needed)
String message = firebaseMessaging.sendAsync(
mockTrendMessage
).get();
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
} catch (Exception e) {
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
}
}
@GetMapping("/test-firebase-trend-notification-walk-bike-km/{fcm_token}")
@Operation(description = "Immediately sends a test notification of type TREND for WALKING_AND_CYCLING_DISTANCE to the provided FCM token.")
public ResponseEntity<String> SendTestTrendNotificationWalkBikeKmFirebase(@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);
TrendDetectionDTO dto = TrendDetectionDTO.mockTrendDetectionDTO();
dto.setDeltaType(DeltaType.PERCENTAGE);
dto.setAttribute(StatAttribute.WALKING_AND_CYLING_DISTANCE);
notification.setData(objectMapper.writeValueAsString(dto));
Message mockTrendMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
// Send to a topic (no device registration needed)
String message = firebaseMessaging.sendAsync(
mockTrendMessage
).get();
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
} catch (Exception e) {
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
}
}
@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<String> SendTestAdhocRouteNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
@@ -25,5 +25,5 @@ public class TrendProperties {
* 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);
private LocalTime earliestTrendNotificationTimeOfDay = LocalTime.of(10, 0);
}
@@ -34,11 +34,15 @@ public class TrendDetectionDTO implements Notifieable {
if (this.type == TrendType.INCREASING) {
return switch (attribute) {
case CAR_DISTANCE -> TrendConnotation.NEGATIVE;
case MOBILITY_SCORE_PER_KM -> TrendConnotation.POSITIVE;
case WALKING_AND_CYLING_DISTANCE -> TrendConnotation.POSITIVE;
default -> TrendConnotation.NEUTRAL;
};
} else if (type == TrendType.DECREASING) {
return switch (attribute) {
case CAR_DISTANCE -> TrendConnotation.POSITIVE;
case MOBILITY_SCORE_PER_KM -> TrendConnotation.NEGATIVE;
case WALKING_AND_CYLING_DISTANCE -> TrendConnotation.NEGATIVE;
default -> TrendConnotation.NEUTRAL;
};
} else {
@@ -5,4 +5,6 @@ package SuMoC.backend.trend.enums;
*/
public enum StatAttribute {
CAR_DISTANCE,
MOBILITY_SCORE_PER_KM,
WALKING_AND_CYLING_DISTANCE
}
@@ -79,9 +79,11 @@ public class WeeklyMobilityStats {
@Column(nullable = false)
private Long sumMetersTaxi = 0L;
public Long getValueFor(StatAttribute attribute) {
public Double getValueFor(StatAttribute attribute) {
return switch (attribute) {
case CAR_DISTANCE -> sumMetersCar;
case MOBILITY_SCORE_PER_KM -> totalDistance == 0 ? 0.0 : (sumMobilityScore * 1000.0) / totalDistance;
case WALKING_AND_CYLING_DISTANCE -> sumMetersWalkingAndCycling.doubleValue();
case CAR_DISTANCE -> sumMetersCar.doubleValue();
};
}
}
@@ -24,7 +24,16 @@ public class TrendDetectorService {
private final TrendProperties trendProperties;
public List<TrendDetectionDTO> detectWeeklyTrends(Integer year, Integer weekNumber, StatAttribute attribute) {
/**
* Detect weekly trends for the given year, week number, attribute, and delta type.
*
* @param year Specified year
* @param weekNumber Specified week number
* @param attribute The attribute to analyze
* @param deltaType The type of delta reported in the detected trend, detection is always based on percentage change.
* @return List of detected trends
*/
public List<TrendDetectionDTO> detectWeeklyTrends(Integer year, Integer weekNumber, StatAttribute attribute, DeltaType deltaType) {
// Fetch stats for current and previous week
List<WeeklyMobilityStats> previousWeekStatsList;
if (weekNumber > 1) {
@@ -55,24 +64,29 @@ public class TrendDetectorService {
if (previousValue != 0) {
double percentageChange = ((currentValue - previousValue) / previousValue) * 100.0;
double absoluteChange = currentValue - previousValue;
if (percentageChange >= trendProperties.getPositiveThreshold()) {
var changeValue = deltaType == DeltaType.PERCENTAGE ? percentageChange : absoluteChange;
detectedTrends.add(new TrendDetectionDTO(
currentStats.getUser().getId(),
TrendTimespan.WEEKLY,
TrendType.INCREASING,
StatAttribute.CAR_DISTANCE,
DeltaType.PERCENTAGE,
percentageChange
attribute,
deltaType,
changeValue
));
} else if (percentageChange <= trendProperties.getNegativeThreshold()) {
var changeValue = deltaType == DeltaType.PERCENTAGE ? percentageChange : absoluteChange;
detectedTrends.add(new TrendDetectionDTO(
previousStats.getUser().getId(),
TrendTimespan.WEEKLY,
TrendType.DECREASING,
StatAttribute.CAR_DISTANCE,
DeltaType.PERCENTAGE,
percentageChange
attribute,
deltaType,
changeValue
));
}
}
@@ -3,6 +3,7 @@ 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.DeltaType;
import SuMoC.backend.trend.enums.StatAttribute;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@@ -23,9 +24,14 @@ public class TrendNotificationService {
* 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);
var detectedCarKmTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE, DeltaType.PERCENTAGE);
var detectedWalkBikeKmTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.WALKING_AND_CYLING_DISTANCE, DeltaType.PERCENTAGE);
var detectedMobilityScorePerKmTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.MOBILITY_SCORE_PER_KM, DeltaType.PERCENTAGE);
// we create a new list so the java type system is happy
notificationSchedulerService.scheduleAll(new ArrayList<>(detectedTrends), NotificationType.TREND, trendProperties.getEarliestTrendNotificationTimeOfDay());
// We space out the notifications in case a user has multiple trends detected - this should be improved if we add more trend types
notificationSchedulerService.scheduleAll(new ArrayList<>(detectedCarKmTrends), NotificationType.TREND, trendProperties.getEarliestTrendNotificationTimeOfDay());
notificationSchedulerService.scheduleAll(new ArrayList<>(detectedWalkBikeKmTrends), NotificationType.TREND, trendProperties.getEarliestTrendNotificationTimeOfDay().plusHours(2));
notificationSchedulerService.scheduleAll(new ArrayList<>(detectedMobilityScorePerKmTrends), NotificationType.TREND, trendProperties.getEarliestTrendNotificationTimeOfDay().plusHours(4));
}
}
+2 -4
View File
@@ -17,8 +17,8 @@ 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
sumoc.trenddetection.positive-threshold=10.0
sumoc.trenddetection.negative-threshold=-10.0
# FireBase
firebase.config.enabled=true
firebase.config.service-account=file:./secrets/fcm-key.json
@@ -31,9 +31,7 @@ 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
# 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
@@ -50,7 +50,7 @@ public class TrendDetectorServiceTest {
}
@Test
void detectWeeklyTrends_WithSignificantChanges_DetectsTrends() {
void detectWeeklyTrends_WithSignificantChanges_DetectsCarKmTrends() {
// Arrange
int year = 2026;
int weekNumber = 2;
@@ -77,7 +77,7 @@ public class TrendDetectorServiceTest {
.thenReturn(List.of(user1Current, user2Current, user3Current));
// Act
List<TrendDetectionDTO> detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE);
List<TrendDetectionDTO> detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE, DeltaType.PERCENTAGE);
// Assert
assertEquals(2, detectedTrends.size(), "Should detect 2 trends (1 increase, 1 decrease)");
@@ -131,11 +131,143 @@ public class TrendDetectorServiceTest {
// Act & Assert - should not throw any exception
assertDoesNotThrow(() -> {
List<TrendDetectionDTO> detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE);
List<TrendDetectionDTO> detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE, DeltaType.PERCENTAGE);
assertEquals(0, detectedTrends.size(), "Should not detect any trends when matching data is missing");
});
}
@Test
void detectWeeklyTrends_WithSignificantChanges_DetectsMobilityScorePerKmTrends() {
// Arrange
int year = 2026;
int weekNumber = 2;
// Set threshold values for this test
when(trendProperties.getPositiveThreshold()).thenReturn(25.0);
when(trendProperties.getNegativeThreshold()).thenReturn(-25.0);
// User 1: Significant increase in mobility score per km
// Previous: score=50, distance=1000m -> 50/1000 = 0.05 per meter
// Current: score=100, distance=1000m -> 100/1000 = 0.10 per meter (+100%)
WeeklyMobilityStats user1Previous = createWeeklyStatsWithMobilityScore(user1, year, weekNumber - 1, 1000.0, 50.0);
WeeklyMobilityStats user1Current = createWeeklyStatsWithMobilityScore(user1, year, weekNumber, 1000.0, 100.0);
// User 2: Significant decrease in mobility score per km
// Previous: score=100, distance=1000m -> 100/1000 = 0.10 per meter
// Current: score=20, distance=1000m -> 20/1000 = 0.02 per meter (-80%)
WeeklyMobilityStats user2Previous = createWeeklyStatsWithMobilityScore(user2, year, weekNumber - 1, 1000.0, 100.0);
WeeklyMobilityStats user2Current = createWeeklyStatsWithMobilityScore(user2, year, weekNumber, 1000.0, 20.0);
// User 3: No significant change
// Previous: score=50, distance=1000m -> 50/1000 = 0.05 per meter
// Current: score=55, distance=1000m -> 55/1000 = 0.055 per meter (+10%)
WeeklyMobilityStats user3Previous = createWeeklyStatsWithMobilityScore(user3, year, weekNumber - 1, 1000.0, 50.0);
WeeklyMobilityStats user3Current = createWeeklyStatsWithMobilityScore(user3, year, weekNumber, 1000.0, 55.0);
when(weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber - 1))
.thenReturn(List.of(user1Previous, user2Previous, user3Previous));
when(weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber))
.thenReturn(List.of(user1Current, user2Current, user3Current));
// Act
List<TrendDetectionDTO> detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.MOBILITY_SCORE_PER_KM, DeltaType.PERCENTAGE);
// Assert
assertEquals(2, detectedTrends.size(), "Should detect 2 trends (1 increase, 1 decrease)");
// Verify increasing trend for user1
TrendDetectionDTO user1Trend = detectedTrends.stream()
.filter(t -> t.getUserId().equals(user1.getId()))
.findFirst()
.orElse(null);
assertNotNull(user1Trend, "User 1 should have a detected trend");
assertEquals(TrendType.INCREASING, user1Trend.getType());
assertEquals(StatAttribute.MOBILITY_SCORE_PER_KM, user1Trend.getAttribute());
assertEquals(TrendTimespan.WEEKLY, user1Trend.getTimespan());
assertEquals(DeltaType.PERCENTAGE, user1Trend.getDeltaType());
assertEquals(100.0, user1Trend.getChangeValue(), 0.01);
// Verify decreasing trend for user2
TrendDetectionDTO user2Trend = detectedTrends.stream()
.filter(t -> t.getUserId().equals(user2.getId()))
.findFirst()
.orElse(null);
assertNotNull(user2Trend, "User 2 should have a detected trend");
assertEquals(TrendType.DECREASING, user2Trend.getType());
assertEquals(StatAttribute.MOBILITY_SCORE_PER_KM, user2Trend.getAttribute());
assertEquals(TrendTimespan.WEEKLY, user2Trend.getTimespan());
assertEquals(DeltaType.PERCENTAGE, user2Trend.getDeltaType());
assertEquals(-80.0, user2Trend.getChangeValue(), 0.01);
// Verify no trend detected for user3
boolean user3HasTrend = detectedTrends.stream()
.anyMatch(t -> t.getUserId().equals(user3.getId()));
assertFalse(user3HasTrend, "User 3 should not have a detected trend (change below threshold)");
}
@Test
void detectWeeklyTrends_WithSignificantChanges_DetectsWalkingAndCyclingDistanceTrends() {
// Arrange
int year = 2026;
int weekNumber = 2;
// Set threshold values for this test
when(trendProperties.getPositiveThreshold()).thenReturn(25.0);
when(trendProperties.getNegativeThreshold()).thenReturn(-25.0);
// User 1: Significant increase in walking and cycling distance (1000m -> 4000m = +300%)
WeeklyMobilityStats user1Previous = createWeeklyStatsWithWalkingAndCycling(user1, year, weekNumber - 1, 1000L);
WeeklyMobilityStats user1Current = createWeeklyStatsWithWalkingAndCycling(user1, year, weekNumber, 4000L);
// User 2: Significant decrease in walking and cycling distance (5000m -> 1000m = -80%)
WeeklyMobilityStats user2Previous = createWeeklyStatsWithWalkingAndCycling(user2, year, weekNumber - 1, 5000L);
WeeklyMobilityStats user2Current = createWeeklyStatsWithWalkingAndCycling(user2, year, weekNumber, 1000L);
// User 3: No significant change (2000m -> 2200m = +10%)
WeeklyMobilityStats user3Previous = createWeeklyStatsWithWalkingAndCycling(user3, year, weekNumber - 1, 2000L);
WeeklyMobilityStats user3Current = createWeeklyStatsWithWalkingAndCycling(user3, year, weekNumber, 2200L);
when(weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber - 1))
.thenReturn(List.of(user1Previous, user2Previous, user3Previous));
when(weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber))
.thenReturn(List.of(user1Current, user2Current, user3Current));
// Act
List<TrendDetectionDTO> detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.WALKING_AND_CYLING_DISTANCE, DeltaType.PERCENTAGE);
// Assert
assertEquals(2, detectedTrends.size(), "Should detect 2 trends (1 increase, 1 decrease)");
// Verify increasing trend for user1
TrendDetectionDTO user1Trend = detectedTrends.stream()
.filter(t -> t.getUserId().equals(user1.getId()))
.findFirst()
.orElse(null);
assertNotNull(user1Trend, "User 1 should have a detected trend");
assertEquals(TrendType.INCREASING, user1Trend.getType());
assertEquals(StatAttribute.WALKING_AND_CYLING_DISTANCE, user1Trend.getAttribute());
assertEquals(TrendTimespan.WEEKLY, user1Trend.getTimespan());
assertEquals(DeltaType.PERCENTAGE, user1Trend.getDeltaType());
assertEquals(300.0, user1Trend.getChangeValue(), 0.01);
// Verify decreasing trend for user2
TrendDetectionDTO user2Trend = detectedTrends.stream()
.filter(t -> t.getUserId().equals(user2.getId()))
.findFirst()
.orElse(null);
assertNotNull(user2Trend, "User 2 should have a detected trend");
assertEquals(TrendType.DECREASING, user2Trend.getType());
assertEquals(StatAttribute.WALKING_AND_CYLING_DISTANCE, user2Trend.getAttribute());
assertEquals(TrendTimespan.WEEKLY, user2Trend.getTimespan());
assertEquals(DeltaType.PERCENTAGE, user2Trend.getDeltaType());
assertEquals(-80.0, user2Trend.getChangeValue(), 0.01);
// Verify no trend detected for user3
boolean user3HasTrend = detectedTrends.stream()
.anyMatch(t -> t.getUserId().equals(user3.getId()));
assertFalse(user3HasTrend, "User 3 should not have a detected trend (change below threshold)");
}
/**
* Helper method to create WeeklyMobilityStats with specified car distance
*/
@@ -162,4 +294,58 @@ public class TrendDetectorServiceTest {
.sumMetersTaxi(0L)
.build();
}
/**
* Helper method to create WeeklyMobilityStats with specified mobility score and total distance
*/
private WeeklyMobilityStats createWeeklyStatsWithMobilityScore(User user, int year, int weekNumber, Double totalDistance, Double mobilityScore) {
return WeeklyMobilityStats.builder()
.user(user)
.year(year)
.weekNumber(weekNumber)
.totalDistance(totalDistance)
.tripCount(10)
.sumMobilityScore(mobilityScore)
.averageMobilityScore(mobilityScore / 10)
.sumMetersTraveled(totalDistance.longValue())
.sumMetersWalkingAndCycling(0L)
.sumMetersPublicTransport(0L)
.sumMetersWalking(0L)
.sumMetersBicycle(0L)
.sumMetersEscooter(0L)
.sumMetersBus(0L)
.sumMetersTram(0L)
.sumMetersTrain(0L)
.sumMetersCar(0L)
.sumMetersMotorcycle(0L)
.sumMetersTaxi(0L)
.build();
}
/**
* Helper method to create WeeklyMobilityStats with specified walking and cycling distance
*/
private WeeklyMobilityStats createWeeklyStatsWithWalkingAndCycling(User user, int year, int weekNumber, Long walkingAndCyclingDistance) {
return WeeklyMobilityStats.builder()
.user(user)
.year(year)
.weekNumber(weekNumber)
.totalDistance(walkingAndCyclingDistance.doubleValue())
.tripCount(10)
.sumMobilityScore(50.0)
.averageMobilityScore(5.0)
.sumMetersTraveled(walkingAndCyclingDistance)
.sumMetersWalkingAndCycling(walkingAndCyclingDistance)
.sumMetersPublicTransport(0L)
.sumMetersWalking(walkingAndCyclingDistance / 2)
.sumMetersBicycle(walkingAndCyclingDistance / 2)
.sumMetersEscooter(0L)
.sumMetersBus(0L)
.sumMetersTram(0L)
.sumMetersTrain(0L)
.sumMetersCar(0L)
.sumMetersMotorcycle(0L)
.sumMetersTaxi(0L)
.build();
}
}