implement full service chain where scheduled task detects regular trips every day and schedules notifications with better alternatives if available
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good

This commit is contained in:
2026-01-16 13:19:19 +01:00
parent b08d9dd22d
commit d099909aab
13 changed files with 299 additions and 24 deletions
@@ -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<RouteDTO> 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<String> 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<String> 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<Long, List<DetectedRegularTripDTO>> detectedRegularTripsByUser = new HashMap<>();
List<DetectedRegularTripDTO> list1 = List.of(
DetectedRegularTripDTO.getTriggeringMock(h3Service, 1L)
);
List<DetectedRegularTripDTO> 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<String> queueTestNotification() {
@@ -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.
@@ -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<String> startH3neighbours;
private List<String> endH3Neighbours;
private List<RegularTripDetectionDTO> 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();
}
}
@@ -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<Long, List<DetectedRegularTripDTO>> detectRegularCarTrips() {
var tripsByUser = getTripsByUser(Modality.CAR);
public HashMap<Long, List<DetectedRegularTripDTO>> detectRegularCarTripsByUserForDayOfWeek(DayOfWeek dayOfWeek) {
var tripsByUser = getTripsByUser(Modality.CAR, dayOfWeek);
// TODO this could be parallelized in the future
HashMap<Long, List<DetectedRegularTripDTO>> 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<Long, List<RegularTripDetectionDTO>> getTripsByUser(Modality modality) {
private HashMap<Long, List<RegularTripDetectionDTO>> getTripsByUser(Modality modality, DayOfWeek dayOfWeek) {
Instant fromDate = Instant.now().minusSeconds(properties.getDetectionTimeWindowDays() * 24 * 60 * 60);
List<RegularTripDetectionDTO> dtoList = tripMapper.toRegularTripDetectionDTOS(tripRepository.findAllValidFromDateWithMainModality(fromDate, modality));
List<RegularTripDetectionDTO> dtoList = tripMapper.toRegularTripDetectionDTOS(tripRepository.findAllValidFromDateWithMainModalityOnCertainWeekday(fromDate, modality, dayOfWeek));
HashMap<Long, List<RegularTripDetectionDTO>> tripsByUser = new HashMap<>();
for (RegularTripDetectionDTO dto : dtoList) {
@@ -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<RouteDTO> 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.
*/
@@ -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);
}
}
}
@@ -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
}
@@ -7,7 +7,7 @@ import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "adhocsuggestion")
@ConfigurationProperties(prefix = "sumoc.adhocsuggestion")
public class AdHocSuggestionProperties {
/**
@@ -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;
}
@@ -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<Long, List<DetectedRegularTripDTO>> 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();
}
}
@@ -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<String> startH3CellKRingNeighboors;
private List<String> 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();
}
}