diff --git a/.env b/.env
index 0cbff1b..ba850d1 100644
--- a/.env
+++ b/.env
@@ -1,3 +1,5 @@
+# This file overrides default envs set in application.properties when run in full docker setup
SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/sumoc
SPRING_DATASOURCE_USERNAME=postgres
-SPRING_DATASOURCE_PASSWORD=admin
\ No newline at end of file
+SPRING_DATASOURCE_PASSWORD=admin
+nominatim.base-url=http://nominatim:8080/
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
index d477124..f8f383a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -37,3 +37,7 @@ build/
/docker_images/*.tar
+
+### Secrets ###
+src/main/resources/firebase-private-key.json
+src/main/resources/firebase-private-key_disable.json
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index ff35984..968e6c5 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -1,8 +1,3 @@
-networks:
- nominatim:
- name: nominatim
- driver: bridge
-
volumes:
nominatim-data:
postgres_data:
@@ -26,11 +21,9 @@ services:
container_name: nominatim
environment:
PBF_URL: https://download.geofabrik.de/europe/germany/nordrhein-westfalen-latest.osm.pbf
- REPLICATION_URL: https://download.geofabrik.de/europe/germany/nordrhein-westfalen-updates/
+ REPLICATION_ENABLED: false
volumes:
- nominatim-data:/var/lib/postgresql/14/main
restart: unless-stopped
ports:
- "6666:8080"
- networks:
- - nominatim
diff --git a/docker-compose.yml b/docker-compose.yml
index 53df399..ce43a3b 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -1,8 +1,3 @@
-networks:
- nominatim:
- name: nominatim
- driver: bridge
-
volumes:
nominatim-data:
postgres_data:
@@ -21,28 +16,26 @@ services:
restart: unless-stopped
db:
- image: postgres:15
- container_name: sumoc-postgres
+ image: postgres:16.2-alpine
+ container_name: sumoc_db
environment:
- POSTGRES_DB: sumoc
- POSTGRES_USER: postgres
- POSTGRES_PASSWORD: admin
+ - POSTGRES_USER=postgres
+ - POSTGRES_PASSWORD=admin
+ - POSTGRES_DB=sumoc
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
- restart: unless-stopped
+ 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_URL: https://download.geofabrik.de/europe/germany/nordrhein-westfalen-updates/
+ REPLICATION_ENABLED: false
volumes:
- nominatim-data:/var/lib/postgresql/14/main
restart: unless-stopped
ports:
- "6666:8080"
- networks:
- - nominatim
diff --git a/pom.xml b/pom.xml
index 94dd5c8..97d5e66 100644
--- a/pom.xml
+++ b/pom.xml
@@ -112,7 +112,6 @@
logging-interceptor
4.12.0
-
org.mapstruct
mapstruct
@@ -136,7 +135,16 @@
reactor-test
test
-
+
+ com.google.firebase
+ firebase-admin
+ 9.7.0
+
+
+ com.uber
+ h3
+ 4.4.0
+
diff --git a/src/main/java/SuMoC/backend/BackendApplication.java b/src/main/java/SuMoC/backend/BackendApplication.java
index 7c359fd..d634127 100644
--- a/src/main/java/SuMoC/backend/BackendApplication.java
+++ b/src/main/java/SuMoC/backend/BackendApplication.java
@@ -2,8 +2,10 @@ package SuMoC.backend;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
+@EnableScheduling
public class BackendApplication {
public static void main(String[] args) {
diff --git a/src/main/java/SuMoC/backend/carta/CartaClient.java b/src/main/java/SuMoC/backend/carta/CartaClient.java
index a347d38..35a900f 100644
--- a/src/main/java/SuMoC/backend/carta/CartaClient.java
+++ b/src/main/java/SuMoC/backend/carta/CartaClient.java
@@ -6,8 +6,7 @@ import sumoc.backend.carta.client.api.CartaApi;
import sumoc.backend.carta.client.api.MapApi;
import sumoc.backend.carta.client.model.Direction;
-import java.time.LocalDateTime;
-import java.time.ZoneOffset;
+import java.time.Instant;
import java.util.concurrent.CompletableFuture;
@Service
@@ -40,8 +39,8 @@ public class CartaClient {
String origin,
String destination,
String mode,
- LocalDateTime arrivalTime,
- LocalDateTime departureTime,
+ Instant arrivalTime,
+ Instant departureTime,
Integer alternatives,
Double walkingSpeed,
Integer transferTime,
@@ -54,8 +53,8 @@ public class CartaClient {
origin,
destination,
mode.toLowerCase(), // possible values: walking, driving, cycling
- arrivalTime.toEpochSecond(ZoneOffset.UTC),
- departureTime.toEpochSecond(ZoneOffset.UTC),
+ arrivalTime.getEpochSecond(),
+ departureTime != null ? departureTime.getEpochSecond() : null,
alternatives,
walkingSpeed,
transferTime,
diff --git a/src/main/java/SuMoC/backend/dev/DevController.java b/src/main/java/SuMoC/backend/dev/DevController.java
new file mode 100644
index 0000000..f19bf8d
--- /dev/null
+++ b/src/main/java/SuMoC/backend/dev/DevController.java
@@ -0,0 +1,86 @@
+package SuMoC.backend.dev;
+
+import SuMoC.backend.meteo.ForecastService;
+import SuMoC.backend.meteo.MeteoClient;
+import SuMoC.backend.scheduling.ScheduledTasks;
+import SuMoC.backend.trend.services.StatTableUpdateService;
+import com.google.firebase.messaging.FirebaseMessaging;
+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 java.time.LocalDate;
+
+@RestController
+@RequestMapping("/dev")
+@Profile("dev")
+public class DevController {
+
+ private final ScheduledTasks scheduledTasks;
+ private final StatTableUpdateService statTableUpdateService;
+ private final FirebaseMessaging firebaseMessaging;
+ private final MeteoClient meteoClient;
+ private final ForecastService forecastService;
+
+ public DevController(
+ ScheduledTasks scheduledTasks,
+ StatTableUpdateService statTableUpdateService,
+ @Autowired(required = false) FirebaseMessaging firebaseMessaging,
+ MeteoClient meteoClient,
+ ForecastService forecastService) {
+ this.scheduledTasks = scheduledTasks;
+ this.statTableUpdateService = statTableUpdateService;
+ this.firebaseMessaging = firebaseMessaging;
+ this.meteoClient = meteoClient;
+ this.forecastService = forecastService;
+ }
+
+ @PostMapping("/trigger-trend-calculation")
+ public void triggerTrendCalculation() {
+ LocalDate dayOfLastWeek = LocalDate.now().minusDays(7);
+ LocalDate day2WeeksAgo = LocalDate.now().minusDays(14);
+ LocalDate day3WeeksAgo = LocalDate.now().minusDays(21);
+ statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(dayOfLastWeek);
+ statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(day2WeeksAgo);
+ statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(day3WeeksAgo);
+ }
+
+ @GetMapping("/test-firebase")
+ public ResponseEntity testFirebaseConnection() {
+ if (firebaseMessaging == null) {
+ return ResponseEntity.status(503)
+ .body("✗ Firebase is not configured (firebase.config.enabled=false)");
+ }
+ try {
+ // 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()
+ ).get();
+ return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
+ } catch (Exception e) {
+ return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
+ }
+ }
+
+ @GetMapping("/test-meteo")
+ public void testMeteoClient() {
+ try {
+ // Test with Zurich coordinates
+ double lat = 51.44378662109375;
+ double lon = 7.007565975189209;
+
+ var forecast = forecastService.getTodayYesterdayForecast(
+ lat,
+ lon);
+ } catch (Exception e) {
+ }
+ }
+
+}
diff --git a/src/main/java/SuMoC/backend/firebase/FirebaseConfiguration.java b/src/main/java/SuMoC/backend/firebase/FirebaseConfiguration.java
new file mode 100644
index 0000000..36bd219
--- /dev/null
+++ b/src/main/java/SuMoC/backend/firebase/FirebaseConfiguration.java
@@ -0,0 +1,51 @@
+package SuMoC.backend.firebase;
+
+import com.google.auth.oauth2.GoogleCredentials;
+import com.google.firebase.FirebaseApp;
+import com.google.firebase.FirebaseOptions;
+import com.google.firebase.messaging.FirebaseMessaging;
+import lombok.RequiredArgsConstructor;
+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 java.io.IOException;
+import java.io.InputStream;
+
+@Configuration
+@EnableConfigurationProperties(FirebaseProperties.class)
+@RequiredArgsConstructor
+@ConditionalOnProperty(prefix = "firebase.config", name = "enabled", havingValue = "true", matchIfMissing = false)
+public class FirebaseConfiguration {
+
+ private final FirebaseProperties firebaseProperties;
+
+ @Bean
+ FirebaseMessaging firebaseMessaging(FirebaseApp firebaseApp) {
+ return FirebaseMessaging.getInstance(firebaseApp);
+ }
+
+ @Bean
+ FirebaseApp firebaseApp(GoogleCredentials credentials) {
+ FirebaseOptions options = FirebaseOptions.builder()
+ .setCredentials(credentials)
+ .build();
+
+ return FirebaseApp.initializeApp(options);
+ }
+
+ @Bean
+ GoogleCredentials googleCredentials(FirebaseProperties firebaseProperties) throws IOException {
+ if (firebaseProperties.serviceAccount() != null) {
+ try (InputStream is = firebaseProperties.serviceAccount().getInputStream()) {
+ return GoogleCredentials.fromStream(is);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ // Use standard credentials chain. Useful when running inside GKE
+ return GoogleCredentials.getApplicationDefault();
+ }
+ }
+}
diff --git a/src/main/java/SuMoC/backend/firebase/FirebaseProperties.java b/src/main/java/SuMoC/backend/firebase/FirebaseProperties.java
new file mode 100644
index 0000000..3cf547e
--- /dev/null
+++ b/src/main/java/SuMoC/backend/firebase/FirebaseProperties.java
@@ -0,0 +1,12 @@
+package SuMoC.backend.firebase;
+
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.core.io.Resource;
+
+@ConfigurationProperties(prefix = "firebase.config")
+public record FirebaseProperties(
+ Boolean enabled,
+ Resource serviceAccount
+) {
+
+}
diff --git a/src/main/java/SuMoC/backend/h3/H3Configuration.java b/src/main/java/SuMoC/backend/h3/H3Configuration.java
new file mode 100644
index 0000000..ba48947
--- /dev/null
+++ b/src/main/java/SuMoC/backend/h3/H3Configuration.java
@@ -0,0 +1,31 @@
+package SuMoC.backend.h3;
+
+import lombok.Getter;
+import lombok.Setter;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@ConfigurationProperties(prefix = "h3")
+@Getter
+@Setter
+public class H3Configuration {
+
+ /**
+ * H3 resolution for route pattern detection.
+ * Typically slightly lower resolution for broader matching.
+ */
+ private int routePatternResolution = 10;
+
+ /**
+ * Number of hexagonal rings to include when matching route patterns.
+ * K-ring depth where k=1 includes immediate neighbors (6 hexagons),
+ * k=2 includes two rings (18 hexagons), etc.
+ * Higher values allow fuzzier location matching but may incorrectly
+ * group distinct locations.
+ * Consider resolution when setting.
+ * Default: 1 (immediate neighbors only)
+ */
+ private int routePatternNeighborRings = 1;
+}
+
diff --git a/src/main/java/SuMoC/backend/h3/H3Service.java b/src/main/java/SuMoC/backend/h3/H3Service.java
new file mode 100644
index 0000000..e4d2851
--- /dev/null
+++ b/src/main/java/SuMoC/backend/h3/H3Service.java
@@ -0,0 +1,86 @@
+package SuMoC.backend.h3;
+
+import com.uber.h3core.H3Core;
+import com.uber.h3core.util.LatLng;
+import org.springframework.stereotype.Service;
+
+import java.io.IOException;
+import java.util.List;
+
+/**
+ * Service for H3 spatial indexing operations.
+ * H3 is a hierarchical hexagonal geospatial indexing system.
+ */
+@Service
+public class H3Service {
+
+ private final H3Core h3;
+ private final H3Configuration config;
+
+ public H3Service(H3Configuration config) {
+ this.config = config;
+ try {
+ this.h3 = H3Core.newInstance();
+ } catch (IOException e) {
+ throw new RuntimeException("Failed to initialize H3Core", e);
+ }
+ }
+
+ /**
+ * Convert latitude/longitude to H3 cell ID with specific resolution.
+ *
+ * @param latitude Latitude in degrees
+ * @param longitude Longitude in degrees
+ * @param resolution H3 resolution (0-15, higher = more precise)
+ * @return H3 cell ID as hex string
+ */
+ public String latLngToCell(double latitude, double longitude, int resolution) {
+ return h3.latLngToCellAddress(latitude, longitude, resolution);
+ }
+
+ /**
+ * Convert latitude/longitude to H3 cell ID using route pattern resolution.
+ * This is typically used for detecting regular trip patterns.
+ *
+ * @param latitude Latitude in degrees
+ * @param longitude Longitude in degrees
+ * @return H3 cell ID as hex string
+ */
+ public String latLngToCellForRoute(double latitude, double longitude) {
+ return latLngToCell(latitude, longitude, config.getRoutePatternResolution());
+ }
+
+ /**
+ * Convert H3 cell ID to center latitude/longitude.
+ *
+ * @param cellId H3 cell ID as hex string
+ * @return LatLng of cell center
+ */
+ public LatLng cellToLatLng(String cellId) {
+ return h3.cellToLatLng(cellId);
+ }
+
+ /**
+ * Get all cells within k distance of the given cell (excluding the cell it self).
+ * K-ring distance means cells reachable in k steps on the hexagonal grid.
+ *
+ * @param cellId H3 cell ID as hex string
+ * @param k Distance (number of rings, 0 = only the cell itself)
+ * @return List of H3 cell IDs including the origin cell
+ */
+ public List getKRingNeighbors(String cellId, int k) {
+ return h3.gridRing(cellId, k);
+ }
+
+ /**
+ * Get K-ring neighbors using the configured route pattern resolution distance.
+ * Ring means the center cell is not included.
+ * Useful for finding nearby locations when matching trip patterns.
+ *
+ * @param cellId H3 cell ID as hex string
+ * @return List of H3 cell IDs within configured neighbor distance
+ */
+ public List getRoutePatternNeighbors(String cellId) {
+ return getKRingNeighbors(cellId, config.getRoutePatternNeighborRings());
+ }
+}
diff --git a/src/main/java/SuMoC/backend/meteo/ForecastResponse.java b/src/main/java/SuMoC/backend/meteo/ForecastResponse.java
new file mode 100644
index 0000000..b7ed3af
--- /dev/null
+++ b/src/main/java/SuMoC/backend/meteo/ForecastResponse.java
@@ -0,0 +1,87 @@
+package SuMoC.backend.meteo;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import java.time.Instant;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+
+public record ForecastResponse(
+ double latitude,
+ double longitude,
+ @JsonProperty("generationtime_ms") double generationtimeMs,
+ @JsonProperty("utc_offset_seconds") int utcOffsetSeconds,
+ String timezone,
+ @JsonProperty("timezone_abbreviation") String timezoneAbbreviation,
+ double elevation,
+ @JsonProperty("hourly_units") HourlyUnits hourlyUnits,
+ Hourly hourly
+) {
+ private static int findIndex(ForecastResponse forecast, LocalDateTime target) {
+ int index = -1;
+ for (int i = 0; i < forecast.hourly().time().size(); i++) {
+ LocalDateTime entry = forecast.hourly().time().get(i);
+ if (entry.toLocalDate().equals(target.toLocalDate()) && entry.getHour() == target.getHour()) {
+ index = i;
+ break;
+ }
+ }
+ if (index == -1) throw new RuntimeException("Start or end not found in list received from meteo.");
+
+ return index;
+ }
+
+ /**
+ * Gets the weather code for a specific point in time.
+ *
+ * @param dateTime the target date and time
+ * @return the weather code if found, empty otherwise
+ */
+ public Optional getWeatherCodeAt(LocalDateTime dateTime) {
+ if (hourly == null || hourly.time == null || hourly.weatherCode == null) {
+ return Optional.empty();
+ }
+
+ for (int i = 0; i < hourly.time.size(); i++) {
+ if (hourly.time.get(i).equals(dateTime)) {
+ return Optional.of(hourly.weatherCode.get(i));
+ }
+ }
+ return Optional.empty();
+ }
+
+ public List getWeatherConditionsBetween(
+ Instant start,
+ Instant end
+ ) throws Exception {
+ LocalDateTime startDateTime = start.atZone(ZoneId.systemDefault()).toLocalDateTime();
+ LocalDateTime endDateTime = end.atZone(ZoneId.systemDefault()).toLocalDateTime();
+ if (start.isAfter(end)) {
+ throw new IllegalArgumentException("Start must be before end");
+ }
+
+ int startIndex = findIndex(this, startDateTime);
+ int endIndex = findIndex(this, endDateTime);
+
+ var results = new ArrayList();
+ for (int i = startIndex; i <= endIndex; i++)
+ results.add(WeatherCondition.from(this.hourly().weatherCode().get(i)));
+ return results;
+
+ }
+
+ public record HourlyUnits(
+ String time,
+ @JsonProperty("weather_code") String weatherCode
+ ) {
+ }
+
+ public record Hourly(
+ List time,
+ @JsonProperty("weather_code") List weatherCode
+ ) {
+ }
+}
diff --git a/src/main/java/SuMoC/backend/meteo/ForecastService.java b/src/main/java/SuMoC/backend/meteo/ForecastService.java
new file mode 100644
index 0000000..1a24a16
--- /dev/null
+++ b/src/main/java/SuMoC/backend/meteo/ForecastService.java
@@ -0,0 +1,20 @@
+package SuMoC.backend.meteo;
+
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Service;
+
+@Service
+@RequiredArgsConstructor
+public class ForecastService {
+
+ private final MeteoClient meteoClient;
+
+ /**
+ * Returns forecast for today and yesterday.
+ */
+ public ForecastResponse getTodayYesterdayForecast(
+ double latitude,
+ double longitude) {
+ return meteoClient.getForecastWeatherCodeTodayYesterday(latitude, longitude).block();
+ }
+}
diff --git a/src/main/java/SuMoC/backend/meteo/MeteoClient.java b/src/main/java/SuMoC/backend/meteo/MeteoClient.java
new file mode 100644
index 0000000..c8ccbb6
--- /dev/null
+++ b/src/main/java/SuMoC/backend/meteo/MeteoClient.java
@@ -0,0 +1,42 @@
+package SuMoC.backend.meteo;
+
+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;
+
+import java.time.LocalDate;
+
+@Service
+public class MeteoClient {
+
+ private final WebClient meteoClient;
+
+ public MeteoClient(@Qualifier("meteoWebClient") WebClient meteoClient) {
+ this.meteoClient = meteoClient;
+ }
+
+ /**
+ * Simple wrapper around meteo's forecast API.
+ * https://open-meteo.com/en/docs
+ */
+ public Mono getForecastWeatherCodeTodayYesterday(
+ double lat,
+ double lon
+ ) {
+ String today = LocalDate.now().toString(); // Uses ISO-8601 format: yyyy-MM-dd
+ // We include yesterday for cases where routes cross midnight
+ String yesterday = LocalDate.now().minusDays(1).toString();
+
+ return meteoClient.get()
+ .uri(uriBuilder -> uriBuilder.path("/forecast")
+ .queryParam("latitude", lat)
+ .queryParam("longitude", lon)
+ .queryParam("hourly", "weather_code")
+ .queryParam("start_date", yesterday)
+ .queryParam("end_date", today)
+ .build())
+ .retrieve()
+ .bodyToMono(ForecastResponse.class);
+ }
+}
diff --git a/src/main/java/SuMoC/backend/meteo/MeteoClientConfig.java b/src/main/java/SuMoC/backend/meteo/MeteoClientConfig.java
new file mode 100644
index 0000000..38cec05
--- /dev/null
+++ b/src/main/java/SuMoC/backend/meteo/MeteoClientConfig.java
@@ -0,0 +1,18 @@
+package SuMoC.backend.meteo;
+
+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(MeteoProperties.class)
+public class MeteoClientConfig {
+
+ @Bean
+ public WebClient meteoWebClient(MeteoProperties properties) {
+ return WebClient.builder()
+ .baseUrl(properties.baseUrl())
+ .build();
+ }
+}
diff --git a/src/main/java/SuMoC/backend/meteo/MeteoProperties.java b/src/main/java/SuMoC/backend/meteo/MeteoProperties.java
new file mode 100644
index 0000000..ba22045
--- /dev/null
+++ b/src/main/java/SuMoC/backend/meteo/MeteoProperties.java
@@ -0,0 +1,9 @@
+package SuMoC.backend.meteo;
+
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+@ConfigurationProperties(prefix = "meteo")
+public record MeteoProperties(
+ String baseUrl
+) {
+}
diff --git a/src/main/java/SuMoC/backend/meteo/UnknownWeatherCodeException.java b/src/main/java/SuMoC/backend/meteo/UnknownWeatherCodeException.java
new file mode 100644
index 0000000..b90a7bc
--- /dev/null
+++ b/src/main/java/SuMoC/backend/meteo/UnknownWeatherCodeException.java
@@ -0,0 +1,7 @@
+package SuMoC.backend.meteo;
+
+public class UnknownWeatherCodeException extends RuntimeException {
+ public UnknownWeatherCodeException(String message) {
+ super(message);
+ }
+}
diff --git a/src/main/java/SuMoC/backend/meteo/WeatherCondition.java b/src/main/java/SuMoC/backend/meteo/WeatherCondition.java
new file mode 100644
index 0000000..7678034
--- /dev/null
+++ b/src/main/java/SuMoC/backend/meteo/WeatherCondition.java
@@ -0,0 +1,41 @@
+package SuMoC.backend.meteo;
+
+import java.util.Set;
+
+/**
+ * Simplified WMO weather codes, taken from https://gist.github.com/stellasphere/9490c195ed2b53c707087c8c2db4ec0c
+ */
+public enum WeatherCondition {
+
+ CLEAR(Set.of(0, 1)),
+ PARTLY_CLOUDY(Set.of(2)),
+ CLOUDY(Set.of(3)),
+
+ FOG(Set.of(45, 48)),
+
+ DRIZZLE(Set.of(51, 53, 55, 56, 57)),
+ RAIN(Set.of(61, 63, 65, 66, 67)),
+
+ SNOW(Set.of(71, 73, 75, 77, 85, 86)),
+
+ SHOWERS(Set.of(80, 81, 82)),
+
+ THUNDERSTORM(Set.of(95, 96, 99)),
+
+ UNKNOWN(Set.of());
+
+ private final Set codes;
+
+ WeatherCondition(Set codes) {
+ this.codes = codes;
+ }
+
+ public static WeatherCondition from(int code) throws Exception {
+ for (WeatherCondition condition : values()) {
+ if (condition.codes.contains(code)) {
+ return condition;
+ }
+ }
+ throw new UnknownWeatherCodeException("Encountered unknown weather code.");
+ }
+}
diff --git a/src/main/java/SuMoC/backend/notification/enums/NotificationStatus.java b/src/main/java/SuMoC/backend/notification/enums/NotificationStatus.java
new file mode 100644
index 0000000..964bc50
--- /dev/null
+++ b/src/main/java/SuMoC/backend/notification/enums/NotificationStatus.java
@@ -0,0 +1,7 @@
+package SuMoC.backend.notification.enums;
+
+public enum NotificationStatus {
+ PENDING,
+ SENT,
+ FAILED
+}
diff --git a/src/main/java/SuMoC/backend/notification/factories/TrendNotificationFactory.java b/src/main/java/SuMoC/backend/notification/factories/TrendNotificationFactory.java
new file mode 100644
index 0000000..d16cc2b
--- /dev/null
+++ b/src/main/java/SuMoC/backend/notification/factories/TrendNotificationFactory.java
@@ -0,0 +1,20 @@
+package SuMoC.backend.notification.factories;
+
+import SuMoC.backend.notification.models.Notification;
+import SuMoC.backend.trend.TrendDetection;
+import SuMoC.backend.trend.services.TrendMessageGenerator;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Component;
+
+@Component
+@RequiredArgsConstructor
+public class TrendNotificationFactory {
+
+ private final TrendMessageGenerator trendMessageGenerator;
+
+ public Notification createNotification(TrendDetection trend) {
+ return Notification.builder()
+ .user(trend.getUser())
+ .build();
+ }
+}
diff --git a/src/main/java/SuMoC/backend/notification/interfaces/NotificationPublisher.java b/src/main/java/SuMoC/backend/notification/interfaces/NotificationPublisher.java
new file mode 100644
index 0000000..090a260
--- /dev/null
+++ b/src/main/java/SuMoC/backend/notification/interfaces/NotificationPublisher.java
@@ -0,0 +1,4 @@
+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
new file mode 100644
index 0000000..7af6679
--- /dev/null
+++ b/src/main/java/SuMoC/backend/notification/interfaces/NotificationSender.java
@@ -0,0 +1,4 @@
+package SuMoC.backend.notification.interfaces;
+
+public interface NotificationSender {
+}
diff --git a/src/main/java/SuMoC/backend/notification/models/Notification.java b/src/main/java/SuMoC/backend/notification/models/Notification.java
new file mode 100644
index 0000000..dda300e
--- /dev/null
+++ b/src/main/java/SuMoC/backend/notification/models/Notification.java
@@ -0,0 +1,46 @@
+package SuMoC.backend.notification.models;
+
+import SuMoC.backend.notification.enums.NotificationStatus;
+import SuMoC.backend.user.models.User;
+import jakarta.persistence.*;
+import lombok.*;
+
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+
+@Entity
+@Table(name = "notifications")
+@Getter
+@Setter
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+public class Notification {
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long id;
+
+ @ManyToOne
+ @JoinColumn(name = "user_id", nullable = false)
+ private User user;
+
+ @Column(nullable = false)
+ private String message;
+
+ /**
+ * Time of day from which on a notification might be sent.
+ * Useful since we might want to send messages about specific trips immediately but not inform about trend changes
+ * etc. in the middle of night when calculating jobs might run.
+ */
+ @Column(nullable = false)
+ private LocalTime earliestTimeOfDayToSend;
+
+ @Column(nullable = false)
+ private NotificationStatus status;
+
+ @Column(nullable = false)
+ private int retryCount;
+
+ @Column(nullable = false)
+ private LocalDateTime createdAt;
+}
diff --git a/src/main/java/SuMoC/backend/notification/repositories/NotificationRepository.java b/src/main/java/SuMoC/backend/notification/repositories/NotificationRepository.java
new file mode 100644
index 0000000..0667d67
--- /dev/null
+++ b/src/main/java/SuMoC/backend/notification/repositories/NotificationRepository.java
@@ -0,0 +1,7 @@
+package SuMoC.backend.notification.repositories;
+
+import SuMoC.backend.notification.models.Notification;
+import org.springframework.data.jpa.repository.JpaRepository;
+
+public interface NotificationRepository extends JpaRepository {
+}
diff --git a/src/main/java/SuMoC/backend/notification/services/TrendNotificationService.java b/src/main/java/SuMoC/backend/notification/services/TrendNotificationService.java
new file mode 100644
index 0000000..d0b8d98
--- /dev/null
+++ b/src/main/java/SuMoC/backend/notification/services/TrendNotificationService.java
@@ -0,0 +1,25 @@
+package SuMoC.backend.notification.services;
+
+import SuMoC.backend.notification.factories.TrendNotificationFactory;
+import SuMoC.backend.notification.models.Notification;
+import SuMoC.backend.notification.repositories.NotificationRepository;
+import SuMoC.backend.trend.TrendDetection;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Service;
+
+import java.util.List;
+
+@Service
+@RequiredArgsConstructor
+public class TrendNotificationService {
+
+ private final NotificationRepository notificationRepository;
+
+ private final TrendNotificationFactory trendNotificationFactory;
+
+ public List generateTrendNotifications(List trendList) {
+ List notificationList = trendList.stream().map(trendNotificationFactory::createNotification).toList();
+
+ return List.of();
+ }
+}
diff --git a/src/main/java/SuMoC/backend/regulartrip/config/DetectorConfiguration.java b/src/main/java/SuMoC/backend/regulartrip/config/DetectorConfiguration.java
new file mode 100644
index 0000000..996042a
--- /dev/null
+++ b/src/main/java/SuMoC/backend/regulartrip/config/DetectorConfiguration.java
@@ -0,0 +1,22 @@
+package SuMoC.backend.regulartrip.config;
+
+import SuMoC.backend.regulartrip.detectionapproaches.Detector;
+import SuMoC.backend.regulartrip.detectionapproaches.IterativeClusterer;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class DetectorConfiguration {
+
+ @Bean
+ @ConditionalOnProperty(
+ prefix = "regulartripdetection",
+ name = "detection-algorithm",
+ havingValue = "iterative",
+ matchIfMissing = true
+ )
+ public Detector iterativeClusterer(RegularTripDetectionProperties properties) {
+ return new IterativeClusterer(properties);
+ }
+}
diff --git a/src/main/java/SuMoC/backend/regulartrip/config/RegularTripDetectionProperties.java b/src/main/java/SuMoC/backend/regulartrip/config/RegularTripDetectionProperties.java
new file mode 100644
index 0000000..a2b238e
--- /dev/null
+++ b/src/main/java/SuMoC/backend/regulartrip/config/RegularTripDetectionProperties.java
@@ -0,0 +1,35 @@
+package SuMoC.backend.regulartrip.config;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+@Data
+@Component
+@ConfigurationProperties(prefix = "regulartripdetection")
+public class RegularTripDetectionProperties {
+
+ // TODO at end check if this is really right place for these vals
+ /**
+ * Minimum number of trips a user must have made between the same start and end locations
+ * for those trips to be considered regular.
+ */
+ private Integer minTripsForRegularity = 2;
+
+ /**
+ * Time window in days to look back for detecting regular trips.
+ */
+ private Integer detectionTimeWindowDays = 30;
+
+ /**
+ * Maximum time difference in minutes between trips to be considered the same regular trip.
+ */
+ private Integer timeWindowSeconds = 90 * 60;
+
+ /**
+ * Number of times the iterative algorithm is run on randomly shuffled trip lists to pick best results.
+ */
+ private Integer iterativeShuffleAmounts = 5;
+
+ private String detectionAlgorithm = "iterative";
+}
diff --git a/src/main/java/SuMoC/backend/regulartrip/detectionapproaches/Detector.java b/src/main/java/SuMoC/backend/regulartrip/detectionapproaches/Detector.java
new file mode 100644
index 0000000..0817dfb
--- /dev/null
+++ b/src/main/java/SuMoC/backend/regulartrip/detectionapproaches/Detector.java
@@ -0,0 +1,14 @@
+package SuMoC.backend.regulartrip.detectionapproaches;
+
+import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
+import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
+
+import java.util.List;
+
+public interface Detector {
+
+ /**
+ * Core function to analyze a list of one users trips for regular trips. Assumes all trips have the same modality and user.
+ */
+ List detectRegularTrips(List trips);
+}
diff --git a/src/main/java/SuMoC/backend/regulartrip/detectionapproaches/IterativeClusterer.java b/src/main/java/SuMoC/backend/regulartrip/detectionapproaches/IterativeClusterer.java
new file mode 100644
index 0000000..18cfed0
--- /dev/null
+++ b/src/main/java/SuMoC/backend/regulartrip/detectionapproaches/IterativeClusterer.java
@@ -0,0 +1,218 @@
+package SuMoC.backend.regulartrip.detectionapproaches;
+
+import SuMoC.backend.regulartrip.config.RegularTripDetectionProperties;
+import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
+import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
+
+import java.time.LocalTime;
+import java.time.ZoneId;
+import java.util.*;
+
+/**
+ * This is the first approach of a regular trip detection algorithm.
+ */
+public class IterativeClusterer implements Detector {
+
+ private final RegularTripDetectionProperties properties;
+
+ public IterativeClusterer(RegularTripDetectionProperties properties) {
+ this.properties = properties;
+ }
+
+ @Override
+ public List detectRegularTrips(List trips) {
+ // Step 1: Init potential detected trip for all trips
+ HashMap baseDetectedTripsMap = initDetectedTripsMap(trips);
+ // Step 2: Find trips supported by min number of supporters
+
+ List> iterationResults = new ArrayList<>();
+ for (int i = 0; i < properties.getIterativeShuffleAmounts(); i++) {
+ // Deep copy the map for each iteration
+ HashMap iterationMap = deepCopyDetectedTripsMap(baseDetectedTripsMap);
+ Collections.shuffle(trips);
+ iterationResults.add(aggregateToSupportedDetections(iterationMap, trips, properties.getMinTripsForRegularity()));
+ }
+
+ List bestIteration = pickBestIteration(iterationResults);
+ return deduplicateOverlappingDetections(bestIteration);
+ }
+
+ /**
+ * Picks the best detection results by picking iteration with the highest total number of supporters.
+ */
+ private List pickBestIteration(List> iterationResults) {
+ return iterationResults.stream()
+ .max(Comparator.comparingInt(iteration ->
+ iteration.stream()
+ // subtracting 1 to avoid inflation by self supporting -> less detections with more supporters are better
+ .mapToInt(detection -> detection.getSupportingTrips().size() - 1)
+ .sum()))
+ .orElse(List.of());
+ }
+
+ /**
+ * Removes overlapping detections by greedily selecting the best non-overlapping set.
+ * Detections with more supporters are prioritized.
+ */
+ private List deduplicateOverlappingDetections(List detections) {
+ // Sort by supporter count (descending)
+ List sorted = new ArrayList<>(detections);
+ sorted.sort(Comparator.comparingInt(d -> -d.getSupportingTrips().size()));
+
+ List result = new ArrayList<>();
+ Set usedTripIds = new HashSet<>();
+
+ for (DetectedRegularTripDTO detection : sorted) {
+ // Get all trip IDs involved in this detection
+ Set detectionTripIds = new HashSet<>();
+ for (RegularTripDetectionDTO trip : detection.getSupportingTrips()) {
+ detectionTripIds.add(trip.getTripId());
+ }
+
+ // Check if any trips are already used
+ boolean hasOverlap = detectionTripIds.stream().anyMatch(usedTripIds::contains);
+
+ if (!hasOverlap) {
+ result.add(detection);
+ usedTripIds.addAll(detectionTripIds);
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Takes a map with potential detected regular trips and checks against a list of trips which are supported
+ * If a trip supports another detected regular trips, its own regular trip is removed.
+ */
+ private List aggregateToSupportedDetections(
+ HashMap potentialDetectedRegularTrips,
+ List trips,
+ int necessarySupporters
+ ) {
+ // We need to dupe deletions with this list since we cant modify other list entries while iterating over it
+ Set deletedDetections = new HashSet<>();
+
+ for (Map.Entry entry : potentialDetectedRegularTrips.entrySet()) {
+ if (deletedDetections.contains(entry.getKey())) continue;
+
+ // Check for all other trips if they support this detected regular trip
+ for (RegularTripDetectionDTO trip : trips) {
+ // prevent checking against trip the detected regular trip stems from
+ if (entry.getKey() == trip.getTripId()) continue;
+
+ if (supportsDetectedRegularTrip(entry.getValue(), trip)) {
+ entry.getValue().getSupportingTrips().add(trip);
+ // remove trip's own potential regular trip since its now a supporter
+ deletedDetections.add(trip.getTripId());
+ }
+
+ }
+ }
+
+ // Generate final results
+ List detectedTrips = new ArrayList<>();
+ for (Map.Entry entry : potentialDetectedRegularTrips.entrySet()) {
+ if (deletedDetections.contains(entry.getKey())) continue;
+ if (entry.getValue().getSupportingTrips().size() >= necessarySupporters) {
+ detectedTrips.add(entry.getValue());
+ }
+ }
+ return detectedTrips;
+ }
+
+ /**
+ * This method holds the core logic to determine if a trip supports a detected regular trip.
+ */
+ private boolean supportsDetectedRegularTrip(DetectedRegularTripDTO regularTrip, RegularTripDetectionDTO trip) {
+ // Conditions:
+ // 1. same day of week
+ if (regularTrip.getDayOfWeek() == trip.getDayOfTheWeek()) {
+ // 2. Departure and arrival within window
+ if (isWithinTimeWindow(regularTrip, trip)) {
+ // 3. Same start and end area
+ if (sameStartAndEndCellArea(regularTrip, trip)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * We consider start and end to be the same place when cells match or are direct neighbours.
+ */
+ private boolean sameStartAndEndCellArea(DetectedRegularTripDTO regularTripDTO, RegularTripDetectionDTO trip) {
+ if (trip.getStartH3Cell().equals(regularTripDTO.getStartH3Center()) || regularTripDTO.getStartH3neighbours().contains(trip.getStartH3Cell())) {
+ return trip.getEndH3Cell().equals(regularTripDTO.getEndH3Center()) || regularTripDTO.getEndH3Neighbours().contains(trip.getEndH3Cell());
+ }
+ return false;
+ }
+
+ private boolean isWithinTimeWindow(DetectedRegularTripDTO regularTrip, RegularTripDetectionDTO trip) {
+ LocalTime departure = LocalTime.ofInstant(trip.getStartTime(), ZoneId.systemDefault());
+ LocalTime arrival = LocalTime.ofInstant(trip.getEndTime(), ZoneId.systemDefault());
+ if (departure.isAfter(regularTrip.getDepartureWindowStart()) && departure.isBefore(regularTrip.getDepartureWindowEnd())) {
+ return arrival.isAfter(regularTrip.getArrivalWindowStart()) && arrival.isBefore(regularTrip.getArrivalWindowEnd());
+ }
+ return false;
+ }
+
+ /**
+ * Converts all trips to a detected regular trip, using original tripId as map key
+ */
+ private HashMap initDetectedTripsMap(List trips) {
+ HashMap potentialDetectedTrips = new HashMap<>();
+
+ for (RegularTripDetectionDTO trip : trips) {
+ LocalTime departure = LocalTime.ofInstant(trip.getStartTime(), ZoneId.systemDefault());
+ LocalTime arrival = LocalTime.ofInstant(trip.getEndTime(), ZoneId.systemDefault());
+
+ potentialDetectedTrips.put(trip.getTripId(), DetectedRegularTripDTO.builder()
+ .modality(trip.getMainModality())
+ .userId(trip.getUserId())
+ .dayOfWeek(trip.getDayOfTheWeek())
+ .departureWindowStart(departure.minusSeconds(properties.getTimeWindowSeconds() / 2))
+ .departureWindowEnd(departure.plusSeconds(properties.getTimeWindowSeconds() / 2))
+ .arrivalWindowStart(arrival.minusSeconds(properties.getTimeWindowSeconds() / 2))
+ .arrivalWindowEnd(arrival.plusSeconds(properties.getTimeWindowSeconds() / 2))
+ .startH3Center(trip.getStartH3Cell())
+ .endH3Center(trip.getEndH3Cell())
+ .startH3neighbours(trip.getStartH3CellKRingNeighboors())
+ .endH3Neighbours(trip.getEndH3CellKRingNeighboors())
+ .supportingTrips(new ArrayList(List.of(trip)))
+ .build());
+ }
+ return potentialDetectedTrips;
+ }
+
+ private HashMap deepCopyDetectedTripsMap(
+ HashMap original) {
+
+ HashMap copy = new HashMap<>();
+
+ for (Map.Entry entry : original.entrySet()) {
+ DetectedRegularTripDTO originalDto = entry.getValue();
+
+ // Create new DTO with copied supporting trips list
+ DetectedRegularTripDTO copiedDto = DetectedRegularTripDTO.builder()
+ .modality(originalDto.getModality())
+ .userId(originalDto.getUserId())
+ .dayOfWeek(originalDto.getDayOfWeek())
+ .departureWindowStart(originalDto.getDepartureWindowStart())
+ .departureWindowEnd(originalDto.getDepartureWindowEnd())
+ .arrivalWindowStart(originalDto.getArrivalWindowStart())
+ .arrivalWindowEnd(originalDto.getArrivalWindowEnd())
+ .startH3Center(originalDto.getStartH3Center())
+ .endH3Center(originalDto.getEndH3Center())
+ .startH3neighbours(originalDto.getStartH3neighbours())
+ .endH3Neighbours(originalDto.getEndH3Neighbours())
+ .supportingTrips(new ArrayList<>(originalDto.getSupportingTrips())) // New list
+ .build();
+
+ copy.put(entry.getKey(), copiedDto);
+ }
+
+ return copy;
+ }
+}
diff --git a/src/main/java/SuMoC/backend/regulartrip/dtos/DetectedRegularTripDTO.java b/src/main/java/SuMoC/backend/regulartrip/dtos/DetectedRegularTripDTO.java
new file mode 100644
index 0000000..d3c9091
--- /dev/null
+++ b/src/main/java/SuMoC/backend/regulartrip/dtos/DetectedRegularTripDTO.java
@@ -0,0 +1,31 @@
+package SuMoC.backend.regulartrip.dtos;
+
+import SuMoC.backend.trip.Modality;
+import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
+import lombok.*;
+
+import java.time.LocalTime;
+import java.util.List;
+
+/**
+ * A DTO representing the details of a detected regular trip.
+ */
+@Builder
+@Getter
+@Setter
+@NoArgsConstructor
+@AllArgsConstructor
+public class DetectedRegularTripDTO {
+ private long userId;
+ private Modality modality;
+ private int dayOfWeek;
+ private LocalTime departureWindowStart;
+ private LocalTime departureWindowEnd;
+ private LocalTime arrivalWindowStart;
+ private LocalTime arrivalWindowEnd;
+ private String startH3Center;
+ private String endH3Center;
+ private List startH3neighbours;
+ private List endH3Neighbours;
+ private List supportingTrips;
+}
diff --git a/src/main/java/SuMoC/backend/regulartrip/services/RegularTripDetectionService.java b/src/main/java/SuMoC/backend/regulartrip/services/RegularTripDetectionService.java
new file mode 100644
index 0000000..3890f1a
--- /dev/null
+++ b/src/main/java/SuMoC/backend/regulartrip/services/RegularTripDetectionService.java
@@ -0,0 +1,55 @@
+package SuMoC.backend.regulartrip.services;
+
+import SuMoC.backend.regulartrip.config.RegularTripDetectionProperties;
+import SuMoC.backend.regulartrip.detectionapproaches.Detector;
+import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
+import SuMoC.backend.trip.Modality;
+import SuMoC.backend.trip.TripMapper;
+import SuMoC.backend.trip.TripRepository;
+import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
+import org.springframework.stereotype.Service;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+@Service
+public class RegularTripDetectionService {
+
+ RegularTripDetectionProperties properties;
+
+ TripRepository tripRepository;
+
+ TripMapper tripMapper;
+
+ Detector tripDetector;
+
+ /**
+ * Detects regular trips 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);
+
+ // 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)));
+ }
+
+ return results;
+ }
+
+ private HashMap> getTripsByUser(Modality modality) {
+ Instant fromDate = Instant.now().minusSeconds(properties.getDetectionTimeWindowDays() * 24 * 60 * 60);
+ List dtoList = tripMapper.toRegularTripDetectionDTOS(tripRepository.findAllValidFromDateWithMainModality(fromDate, modality));
+
+ HashMap> tripsByUser = new HashMap<>();
+ for (RegularTripDetectionDTO dto : dtoList) {
+ tripsByUser.computeIfAbsent(dto.getUserId(), k -> new ArrayList<>()).add(dto);
+ }
+ return tripsByUser;
+ }
+}
diff --git a/src/main/java/SuMoC/backend/routing/RoutingController.java b/src/main/java/SuMoC/backend/routing/RoutingController.java
index da5b13f..e06bd5e 100644
--- a/src/main/java/SuMoC/backend/routing/RoutingController.java
+++ b/src/main/java/SuMoC/backend/routing/RoutingController.java
@@ -3,8 +3,9 @@ package SuMoC.backend.routing;
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 io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
-import org.apache.commons.lang3.NotImplementedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
@@ -12,14 +13,17 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClientRequestException;
-import sumoc.backend.carta.client.model.Route;
import java.util.ArrayList;
import java.util.List;
+import java.util.logging.Logger;
@RestController
@RequestMapping("/routing/alternative")
public class RoutingController {
+
+ private final Logger logger = Logger.getLogger(RoutingController.class.getName());
+
private final RoutingService routingService;
@Autowired
@@ -27,8 +31,8 @@ public class RoutingController {
this.routingService = routingService;
}
- // TODO operation description + how to handle preferences (optional, if not provided use saved users prefs or default
@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
@@ -37,10 +41,11 @@ public class RoutingController {
routingAlternativeRequestDTO.setRoutingPreferencesDTO(preferences);
}
- var routeDTOs = routingService.getAlternativeRoute(routingAlternativeRequestDTO);
+ var routeDTOs = routingService.determineAlternativeRoutesOnUserRequest(routingAlternativeRequestDTO);
return ResponseEntity.ok(routeDTOs);
} catch (WebClientRequestException e) {
// nominatim container is not up yet, we return mock
+ logger.warning("Nominatim service is not available. Returning mock route data. Error: " + e.getMessage());
ArrayList mockDTOs = new ArrayList<>();
mockDTOs.add(RouteDTO.getMockRouteDTO());
mockDTOs.add(RouteDTO.getMockRouteDTO());
diff --git a/src/main/java/SuMoC/backend/routing/config/AdHocRoutingProperties.java b/src/main/java/SuMoC/backend/routing/config/AdHocRoutingProperties.java
new file mode 100644
index 0000000..d922668
--- /dev/null
+++ b/src/main/java/SuMoC/backend/routing/config/AdHocRoutingProperties.java
@@ -0,0 +1,24 @@
+package SuMoC.backend.routing.config;
+
+import lombok.Getter;
+import lombok.Setter;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+/**
+ * These are the routing properties for alternatives that are calculated as a resonse to an uploaded trip.
+ * We separate these from properties for OnCall (Explicitly Requested by user) routing properties since
+ * the assumption is that "unasked for" alternatives have less tolerance for additional travel time etc.
+ */
+@ConfigurationProperties(prefix = "routing.adhoc")
+@Getter
+@Setter
+public class AdHocRoutingProperties extends RoutingProperties {
+
+ public AdHocRoutingProperties() {
+ super();
+ setAcceptableAdditionalMultiplierRegular(1.30);
+ setAcceptableAdditionalMultiplierPrefersPhysical(1.6);
+ setMinimumAcceptedAdditionalSecondsRegular(5 * 60);
+ setMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity(5 * 60);
+ }
+}
diff --git a/src/main/java/SuMoC/backend/routing/config/OnCallRoutingProperties.java b/src/main/java/SuMoC/backend/routing/config/OnCallRoutingProperties.java
new file mode 100644
index 0000000..a4236dc
--- /dev/null
+++ b/src/main/java/SuMoC/backend/routing/config/OnCallRoutingProperties.java
@@ -0,0 +1,22 @@
+package SuMoC.backend.routing.config;
+
+import lombok.Getter;
+import lombok.Setter;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+/**
+ * These are the routing properties for alternatives explicitly requested by the user.
+ */
+@ConfigurationProperties(prefix = "routing.oncall")
+@Getter
+@Setter
+public class OnCallRoutingProperties extends RoutingProperties {
+
+ public OnCallRoutingProperties() {
+ super();
+ setAcceptableAdditionalMultiplierRegular(1.50);
+ setAcceptableAdditionalMultiplierPrefersPhysical(1.80);
+ setMinimumAcceptedAdditionalSecondsRegular(10 * 60);
+ setMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity(15 * 60);
+ }
+}
diff --git a/src/main/java/SuMoC/backend/routing/config/RoutingConfig.java b/src/main/java/SuMoC/backend/routing/config/RoutingConfig.java
index 99baa6c..075f9e4 100644
--- a/src/main/java/SuMoC/backend/routing/config/RoutingConfig.java
+++ b/src/main/java/SuMoC/backend/routing/config/RoutingConfig.java
@@ -4,6 +4,9 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Configuration;
@Configuration
-@EnableConfigurationProperties(RoutingProperties.class)
+@EnableConfigurationProperties({
+ OnCallRoutingProperties.class,
+ AdHocRoutingProperties.class
+})
public class RoutingConfig {
}
diff --git a/src/main/java/SuMoC/backend/routing/config/RoutingProperties.java b/src/main/java/SuMoC/backend/routing/config/RoutingProperties.java
index c9f2dd4..8fb2e65 100644
--- a/src/main/java/SuMoC/backend/routing/config/RoutingProperties.java
+++ b/src/main/java/SuMoC/backend/routing/config/RoutingProperties.java
@@ -1,13 +1,49 @@
package SuMoC.backend.routing.config;
+import SuMoC.backend.meteo.WeatherCondition;
import lombok.Getter;
import lombok.Setter;
-import org.springframework.boot.context.properties.ConfigurationProperties;
-@ConfigurationProperties(prefix = "routing")
+import java.util.List;
+
@Getter
@Setter
-public class RoutingProperties {
- private int toleratedAdditionalTravelSeconds = 15 * 60;
- private int toleratedAdditionalPhysicalActivitiesSeconds = 45 * 60;
+public abstract class RoutingProperties {
+ /**
+ * Multiplier of how much more travel time is tolerated for alternative routing.
+ */
+ private double acceptableAdditionalMultiplierRegular;
+
+ /**
+ * Multiplier of accepted additional travel time for users that wish more physical activity.
+ */
+ private double acceptableAdditionalMultiplierPrefersPhysical;
+
+ /**
+ * Minimum of accepted additional travel time for regular users which is always accepted.
+ */
+ private Integer minimumAcceptedAdditionalSecondsRegular;
+
+ /**
+ * Minimum of accepted additional travel time for users that wish more physical activity.
+ */
+ private Integer minimumAcceptedAdditionalSecondsPrefersPhysicalActivity;
+
+ private List acceptableWalkingConditions;
+
+ private List acceptableCyclingConditions;
+
+ public RoutingProperties() {
+ this.acceptableCyclingConditions = List.of(
+ WeatherCondition.CLEAR,
+ WeatherCondition.PARTLY_CLOUDY,
+ WeatherCondition.CLOUDY
+ );
+ this.acceptableWalkingConditions = List.of(
+ WeatherCondition.CLEAR,
+ WeatherCondition.PARTLY_CLOUDY,
+ WeatherCondition.CLOUDY,
+ WeatherCondition.FOG
+ );
+ }
}
diff --git a/src/main/java/SuMoC/backend/routing/dtos/RouteDTO.java b/src/main/java/SuMoC/backend/routing/dtos/RouteDTO.java
index c5d9eb9..cb02baa 100644
--- a/src/main/java/SuMoC/backend/routing/dtos/RouteDTO.java
+++ b/src/main/java/SuMoC/backend/routing/dtos/RouteDTO.java
@@ -8,7 +8,8 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
-import java.time.LocalDateTime;
+import java.time.Duration;
+import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
@@ -36,17 +37,19 @@ public class RouteDTO {
@Schema(description = "The longitude of the end address.")
private double endLon;
@Schema(description = "The start date and time of the route.")
- private LocalDateTime startDateTime;
+ private Instant startDateTime;
@Schema(description = "The end date and time of the route.")
- private LocalDateTime endDateTime;
+ private Instant endDateTime;
@Schema(description = "The steps the route consists of.")
private List steps;
@Schema(description = "Amount of CO2e savings in gramm compared to a car trip for the same route.")
private double co2Savings;
+ @Schema(description = "CO2e emission of this route.")
+ private double co2Emissions;
@Schema(description = "The temporal difference in minutes compared to the original route the user requested alternatives for.")
private double timeDifferenceSeconds;
- public RouteDTO(AddressDTO startAddress, @Nullable String firstStopName, double startLat, double startLon, AddressDTO endAddress, @Nullable String lastStopName, double endLat, double endLon, LocalDateTime startDateTime, LocalDateTime endDateTime, List steps, double co2Savings, double timeDifferenceSeconds) {
+ public RouteDTO(AddressDTO startAddress, @Nullable String firstStopName, double startLat, double startLon, AddressDTO endAddress, @Nullable String lastStopName, double endLat, double endLon, Instant startDateTime, Instant endDateTime, List steps, double co2Savings, double timeDifferenceSeconds, double co2Emissions) {
this.startAddress = startAddress;
this.firstStopName = firstStopName;
this.startLat = startLat;
@@ -59,6 +62,7 @@ public class RouteDTO {
this.endDateTime = endDateTime;
this.steps = steps;
this.co2Savings = co2Savings;
+ this.co2Emissions = co2Emissions;
this.timeDifferenceSeconds = timeDifferenceSeconds;
}
@@ -101,11 +105,12 @@ public class RouteDTO {
"Viehhofer Platz",
51.459167,
7.014928,
- LocalDateTime.now().minusMinutes(30),
- LocalDateTime.now(),
+ Instant.now().minus(Duration.ofMinutes(30)),
+ Instant.now(),
new ArrayList(),
120.5f,
- +16.3f
+ +16.3f,
+ 20
);
dto.steps.add(new StepDTO(
Modality.WALKING,
@@ -124,4 +129,23 @@ public class RouteDTO {
));
return dto;
}
+
+ public long getDurationSeconds() {
+ return endDateTime.getEpochSecond() - startDateTime.getEpochSecond();
+ }
+
+ /**
+ * We consider routes that only consist of walking and cycling steps as physical activity.
+ */
+ public boolean isPhysicalActivity() {
+ return steps.stream().allMatch(step -> step.getModality() == Modality.WALKING || step.getModality() == Modality.BICYCLE);
+ }
+
+ public boolean isCyclingRoute() {
+ return steps.stream().allMatch(step -> step.getModality() == Modality.BICYCLE);
+ }
+
+ public boolean isWalkingRoute() {
+ return steps.stream().allMatch(step -> step.getModality() == Modality.WALKING);
+ }
}
diff --git a/src/main/java/SuMoC/backend/routing/dtos/RoutingAlternativeRequestDTO.java b/src/main/java/SuMoC/backend/routing/dtos/RoutingAlternativeRequestDTO.java
index 37a0ff3..de7b21c 100644
--- a/src/main/java/SuMoC/backend/routing/dtos/RoutingAlternativeRequestDTO.java
+++ b/src/main/java/SuMoC/backend/routing/dtos/RoutingAlternativeRequestDTO.java
@@ -3,13 +3,15 @@ package SuMoC.backend.routing.dtos;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.annotation.Nullable;
import jakarta.validation.constraints.NotNull;
-import lombok.Getter;
-import lombok.Setter;
+import lombok.*;
-import java.time.LocalDateTime;
+import java.time.Instant;
@Getter
@Setter
+@Builder
+@AllArgsConstructor
+@NoArgsConstructor
@Schema(description = "This DTO represents a request for alternative routes between an origin and a destination.")
public class RoutingAlternativeRequestDTO {
@NotNull
@@ -21,9 +23,9 @@ public class RoutingAlternativeRequestDTO {
@NotNull
private Double destinationLon;
@NotNull
- private LocalDateTime arrivalTime;
+ private Instant arrivalTime;
@NotNull
- private LocalDateTime departureTime; // We need both times to calculate duration to compare alternatives
+ private Instant departureTime; // We need both times to calculate duration to compare alternatives
@Nullable
private RoutingPreferencesDTO routingPreferencesDTO;
}
diff --git a/src/main/java/SuMoC/backend/routing/services/AlternativeFilterService.java b/src/main/java/SuMoC/backend/routing/services/AlternativeFilterService.java
new file mode 100644
index 0000000..9cf3d08
--- /dev/null
+++ b/src/main/java/SuMoC/backend/routing/services/AlternativeFilterService.java
@@ -0,0 +1,107 @@
+package SuMoC.backend.routing.services;
+
+import SuMoC.backend.meteo.ForecastResponse;
+import SuMoC.backend.meteo.ForecastService;
+import SuMoC.backend.meteo.WeatherCondition;
+import SuMoC.backend.routing.config.RoutingProperties;
+import SuMoC.backend.routing.dtos.RouteDTO;
+import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Service;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.logging.Logger;
+
+/**
+ * This services bundles functionality to filter suggested alternative routes to prevent us from suggesting
+ * routes with unacceptable additional travel time etc.
+ */
+@Service
+@RequiredArgsConstructor
+public class AlternativeFilterService {
+
+ private static final Logger logger = Logger.getLogger(AlternativeFilterService.class.getName());
+ private final ForecastService forecastService;
+
+ /**
+ * We apply the following logic to filter out trips:
+ * Regular:
+ * - A minimum of X minutes extra is acceptable
+ * - Y% more travel time is acceptable
+ * If user wants more phyiscal activity, for cycling and walking:
+ * - A minimum of Z minutes extra is acceptable
+ * - W% more travel time is acceptable
+ */
+ public List filterForAdditionalTravelTime(
+ RoutingAlternativeRequestDTO alternativeRequestDTO,
+ List alternatives,
+ RoutingProperties routingProperties
+ ) {
+ List filteredAlternatives = new ArrayList<>();
+
+ long originalTravelTimeSeconds = alternativeRequestDTO.getArrivalTime().getEpochSecond() - alternativeRequestDTO.getDepartureTime().getEpochSecond();
+ double toleratedMaximumRegular = originalTravelTimeSeconds * routingProperties.getAcceptableAdditionalMultiplierRegular();
+ double toleratedMaximumPhysical = originalTravelTimeSeconds * routingProperties.getAcceptableAdditionalMultiplierPrefersPhysical();
+
+ for (RouteDTO routeDTO : alternatives) {
+ long travelTimeDeltaSeconds = routeDTO.getDurationSeconds() - originalTravelTimeSeconds;
+
+ if (routeDTO.isPhysicalActivity() && alternativeRequestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity()) {
+ if (travelTimeDeltaSeconds < routingProperties.getMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity()
+ || (long) travelTimeDeltaSeconds < toleratedMaximumPhysical) {
+ filteredAlternatives.add(routeDTO);
+ }
+ } else {
+ if (travelTimeDeltaSeconds < routingProperties.getMinimumAcceptedAdditionalSecondsRegular()
+ || (long) travelTimeDeltaSeconds < toleratedMaximumRegular) {
+ filteredAlternatives.add(routeDTO);
+ }
+ }
+ }
+
+ return filteredAlternatives;
+ }
+
+ /**
+ * If weather conditions at point of travel are considered not acceptable for "outdoor" modalities such as
+ * walking and biking, the routes are removed. This does not affect transit routes which necessarily have to contain
+ * some walking elements.
+ */
+ public List filterForBadWeather(
+ RoutingAlternativeRequestDTO requestDTO,
+ List alternatives,
+ RoutingProperties routingProperties
+ ) {
+ try {
+ ForecastResponse forecast = forecastService.getTodayYesterdayForecast(requestDTO.getOriginLat(), requestDTO.getOriginLon());
+
+ ArrayList filteredAlternatives = new ArrayList<>();
+ for (RouteDTO route : alternatives) {
+ if (route.isPhysicalActivity()) {
+ var weatherConditions = forecast.getWeatherConditionsBetween(route.getStartDateTime(), route.getEndDateTime());
+ if (route.isCyclingRoute() && allConditionsAcceptable(weatherConditions, routingProperties.getAcceptableCyclingConditions())) {
+ filteredAlternatives.add(route);
+ } else if (route.isWalkingRoute() && allConditionsAcceptable(weatherConditions, routingProperties.getAcceptableWalkingConditions())) {
+ filteredAlternatives.add(route);
+ } else {
+ throw new RuntimeException("Unexpected case of a physical activity route that is not pure cycling or walking");
+ }
+ } else {
+ filteredAlternatives.add(route);
+ }
+ }
+
+ return filteredAlternatives;
+ } catch (Exception e) {
+ logger.warning(e.getMessage());
+ return alternatives;
+ }
+ }
+
+ private boolean allConditionsAcceptable(List conditions, List acceptableConditions) {
+ return new HashSet<>(acceptableConditions).containsAll(conditions);
+ }
+
+}
diff --git a/src/main/java/SuMoC/backend/routing/services/CartaTransitRouteProcessor.java b/src/main/java/SuMoC/backend/routing/services/CartaTransitRouteProcessor.java
new file mode 100644
index 0000000..8c16522
--- /dev/null
+++ b/src/main/java/SuMoC/backend/routing/services/CartaTransitRouteProcessor.java
@@ -0,0 +1,81 @@
+package SuMoC.backend.routing.services;
+
+import SuMoC.backend.routing.dtos.StepDTO;
+import SuMoC.backend.trip.Modality;
+import sumoc.backend.carta.client.model.Route;
+import sumoc.backend.carta.client.model.Step;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Processes a Carta Route and extracts StepDTOs and first , last stop name.
+ */
+public class CartaTransitRouteProcessor {
+ private final Route cartaRoute;
+
+ private List steps = null;
+
+ private String firstStopName = null;
+
+ private String lastStopName = null;
+
+ public CartaTransitRouteProcessor(Route cartaRoute) {
+ this.cartaRoute = cartaRoute;
+ this.process();
+ }
+
+ /**
+ * Extracts information from the route.
+ */
+ public void process() {
+ ArrayList steps = new ArrayList<>();
+
+ assert cartaRoute.getSteps() != null;
+ for (Step step : cartaRoute.getSteps()) {
+ // Get first stop name
+ if (this.firstStopName == null && step.getType().equals("TransitStep")) {
+ this.firstStopName = step.getStops().getFirst().getName();
+ }
+ // always set last stop as lastStopName so it will match in the end
+ if (step.getType().equals("TransitStep")) {
+ this.lastStopName = step.getStops().getLast().getName();
+ }
+
+ Modality stepModality = step.getType().equals("TransitStep")
+ ? Modality.fromCartaString(step.getLine().getType().toString())
+ : Modality.fromCartaString(step.getType());
+
+ steps.add(new StepDTO(
+ stepModality,
+ step.getType().equals("TransitStep") ? step.getLine().getCode() : null,
+ step.getDistance()
+ ));
+ }
+
+ this.steps = steps;
+ }
+
+ public List getSteps() {
+ if (this.steps == null) {
+ throw new IllegalStateException("Getter called before processing");
+ }
+ return this.steps;
+ }
+
+ public String getFirstStopName() {
+ if (this.firstStopName == null) {
+ throw new IllegalStateException("Getter called before processing");
+ }
+ return this.firstStopName;
+ }
+
+ public String getLastStopName() {
+ if (this.lastStopName == null) {
+ throw new IllegalStateException("Getter called before processing");
+ }
+ return this.lastStopName;
+ }
+
+
+}
diff --git a/src/main/java/SuMoC/backend/routing/RoutingService.java b/src/main/java/SuMoC/backend/routing/services/RoutingService.java
similarity index 53%
rename from src/main/java/SuMoC/backend/routing/RoutingService.java
rename to src/main/java/SuMoC/backend/routing/services/RoutingService.java
index 86448b6..7d67d0d 100644
--- a/src/main/java/SuMoC/backend/routing/RoutingService.java
+++ b/src/main/java/SuMoC/backend/routing/services/RoutingService.java
@@ -1,16 +1,17 @@
-package SuMoC.backend.routing;
+package SuMoC.backend.routing.services;
import SuMoC.backend.carta.CartaClient;
import SuMoC.backend.geocoding.AddressDTO;
import SuMoC.backend.geocoding.GeoCodingService;
-import SuMoC.backend.routing.config.RoutingProperties;
+import SuMoC.backend.routing.config.AdHocRoutingProperties;
+import SuMoC.backend.routing.config.OnCallRoutingProperties;
import SuMoC.backend.routing.dtos.RouteDTO;
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
import SuMoC.backend.routing.dtos.StepDTO;
import SuMoC.backend.routing.exceptions.NoCarRouteFoundException;
import SuMoC.backend.routing.exceptions.NoCarbonEmissionFoundException;
import SuMoC.backend.trip.Modality;
-import org.springframework.beans.factory.annotation.Autowired;
+import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import sumoc.backend.carta.client.model.Direction;
@@ -23,20 +24,18 @@ import java.util.Map;
import java.util.concurrent.CompletableFuture;
@Service
+@RequiredArgsConstructor
public class RoutingService {
private final GeoCodingService geoCodingService;
private final CartaClient cartaClient;
- private final RoutingProperties routingProperties;
+ private final AlternativeFilterService alternativeFilterService;
- @Autowired
- public RoutingService(CartaClient cartaClient, RoutingProperties routingProperties, GeoCodingService geoCodingService) {
- this.cartaClient = cartaClient;
- this.routingProperties = routingProperties;
- this.geoCodingService = geoCodingService;
- }
+ private final OnCallRoutingProperties onCallRoutingProperties;
+
+ private final AdHocRoutingProperties adHocRoutingProperties;
/**
* Makes an individual call to the CARTA API and returns a direction future.
@@ -52,7 +51,7 @@ public class RoutingService {
requestDTO.getDestinationLat() + "," + requestDTO.getDestinationLon(),
mode,
requestDTO.getArrivalTime(),
- requestDTO.getDepartureTime(),
+ null,
alternatives, // alternatives
null, // walkingSpeed
null, // transferTime TODO what is default? adapt?
@@ -113,7 +112,40 @@ public class RoutingService {
return directions;
}
- public List getAlternativeRoute(RoutingAlternativeRequestDTO requestDTO) {
+ /**
+ * Gets possible routes from CARTA, converts them to our format and applies filter to only provide acceptable solutions without excessive additional travel time.
+ * This is the public method for alternatives explicitly asked for by the client.
+ */
+ public List determineAlternativeRoutesOnUserRequest(RoutingAlternativeRequestDTO requestDTO) {
+ List routes = getPossibleAlternativeRoutes(requestDTO);
+ routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, onCallRoutingProperties);
+
+ return routes;
+ }
+
+ /**
+ * Public alternative retrieval method which is used to check for alternatives we suggest to user via notification
+ * right after user finished the trip.
+ * Similar to determineAlternativeRoutesOnUserRequest but here we apply stricter thresholds for alternatives
+ * and also apply weather filtering (if enabled) to not suggest routes the user definitly would not have consideres.
+ */
+ public List determineAlternativeRoutesAdHoc(RoutingAlternativeRequestDTO requestDTO) {
+ assert requestDTO.getRoutingPreferencesDTO() != null;
+
+ List routes = getPossibleAlternativeRoutes(requestDTO);
+ routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, adHocRoutingProperties);
+
+ if (requestDTO.getRoutingPreferencesDTO().isConsiderWeatherConditions()) {
+ routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties);
+ }
+
+ return routes;
+ }
+
+ /**
+ * Returns possible alternative routes for the request - no sanity filtering regarding travel times etc. is applied.
+ */
+ private List getPossibleAlternativeRoutes(RoutingAlternativeRequestDTO requestDTO) {
assert requestDTO.getRoutingPreferencesDTO() != null;
HashMap directionMap = getPossibleDirectionsFromCarta(requestDTO);
ArrayList suggestedAlternatives = new ArrayList<>();
@@ -127,12 +159,6 @@ public class RoutingService {
AddressDTO originAddress = addressesTuple.getT1();
AddressDTO destinationAddress = addressesTuple.getT2();
- // Define max additional time for sustainable alternatives
- int maxAdditionalTimeNonPhysical = routingProperties.getToleratedAdditionalTravelSeconds();
- int maxAdditionalTimePhysical = requestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity() ?
- routingProperties.getToleratedAdditionalPhysicalActivitiesSeconds() :
- routingProperties.getToleratedAdditionalTravelSeconds();
-
// Setting up car data for baseline
Route carRoute;
try {
@@ -151,33 +177,31 @@ public class RoutingService {
Direction bikeDirection = directionMap.get("bike");
if (bikeDirection.getRoutes() != null && !bikeDirection.getRoutes().isEmpty()) {
Route bikeRoute = bikeDirection.getRoutes().getFirst();
- int durationDifferenceCar = bikeRoute.getDuration() - carRoute.getDuration();
- if (durationDifferenceCar < maxAdditionalTimePhysical) {
- ArrayList steps = new ArrayList<>();
- steps.add(new StepDTO(
- Modality.BICYCLE,
- null,
- bikeRoute.getDistance()
- )
- );
+ ArrayList steps = new ArrayList<>();
+ steps.add(new StepDTO(
+ Modality.BICYCLE,
+ null,
+ bikeRoute.getDistance()
+ )
+ );
- RouteDTO routeDTO = new RouteDTO(
- originAddress,
- null,
- bikeRoute.getSourceCoordinate().getLatitude(),
- bikeRoute.getSourceCoordinate().getLongitude(),
- destinationAddress,
- null,
- bikeRoute.getTargetCoordinate().getLatitude(),
- bikeRoute.getTargetCoordinate().getLongitude(),
- requestDTO.getArrivalTime().minusSeconds(bikeRoute.getDuration()),
- requestDTO.getArrivalTime(),
- steps,
- carCarbondDioxide,
- bikeRoute.getDuration() - carRoute.getDuration()
- );
- suggestedAlternatives.add(routeDTO);
- }
+ RouteDTO routeDTO = new RouteDTO(
+ originAddress,
+ null,
+ bikeRoute.getSourceCoordinate().getLatitude(),
+ bikeRoute.getSourceCoordinate().getLongitude(),
+ destinationAddress,
+ null,
+ bikeRoute.getTargetCoordinate().getLatitude(),
+ bikeRoute.getTargetCoordinate().getLongitude(),
+ requestDTO.getArrivalTime().minusSeconds(bikeRoute.getDuration()),
+ requestDTO.getArrivalTime(),
+ steps,
+ carCarbondDioxide,
+ bikeRoute.getDuration() - carRoute.getDuration(),
+ 0.0
+ );
+ suggestedAlternatives.add(routeDTO);
}
}
@@ -185,40 +209,60 @@ public class RoutingService {
Direction walkDirection = directionMap.get("walk");
if (walkDirection.getRoutes() != null && !walkDirection.getRoutes().isEmpty()) {
Route walkRoute = walkDirection.getRoutes().getFirst();
- int durationDifferenceCar = walkRoute.getDuration() - carRoute.getDuration();
- if (durationDifferenceCar < maxAdditionalTimePhysical) {
- ArrayList steps = new ArrayList<>();
- steps.add(new StepDTO(
- Modality.WALKING,
- null,
- walkRoute.getDistance()
- ));
+ ArrayList steps = new ArrayList<>();
+ steps.add(new StepDTO(
+ Modality.WALKING,
+ null,
+ walkRoute.getDistance()
+ ));
+
+ RouteDTO routeDTO = new RouteDTO(
+ originAddress,
+ null,
+ walkRoute.getSourceCoordinate().getLatitude(),
+ walkRoute.getSourceCoordinate().getLongitude(),
+ destinationAddress,
+ null,
+ walkRoute.getTargetCoordinate().getLatitude(),
+ walkRoute.getTargetCoordinate().getLongitude(),
+ requestDTO.getArrivalTime().minusSeconds(walkRoute.getDuration()),
+ requestDTO.getArrivalTime(),
+ steps,
+ carCarbondDioxide,
+ walkRoute.getDuration() - carRoute.getDuration(),
+ 0.0
+ );
+ suggestedAlternatives.add(routeDTO);
+ }
+ }
+
+ if (directionMap.containsKey("transit")) {
+ Direction transitDirection = directionMap.get("transit");
+ if (transitDirection.getRoutes() != null && !transitDirection.getRoutes().isEmpty()) {
+ for (Route route : transitDirection.getRoutes()) {
+ CartaTransitRouteProcessor routeProcessor = new CartaTransitRouteProcessor(route);
RouteDTO routeDTO = new RouteDTO(
originAddress,
- null,
- walkRoute.getSourceCoordinate().getLatitude(),
- walkRoute.getSourceCoordinate().getLongitude(),
+ routeProcessor.getFirstStopName(),
+ route.getSourceCoordinate().getLatitude(),
+ route.getSourceCoordinate().getLongitude(),
destinationAddress,
- null,
- walkRoute.getTargetCoordinate().getLatitude(),
- walkRoute.getTargetCoordinate().getLongitude(),
- requestDTO.getArrivalTime().minusSeconds(walkRoute.getDuration()),
+ routeProcessor.getLastStopName(),
+ route.getTargetCoordinate().getLatitude(),
+ route.getTargetCoordinate().getLongitude(),
+ requestDTO.getArrivalTime().minusSeconds(route.getDuration()),
requestDTO.getArrivalTime(),
- steps,
- carCarbondDioxide,
- walkRoute.getDuration() - carRoute.getDuration()
+ routeProcessor.getSteps(),
+ carCarbondDioxide - route.getEmission().getCarbonDioxide(),
+ route.getDuration() - carRoute.getDuration(),
+ route.getEmission().getCarbonDioxide()
);
suggestedAlternatives.add(routeDTO);
}
}
}
- // TODO public transit
- // TODO if consider weather
- // get weather for origin
- // if bad, remove walking and biking options
-
return suggestedAlternatives;
}
}
diff --git a/src/main/java/SuMoC/backend/scheduling/ScheduledTasks.java b/src/main/java/SuMoC/backend/scheduling/ScheduledTasks.java
new file mode 100644
index 0000000..df949d5
--- /dev/null
+++ b/src/main/java/SuMoC/backend/scheduling/ScheduledTasks.java
@@ -0,0 +1,32 @@
+package SuMoC.backend.scheduling;
+
+import SuMoC.backend.trend.services.StatTableUpdateService;
+import lombok.RequiredArgsConstructor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+
+import java.time.LocalDate;
+
+@Component
+@RequiredArgsConstructor
+public class ScheduledTasks {
+
+ private static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);
+
+ private final SchedulingProperties properties;
+
+ private final StatTableUpdateService statTableUpdateService;
+
+ @Scheduled(cron = "#{@schedulingProperties.calculateWeeklyMobilityStats}")
+ public void scheduleCalculateWeeklyMobilityStats() {
+ logger.info("Scheduled task triggered: calculateWeeklyMobilityStatsForAllUsers");
+ try {
+ LocalDate dayOfLastWeek = LocalDate.now().minusDays(7);
+ statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(dayOfLastWeek);
+ } catch (Exception e) {
+ logger.error("Error calculating weekly mobility stats.", e);
+ }
+ }
+}
diff --git a/src/main/java/SuMoC/backend/scheduling/SchedulingConfig.java b/src/main/java/SuMoC/backend/scheduling/SchedulingConfig.java
new file mode 100644
index 0000000..d408043
--- /dev/null
+++ b/src/main/java/SuMoC/backend/scheduling/SchedulingConfig.java
@@ -0,0 +1,24 @@
+package SuMoC.backend.scheduling;
+
+import lombok.RequiredArgsConstructor;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.scheduling.TaskScheduler;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
+
+@Configuration
+@RequiredArgsConstructor
+public class SchedulingConfig {
+
+ private final SchedulingProperties schedulingProperties;
+
+ @Bean
+ public TaskScheduler taskScheduler() {
+ ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
+ scheduler.setPoolSize(schedulingProperties.getPoolSize());
+ scheduler.setThreadNamePrefix("sumoc-scheduler-");
+ scheduler.setAwaitTerminationSeconds(30);
+ scheduler.setWaitForTasksToCompleteOnShutdown(true);
+ return scheduler;
+ }
+}
diff --git a/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java b/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java
new file mode 100644
index 0000000..f6103e7
--- /dev/null
+++ b/src/main/java/SuMoC/backend/scheduling/SchedulingProperties.java
@@ -0,0 +1,15 @@
+package SuMoC.backend.scheduling;
+
+import lombok.Getter;
+import lombok.Setter;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+@Component
+@ConfigurationProperties(prefix = "sumoc.scheduling")
+@Getter
+@Setter
+public class SchedulingProperties {
+ private int poolSize = 5;
+ private String calculateWeeklyMobilityStats = "1 30 0 * * 1"; // Once per week
+}
diff --git a/src/main/java/SuMoC/backend/security/SecurityConfiguration.java b/src/main/java/SuMoC/backend/security/SecurityConfiguration.java
index deb4202..04d9308 100644
--- a/src/main/java/SuMoC/backend/security/SecurityConfiguration.java
+++ b/src/main/java/SuMoC/backend/security/SecurityConfiguration.java
@@ -90,6 +90,7 @@ public class SecurityConfiguration {
.authorizeHttpRequests(auth -> {
auth.requestMatchers(AUTH_WHITELIST).permitAll();
auth.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll();
+ auth.requestMatchers("/dev/**").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/java/SuMoC/backend/seed/trip/DevTripSeeder.java b/src/main/java/SuMoC/backend/seed/trip/DevTripSeeder.java
index 659664c..a6d7eef 100644
--- a/src/main/java/SuMoC/backend/seed/trip/DevTripSeeder.java
+++ b/src/main/java/SuMoC/backend/seed/trip/DevTripSeeder.java
@@ -28,13 +28,16 @@ public class DevTripSeeder implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
- // Iterate over all users and create 5 random trips for each
+ // Iterate over all users and create 5 random trips for each of the last 5 weeks
userRepository.findAll().forEach(user -> {
- for (int i = 0; i < 5; i++) {
- NewTripDTO newTrip = TripFactory.randomNewTripDTO(
- java.time.LocalDateTime.now().minusDays((long) (Math.random() * 30))
- );
- tripService.addTrip(user, newTrip);
+ for (int week = 0; week < 5; week++) {
+ for (int i = 0; i < 5; i++) {
+ // Create trips within each week's time range
+ long daysAgo = week * 7 + (long) (Math.random() * 7);
+ NewTripDTO newTrip = TripFactory.randomNewTripDTO(
+ java.time.Instant.now().minus(java.time.Duration.ofDays((long) (Math.random() * 30))));
+ tripService.addTrip(user, newTrip);
+ }
}
});
}
diff --git a/src/main/java/SuMoC/backend/suggestion/config/AdHocSuggestionProperties.java b/src/main/java/SuMoC/backend/suggestion/config/AdHocSuggestionProperties.java
new file mode 100644
index 0000000..c7be2f8
--- /dev/null
+++ b/src/main/java/SuMoC/backend/suggestion/config/AdHocSuggestionProperties.java
@@ -0,0 +1,18 @@
+package SuMoC.backend.suggestion.config;
+
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+@Data
+@Component
+@ConfigurationProperties(prefix = "adhocsuggestion")
+public class AdHocSuggestionProperties {
+
+ /**
+ * Maximum time after which an uploaded trip is considered recent enough to send
+ * an alternative routing suggestion for if available.
+ */
+ private Integer recentTripThresholdSeconds = 60 * 60;
+}
diff --git a/src/main/java/SuMoC/backend/suggestion/services/AdHocSuggestionService.java b/src/main/java/SuMoC/backend/suggestion/services/AdHocSuggestionService.java
new file mode 100644
index 0000000..f6de03c
--- /dev/null
+++ b/src/main/java/SuMoC/backend/suggestion/services/AdHocSuggestionService.java
@@ -0,0 +1,57 @@
+package SuMoC.backend.suggestion.services;
+
+
+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.models.Trip;
+import lombok.RequiredArgsConstructor;
+import org.springframework.scheduling.annotation.Async;
+import org.springframework.stereotype.Service;
+
+import java.time.Instant;
+
+@Service
+@RequiredArgsConstructor
+public class AdHocSuggestionService {
+
+ private final RoutingService routingService;
+
+ private final AdHocSuggestionProperties adHocSuggestionProperties;
+
+ /**
+ * 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.
+ */
+ @Async
+ public void checkNewTripForNotifiedAlternativeSuggestion(Trip newTrip) {
+ if (!isRecentTrip(newTrip)) return;
+
+ 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
+ }
+
+ private boolean isRecentTrip(Trip trip) {
+ long secondsSinceTripCompletion = Instant.now().getEpochSecond() - trip.getEndTime().getEpochSecond();
+ return secondsSinceTripCompletion < adHocSuggestionProperties.getRecentTripThresholdSeconds();
+ }
+
+ 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();
+ return RoutingAlternativeRequestDTO.builder()
+ .originLat(trip.getStartLatitude())
+ .originLon(trip.getStartLongitude())
+ .destinationLat(trip.getEndLatitude())
+ .destinationLon(trip.getEndLongitude())
+ .arrivalTime(trip.getEndTime())
+ .departureTime(trip.getStartTime())
+ .routingPreferencesDTO(preferences).build();
+ }
+}
diff --git a/src/main/java/SuMoC/backend/trend/TrendDetection.java b/src/main/java/SuMoC/backend/trend/TrendDetection.java
new file mode 100644
index 0000000..b715afd
--- /dev/null
+++ b/src/main/java/SuMoC/backend/trend/TrendDetection.java
@@ -0,0 +1,37 @@
+package SuMoC.backend.trend;
+
+import SuMoC.backend.trend.enums.*;
+import SuMoC.backend.user.models.User;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+
+@Data
+@Builder
+@AllArgsConstructor
+public class TrendDetection {
+ private User user;
+ private TrendTimespan timespan;
+ private TrendType type;
+ private StatAttribute attribute;
+ private DeltaType deltaType;
+ private double changeValue;
+
+ public TrendConnotation getTrendConnotation() {
+ if (this.type == TrendType.INCREASING) {
+ return switch (attribute) {
+ case CAR_DISTANCE -> TrendConnotation.NEGATIVE;
+ default -> TrendConnotation.NEUTRAL;
+ };
+ } else if (type == TrendType.DECREASING) {
+ return switch (attribute) {
+ case CAR_DISTANCE -> TrendConnotation.POSITIVE;
+ default -> TrendConnotation.NEUTRAL;
+ };
+ } else {
+ return TrendConnotation.NEUTRAL;
+ }
+ }
+}
+
+
diff --git a/src/main/java/SuMoC/backend/trend/WeeklyMobilityStatsRepository.java b/src/main/java/SuMoC/backend/trend/WeeklyMobilityStatsRepository.java
new file mode 100644
index 0000000..21ea598
--- /dev/null
+++ b/src/main/java/SuMoC/backend/trend/WeeklyMobilityStatsRepository.java
@@ -0,0 +1,16 @@
+package SuMoC.backend.trend;
+
+import SuMoC.backend.trend.models.WeeklyMobilityStats;
+import SuMoC.backend.trend.models.WeeklyMobilityStatsId;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
+
+import java.util.List;
+
+public interface WeeklyMobilityStatsRepository extends JpaRepository {
+
+ @Query("SELECT wms FROM WeeklyMobilityStats wms JOIN FETCH wms.user WHERE wms.year = :year AND wms.weekNumber = :weekNumber")
+ List findAllByYearAndWeekNumberWithUser(@Param("year") Integer year, @Param("weekNumber") Integer weekNumber);
+
+}
diff --git a/src/main/java/SuMoC/backend/trend/config/TrendDetectionProperties.java b/src/main/java/SuMoC/backend/trend/config/TrendDetectionProperties.java
new file mode 100644
index 0000000..4930a6d
--- /dev/null
+++ b/src/main/java/SuMoC/backend/trend/config/TrendDetectionProperties.java
@@ -0,0 +1,21 @@
+package SuMoC.backend.trend.config;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+@Data
+@Component
+@ConfigurationProperties(prefix = "trenddetection")
+public class TrendDetectionProperties {
+
+ /**
+ * Minimum percentage change to detect a positive trend (e.g., 25.0 for 25%)
+ */
+ private double positiveThreshold = 25.0;
+
+ /**
+ * Minimum percentage change to detect a negative trend (e.g., -25.0 for -25%)
+ */
+ private double negativeThreshold = -25.0;
+}
diff --git a/src/main/java/SuMoC/backend/trend/enums/DeltaType.java b/src/main/java/SuMoC/backend/trend/enums/DeltaType.java
new file mode 100644
index 0000000..774a0f6
--- /dev/null
+++ b/src/main/java/SuMoC/backend/trend/enums/DeltaType.java
@@ -0,0 +1,6 @@
+package SuMoC.backend.trend.enums;
+
+public enum DeltaType {
+ ABSOLUTE,
+ PERCENTAGE
+}
diff --git a/src/main/java/SuMoC/backend/trend/enums/StatAttribute.java b/src/main/java/SuMoC/backend/trend/enums/StatAttribute.java
new file mode 100644
index 0000000..fc1a796
--- /dev/null
+++ b/src/main/java/SuMoC/backend/trend/enums/StatAttribute.java
@@ -0,0 +1,8 @@
+package SuMoC.backend.trend.enums;
+
+/**
+ * Represents statistical attributes a detected trend can pertain to.
+ */
+public enum StatAttribute {
+ CAR_DISTANCE,
+}
diff --git a/src/main/java/SuMoC/backend/trend/enums/TrendConnotation.java b/src/main/java/SuMoC/backend/trend/enums/TrendConnotation.java
new file mode 100644
index 0000000..f3a84da
--- /dev/null
+++ b/src/main/java/SuMoC/backend/trend/enums/TrendConnotation.java
@@ -0,0 +1,7 @@
+package SuMoC.backend.trend.enums;
+
+public enum TrendConnotation {
+ POSITIVE,
+ NEGATIVE,
+ NEUTRAL
+}
diff --git a/src/main/java/SuMoC/backend/trend/enums/TrendTimespan.java b/src/main/java/SuMoC/backend/trend/enums/TrendTimespan.java
new file mode 100644
index 0000000..ea69bec
--- /dev/null
+++ b/src/main/java/SuMoC/backend/trend/enums/TrendTimespan.java
@@ -0,0 +1,5 @@
+package SuMoC.backend.trend.enums;
+
+public enum TrendTimespan {
+ WEEKLY,
+}
diff --git a/src/main/java/SuMoC/backend/trend/enums/TrendType.java b/src/main/java/SuMoC/backend/trend/enums/TrendType.java
new file mode 100644
index 0000000..d3f7d17
--- /dev/null
+++ b/src/main/java/SuMoC/backend/trend/enums/TrendType.java
@@ -0,0 +1,7 @@
+package SuMoC.backend.trend.enums;
+
+public enum TrendType {
+ INCREASING,
+ DECREASING,
+ STABLE
+}
diff --git a/src/main/java/SuMoC/backend/trend/models/WeeklyMobilityStats.java b/src/main/java/SuMoC/backend/trend/models/WeeklyMobilityStats.java
new file mode 100644
index 0000000..ab64689
--- /dev/null
+++ b/src/main/java/SuMoC/backend/trend/models/WeeklyMobilityStats.java
@@ -0,0 +1,87 @@
+package SuMoC.backend.trend.models;
+
+import SuMoC.backend.trend.enums.StatAttribute;
+import SuMoC.backend.user.models.User;
+import jakarta.persistence.*;
+import lombok.*;
+
+@Entity
+@Table(name = "weekly_mobility_stats")
+@IdClass(WeeklyMobilityStatsId.class)
+@Getter
+@Setter
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+public class WeeklyMobilityStats {
+
+ @Id
+ @ManyToOne
+ @JoinColumn(name = "user_id", nullable = false)
+ private User user;
+
+ @Id
+ @Column(nullable = false)
+ private Integer year;
+
+ @Id
+ @Column(nullable = false)
+ private Integer weekNumber;
+
+ @Column(nullable = false)
+ private Double totalDistance;
+
+ @Column(nullable = false)
+ private Integer tripCount;
+
+ @Column(nullable = false)
+ private Double sumMobilityScore;
+
+ /**
+ * The average mobility score for the week. sumMobilityScore / tripCount
+ */
+ @Column(nullable = false)
+ private Double averageMobilityScore;
+
+ @Column(nullable = false)
+ private Long sumMetersTraveled = 0L;
+
+ @Column(nullable = false)
+ private Long sumMetersWalkingAndCycling = 0L;
+
+ @Column(nullable = false)
+ private Long sumMetersPublicTransport = 0L;
+
+ @Column(nullable = false)
+ private Long sumMetersWalking = 0L;
+
+ @Column(nullable = false)
+ private Long sumMetersBicycle = 0L;
+
+ @Column(nullable = false)
+ private Long sumMetersEscooter = 0L;
+
+ @Column(nullable = false)
+ private Long sumMetersBus = 0L;
+
+ @Column(nullable = false)
+ private Long sumMetersTram = 0L;
+
+ @Column(nullable = false)
+ private Long sumMetersTrain = 0L;
+
+ @Column(nullable = false)
+ private Long sumMetersCar = 0L;
+
+ @Column(nullable = false)
+ private Long sumMetersMotorcycle = 0L;
+
+ @Column(nullable = false)
+ private Long sumMetersTaxi = 0L;
+
+ public Long getValueFor(StatAttribute attribute) {
+ return switch (attribute) {
+ case CAR_DISTANCE -> sumMetersCar;
+ };
+ }
+}
diff --git a/src/main/java/SuMoC/backend/trend/models/WeeklyMobilityStatsId.java b/src/main/java/SuMoC/backend/trend/models/WeeklyMobilityStatsId.java
new file mode 100644
index 0000000..4bee519
--- /dev/null
+++ b/src/main/java/SuMoC/backend/trend/models/WeeklyMobilityStatsId.java
@@ -0,0 +1,17 @@
+package SuMoC.backend.trend.models;
+
+import SuMoC.backend.user.models.User;
+import lombok.AllArgsConstructor;
+import lombok.EqualsAndHashCode;
+import lombok.NoArgsConstructor;
+
+import java.io.Serializable;
+
+@AllArgsConstructor
+@NoArgsConstructor
+@EqualsAndHashCode
+public class WeeklyMobilityStatsId implements Serializable {
+ private User user;
+ private Integer year;
+ private Integer weekNumber;
+}
diff --git a/src/main/java/SuMoC/backend/trend/services/StatTableUpdateService.java b/src/main/java/SuMoC/backend/trend/services/StatTableUpdateService.java
new file mode 100644
index 0000000..84dab0f
--- /dev/null
+++ b/src/main/java/SuMoC/backend/trend/services/StatTableUpdateService.java
@@ -0,0 +1,64 @@
+package SuMoC.backend.trend.services;
+
+import SuMoC.backend.trend.WeeklyMobilityStatsRepository;
+import SuMoC.backend.trend.statcalculation.WeeklyMobilityStatsCalculator;
+import SuMoC.backend.trip.TripRepository;
+import SuMoC.backend.trip.models.Trip;
+import jakarta.transaction.Transactional;
+import lombok.RequiredArgsConstructor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import java.time.DayOfWeek;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+@Service
+@RequiredArgsConstructor
+@Transactional
+public class StatTableUpdateService {
+
+ private static final Logger logger = LoggerFactory.getLogger(StatTableUpdateService.class);
+
+ private final TripRepository tripRepository;
+
+ private final WeeklyMobilityStatsRepository weeklyMobilityStatsRepository;
+
+
+ /**
+ * Calculates weekly mobility stats for the week of a given LocalDate.
+ */
+ public void updateWeeklyMobilityStatsForAllUsers(LocalDate week) {
+ logger.info("Starting calculation of weekly mobility stats for all users.");
+ // Get all trips of the last full week
+ LocalDate weekStart = week.with(DayOfWeek.MONDAY);
+ LocalDate weekEnd = weekStart.plusWeeks(1);
+ LocalDateTime startDateTime = weekStart.atStartOfDay();
+ LocalDateTime endDateTime = weekEnd.atStartOfDay();
+ List trips = tripRepository.findValidTripsInWeek(startDateTime, endDateTime);
+
+ // Groupy trips by userId
+ // TODO verify that we correctly set up the repository find method to avoid querying each trip's user separately (N+1 problem)
+ Map> tripsByUser = trips.stream()
+ .collect(Collectors.groupingBy(trip -> trip.getUser().getId()));
+
+ // Calc last full week passed
+ Integer year = week.getYear();
+ Integer weekNumber = week.get(java.time.temporal.IsoFields.WEEK_OF_WEEK_BASED_YEAR);
+
+ // For each user that made at least one trip, calculate weekly mobility stats and save to DB
+ for (Map.Entry> entry : tripsByUser.entrySet()) {
+ Long userId = entry.getKey();
+ List userTrips = entry.getValue();
+ var stats = WeeklyMobilityStatsCalculator.calculateStats(year, weekNumber, userTrips);
+ weeklyMobilityStatsRepository.save(stats);
+ }
+
+ logger.info("Finished calculation of weekly mobility stats for all users.");
+ }
+
+}
diff --git a/src/main/java/SuMoC/backend/trend/services/TrendDetectorService.java b/src/main/java/SuMoC/backend/trend/services/TrendDetectorService.java
new file mode 100644
index 0000000..766bab6
--- /dev/null
+++ b/src/main/java/SuMoC/backend/trend/services/TrendDetectorService.java
@@ -0,0 +1,84 @@
+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.enums.DeltaType;
+import SuMoC.backend.trend.enums.StatAttribute;
+import SuMoC.backend.trend.enums.TrendTimespan;
+import SuMoC.backend.trend.enums.TrendType;
+import SuMoC.backend.trend.models.WeeklyMobilityStats;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Service;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+@Service
+@RequiredArgsConstructor
+public class TrendDetectorService {
+
+ private final WeeklyMobilityStatsRepository weeklyMobilityStatsRepository;
+
+ private final TrendDetectionProperties trendDetectionProperties;
+
+ public List detectWeeklyTrends(Integer year, Integer weekNumber, StatAttribute attribute) {
+ // Fetch stats for current and previous week
+ List previousWeekStatsList;
+ if (weekNumber > 1) {
+ previousWeekStatsList = weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber - 1);
+ } else {
+ // we are forgetting about week 53 here, but it's rare enough to ignore for now
+ previousWeekStatsList = weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year - 1, 52);
+ }
+ List currentWeekStatsList = weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber);
+
+ // Convert to maps for easy userId-based lookup
+ Map previousWeekStats = previousWeekStatsList.stream()
+ .collect(Collectors.toMap(stats -> stats.getUser().getId(), stats -> stats));
+
+ Map currentWeekStats = currentWeekStatsList.stream()
+ .collect(Collectors.toMap(stats -> stats.getUser().getId(), stats -> stats));
+
+ // Detect trends for provided attribute
+ List detectedTrends = new ArrayList<>();
+ for (Map.Entry entry : currentWeekStats.entrySet()) {
+ Long userId = entry.getKey();
+ WeeklyMobilityStats currentStats = entry.getValue();
+ WeeklyMobilityStats previousStats = previousWeekStats.get(userId);
+
+ if (previousStats != null) {
+ double currentValue = currentStats.getValueFor(attribute);
+ double previousValue = previousStats.getValueFor(attribute);
+
+ if (previousValue != 0) {
+ double percentageChange = ((currentValue - previousValue) / previousValue) * 100.0;
+
+ if (percentageChange >= trendDetectionProperties.getPositiveThreshold()) {
+ detectedTrends.add(new TrendDetection(
+ currentStats.getUser(),
+ TrendTimespan.WEEKLY,
+ TrendType.INCREASING,
+ StatAttribute.CAR_DISTANCE,
+ DeltaType.PERCENTAGE,
+ percentageChange
+ ));
+ } else if (percentageChange <= trendDetectionProperties.getNegativeThreshold()) {
+ detectedTrends.add(new TrendDetection(
+ previousStats.getUser(),
+ TrendTimespan.WEEKLY,
+ TrendType.DECREASING,
+ StatAttribute.CAR_DISTANCE,
+ DeltaType.PERCENTAGE,
+ percentageChange
+ ));
+ }
+ }
+ }
+ }
+
+ return detectedTrends;
+ }
+}
diff --git a/src/main/java/SuMoC/backend/trend/services/TrendMessageGenerator.java b/src/main/java/SuMoC/backend/trend/services/TrendMessageGenerator.java
new file mode 100644
index 0000000..59754b7
--- /dev/null
+++ b/src/main/java/SuMoC/backend/trend/services/TrendMessageGenerator.java
@@ -0,0 +1,8 @@
+package SuMoC.backend.trend.services;
+
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class TrendMessageGenerator {
+}
diff --git a/src/main/java/SuMoC/backend/trend/statcalculation/WeeklyMobilityStatsCalculator.java b/src/main/java/SuMoC/backend/trend/statcalculation/WeeklyMobilityStatsCalculator.java
new file mode 100644
index 0000000..00afad7
--- /dev/null
+++ b/src/main/java/SuMoC/backend/trend/statcalculation/WeeklyMobilityStatsCalculator.java
@@ -0,0 +1,72 @@
+package SuMoC.backend.trend.statcalculation;
+
+import SuMoC.backend.trend.models.WeeklyMobilityStats;
+import SuMoC.backend.trip.models.Trip;
+import SuMoC.backend.trip.models.TripSegment;
+
+import java.util.List;
+
+public class WeeklyMobilityStatsCalculator {
+
+ public static WeeklyMobilityStats calculateStats(Integer year, Integer weekNumber, List trips) {
+ int tripCount = trips.size();
+ double sumMobilityScore = 0;
+ double sumMetersWalking = 0;
+ double sumMetersBicycle = 0;
+ double sumMetersEscooter = 0;
+ double sumMetersBus = 0;
+ double sumMetersTram = 0;
+ double sumMetersTrain = 0;
+ double sumMetersCar = 0;
+ double sumMetersMotorcycle = 0;
+ double sumMetersTaxi = 0;
+
+ for (Trip trip : trips) {
+ sumMobilityScore += trip.getMobilityScore();
+
+ for (TripSegment segment : trip.getTripSegments()) {
+ switch (segment.getModality()) {
+ case WALKING -> sumMetersWalking += segment.getDistanceMeters();
+ case BICYCLE -> sumMetersBicycle += segment.getDistanceMeters();
+ case ESCOOTER -> sumMetersEscooter += segment.getDistanceMeters();
+ case BUS -> sumMetersBus += segment.getDistanceMeters();
+ case TRAM -> sumMetersTram += segment.getDistanceMeters();
+ case TRAIN -> sumMetersTrain += segment.getDistanceMeters();
+ case CAR -> sumMetersCar += segment.getDistanceMeters();
+ case MOTORCYCLE -> sumMetersMotorcycle += segment.getDistanceMeters();
+ case TAXI -> sumMetersTaxi += segment.getDistanceMeters();
+ }
+ }
+ }
+
+ double sumMetersTraveled = sumMetersWalking + sumMetersBicycle + sumMetersEscooter +
+ sumMetersBus + sumMetersTram + sumMetersTrain +
+ sumMetersCar + sumMetersMotorcycle + sumMetersTaxi;
+ double sumMetersWalkingAndCycling = sumMetersWalking + sumMetersBicycle;
+ double sumMetersPublicTransport = sumMetersBus + sumMetersTram + sumMetersTrain;
+ double averageMobilityScore = sumMobilityScore / tripCount;
+
+ return WeeklyMobilityStats.builder()
+ .user(trips.getFirst().getUser())
+ .year(year)
+ .weekNumber(weekNumber)
+ .totalDistance(sumMetersTraveled)
+ .tripCount(tripCount)
+ .sumMobilityScore(sumMobilityScore)
+ .averageMobilityScore(averageMobilityScore)
+ .sumMetersTraveled((long) sumMetersTraveled)
+ .sumMetersWalkingAndCycling((long) sumMetersWalkingAndCycling)
+ .sumMetersPublicTransport((long) sumMetersPublicTransport)
+ .sumMetersWalking((long) sumMetersWalking)
+ .sumMetersBicycle((long) sumMetersBicycle)
+ .sumMetersEscooter((long) sumMetersEscooter)
+ .sumMetersBus((long) sumMetersBus)
+ .sumMetersTram((long) sumMetersTram)
+ .sumMetersTrain((long) sumMetersTrain)
+ .sumMetersCar((long) sumMetersCar)
+ .sumMetersMotorcycle((long) sumMetersMotorcycle)
+ .sumMetersTaxi((long) sumMetersTaxi)
+ .build();
+ }
+
+}
diff --git a/src/main/java/SuMoC/backend/trip/Modality.java b/src/main/java/SuMoC/backend/trip/Modality.java
index 915956f..509458c 100644
--- a/src/main/java/SuMoC/backend/trip/Modality.java
+++ b/src/main/java/SuMoC/backend/trip/Modality.java
@@ -10,5 +10,19 @@ public enum Modality {
TRAIN,
CAR,
MOTORCYCLE,
- TAXI
+ TAXI;
+
+ public static Modality fromCartaString(String cartaType) {
+ return switch (cartaType.toLowerCase()) {
+ case "tram", "subway", "metro" -> TRAM;
+ case "rail", "monorail" -> TRAIN;
+ case "bus", "trolleybus" -> BUS;
+ case "ferry", "cablecar", "gondola", "funicular" ->
+ throw new UnsupportedOperationException("Transport type needs to be added to backend: " + cartaType);
+ // these are to dervive modality from carta step type
+ case "walkingstep" -> WALKING;
+ case "cyclingstep" -> BICYCLE;
+ default -> throw new IllegalArgumentException("Unknown CARTA modality: " + cartaType);
+ };
+ }
}
diff --git a/src/main/java/SuMoC/backend/trip/TripController.java b/src/main/java/SuMoC/backend/trip/TripController.java
index 2f85adc..d05ee9e 100644
--- a/src/main/java/SuMoC/backend/trip/TripController.java
+++ b/src/main/java/SuMoC/backend/trip/TripController.java
@@ -1,13 +1,15 @@
package SuMoC.backend.trip;
+import SuMoC.backend.suggestion.services.AdHocSuggestionService;
import SuMoC.backend.trip.dtos.NewTripDTO;
import SuMoC.backend.trip.dtos.TripDTO;
+import SuMoC.backend.trip.models.Trip;
import SuMoC.backend.user.models.User;
import SuMoC.backend.user.repository.UserRepository;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
-import org.springframework.beans.factory.annotation.Autowired;
+import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
@@ -18,15 +20,14 @@ import java.util.List;
@RestController
@RequestMapping("/trip")
+@RequiredArgsConstructor
public class TripController {
+
private final TripService tripService;
+
private final UserRepository userRepository;
- @Autowired
- public TripController(TripService tripService, UserRepository userRepository) {
- this.tripService = tripService;
- this.userRepository = userRepository;
- }
+ private final AdHocSuggestionService adHocSuggestionService;
// TODO extend security context with user id to avoid unnecessary db query
private User getAuthenticatedUser() {
@@ -38,8 +39,11 @@ public class TripController {
@PostMapping("/uploadTrip")
public ResponseEntity uploadTrip(@Valid @RequestBody NewTripDTO newTripDTO) {
User user = getAuthenticatedUser();
+ Trip savedTrip = tripService.addTrip(user, newTripDTO);
+
+ // let the ad hoc service suggest an alternative more ecofriendly route if appropriate
+ adHocSuggestionService.checkNewTripForNotifiedAlternativeSuggestion(savedTrip);
- tripService.addTrip(user, newTripDTO);
return ResponseEntity.status(HttpStatus.CREATED).build();
}
diff --git a/src/main/java/SuMoC/backend/trip/TripFactory.java b/src/main/java/SuMoC/backend/trip/TripFactory.java
index 895389f..3fa78ff 100644
--- a/src/main/java/SuMoC/backend/trip/TripFactory.java
+++ b/src/main/java/SuMoC/backend/trip/TripFactory.java
@@ -4,7 +4,8 @@ import SuMoC.backend.trip.dtos.NewTripDTO;
import SuMoC.backend.trip.dtos.NewTripSegmentDTO;
import lombok.NoArgsConstructor;
-import java.time.LocalDateTime;
+import java.time.Duration;
+import java.time.Instant;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
@@ -27,7 +28,7 @@ public class TripFactory {
* take 2 hours in total, and have random start and end places from a predefined list of NRW cities.
* So data is not really realistic.
*/
- public static NewTripDTO randomNewTripDTO(LocalDateTime startTime) {
+ public static NewTripDTO randomNewTripDTO(Instant startTime) {
String startPlace = NRW_CITIES.get(ThreadLocalRandom.current().nextInt(NRW_CITIES.size()));
String endPlace = NRW_CITIES.get(ThreadLocalRandom.current().nextInt(NRW_CITIES.size()));
while (endPlace.equals(startPlace)) {
@@ -42,7 +43,7 @@ public class TripFactory {
.build(),
NewTripSegmentDTO.builder()
.modality(randomModality())
- .startTime(startTime.plusMinutes(60))
+ .startTime(startTime.plus(Duration.ofMinutes(60)))
.distanceMeters(ThreadLocalRandom.current().nextFloat() * 10000)
.build()
);
@@ -56,7 +57,7 @@ public class TripFactory {
.endLongitude(6.800951430299369)
.co2Emissions(100.0)
.startTime(startTime)
- .endTime(startTime.plusMinutes(120))
+ .endTime(startTime.plus(Duration.ofMinutes(120)))
.mobilityScore(ThreadLocalRandom.current().nextFloat() * 100)
.tripSegments(segments)
.build();
diff --git a/src/main/java/SuMoC/backend/trip/TripMapper.java b/src/main/java/SuMoC/backend/trip/TripMapper.java
index 4a6f9a6..3f6f94d 100644
--- a/src/main/java/SuMoC/backend/trip/TripMapper.java
+++ b/src/main/java/SuMoC/backend/trip/TripMapper.java
@@ -1,21 +1,81 @@
package SuMoC.backend.trip;
+import SuMoC.backend.h3.H3Service;
import SuMoC.backend.trip.dtos.NewTripDTO;
+import SuMoC.backend.trip.dtos.NewTripSegmentDTO;
+import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
import SuMoC.backend.trip.dtos.TripDTO;
import SuMoC.backend.trip.models.Trip;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
+import org.springframework.beans.factory.annotation.Autowired;
+import java.util.Arrays;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+@Mapper(componentModel = "spring", uses = {TripSegmentMapper.class, H3Service.class})
+public abstract class TripMapper {
+
+ @Autowired
+ protected H3Service h3service;
-@Mapper(componentModel = "spring", uses = TripSegmentMapper.class)
-public interface TripMapper {
@Mapping(source = "id", target = "tripId")
@Mapping(source = "user.id", target = "userId")
- TripDTO toTripDTO(Trip trip);
+ public abstract TripDTO toTripDTO(Trip trip);
- List toTripDTOs(List trips);
+ public abstract List toTripDTOs(List trips);
@Mapping(source = "tripSegments", target = "tripSegments")
- Trip toTrip(NewTripDTO newTripDTO);
+ @Mapping(target = "startH3Cell", expression = "java(calculateH3CellStart(newTripDTO))")
+ @Mapping(target = "endH3Cell", expression = "java(calculateH3CellEnd(newTripDTO))")
+ @Mapping(target = "mainModality", expression = "java(mainModalityByDistance(newTripDTO))")
+ public abstract Trip toTrip(NewTripDTO newTripDTO);
+
+ @Mapping(source = "id", target = "tripId")
+ @Mapping(source = "user.id", target = "userId")
+ @Mapping(target = "startH3CellKRingNeighboors", expression = "java(calculateStartH3KRingNeighboords(trip))")
+ @Mapping(target = "endH3CellKRingNeighboors", expression = "java(calculateEndtH3KRingNeighboords(trip))")
+ public abstract RegularTripDetectionDTO toRegularTripDetectionDTO(Trip trip);
+
+ public abstract List toRegularTripDetectionDTOS(List trips);
+
+ protected String calculateH3CellStart(NewTripDTO newTripDTO) {
+ return h3service.latLngToCellForRoute(newTripDTO.getStartLatitude(), newTripDTO.getStartLongitude());
+ }
+
+ protected String calculateH3CellEnd(NewTripDTO newTripDTO) {
+ return h3service.latLngToCellForRoute(newTripDTO.getEndLatitude(), newTripDTO.getEndLongitude());
+ }
+
+ protected List calculateStartH3KRingNeighboords(Trip trip) {
+ return h3service.getRoutePatternNeighbors(trip.getStartH3Cell());
+ }
+
+ protected List calculateEndtH3KRingNeighboords(Trip trip) {
+ return h3service.getRoutePatternNeighbors(trip.getEndH3Cell());
+ }
+
+ protected Modality mainModalityByDistance(NewTripDTO newTripDTO) {
+ HashMap map = Arrays.stream(Modality.values())
+ .collect(Collectors.toMap(
+ modality -> modality,
+ modality -> 0f,
+ (a, b) -> a,
+ HashMap::new
+ ));
+
+ for (NewTripSegmentDTO segmentDTO : newTripDTO.getTripSegments()) {
+ Modality modality = segmentDTO.getModality();
+ map.put(modality, map.get(modality) + segmentDTO.getDistanceMeters());
+ }
+
+ return map.entrySet().stream()
+ .max(Map.Entry.comparingByValue())
+ .map(Map.Entry::getKey)
+ .orElse(Modality.IDLE);
+
+ }
}
diff --git a/src/main/java/SuMoC/backend/trip/TripRepository.java b/src/main/java/SuMoC/backend/trip/TripRepository.java
index 761abed..4b8c96a 100644
--- a/src/main/java/SuMoC/backend/trip/TripRepository.java
+++ b/src/main/java/SuMoC/backend/trip/TripRepository.java
@@ -1,13 +1,30 @@
package SuMoC.backend.trip;
-import SuMoC.backend.user.models.User;
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.Instant;
+import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
-public interface TripRepository extends JpaRepository {
+public interface TripRepository extends JpaRepository {
Optional findTripById(Long id);
+
Optional> findAllByUser(User user);
+
+ @Query("SELECT trip FROM Trip trip " +
+ "JOIN FETCH trip.user " +
+ "JOIN FETCH trip.tripSegments " +
+ "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);
}
diff --git a/src/main/java/SuMoC/backend/trip/TripService.java b/src/main/java/SuMoC/backend/trip/TripService.java
index 6ee5663..528befa 100644
--- a/src/main/java/SuMoC/backend/trip/TripService.java
+++ b/src/main/java/SuMoC/backend/trip/TripService.java
@@ -43,11 +43,12 @@ public class TripService {
tripRepository.save(trip);
}
- public void addTrip(User user, NewTripDTO newTripDTO) {
+ public Trip addTrip(User user, NewTripDTO newTripDTO) {
Trip trip = tripMapper.toTrip(newTripDTO);
trip.setUser(user);
trip.getTripSegments().forEach(tripSegment -> tripSegment.setTrip(trip));
tripRepository.save(trip);
+ return trip;
}
public List getAllTripsOfUser(User user) {
diff --git a/src/main/java/SuMoC/backend/trip/dtos/NewTripDTO.java b/src/main/java/SuMoC/backend/trip/dtos/NewTripDTO.java
index 6013f36..7baa7f5 100644
--- a/src/main/java/SuMoC/backend/trip/dtos/NewTripDTO.java
+++ b/src/main/java/SuMoC/backend/trip/dtos/NewTripDTO.java
@@ -5,7 +5,7 @@ import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.*;
-import java.time.LocalDateTime;
+import java.time.Instant;
import java.util.Set;
/**
@@ -27,8 +27,8 @@ public class NewTripDTO {
private String endPlace;
private double endLatitude;
private double endLongitude;
- private LocalDateTime startTime;
- private LocalDateTime endTime;
+ private Instant startTime;
+ private Instant endTime;
private double mobilityScore;
private double co2Emissions;
@NotNull
diff --git a/src/main/java/SuMoC/backend/trip/dtos/NewTripSegmentDTO.java b/src/main/java/SuMoC/backend/trip/dtos/NewTripSegmentDTO.java
index 4e1ab8f..dde8314 100644
--- a/src/main/java/SuMoC/backend/trip/dtos/NewTripSegmentDTO.java
+++ b/src/main/java/SuMoC/backend/trip/dtos/NewTripSegmentDTO.java
@@ -3,7 +3,7 @@ package SuMoC.backend.trip.dtos;
import SuMoC.backend.trip.Modality;
import lombok.Builder;
-import java.time.LocalDateTime;
+import java.time.Instant;
/**
* DTO representing a trip segment submitted from the App which is not yet persisted in the database.
@@ -11,13 +11,13 @@ import java.time.LocalDateTime;
@Builder
public class NewTripSegmentDTO {
private Modality modality;
- private LocalDateTime startTime;
+ private Instant startTime;
private float distanceMeters;
public NewTripSegmentDTO() {
}
- public NewTripSegmentDTO(Modality modality, LocalDateTime startTime, float distanceMeters) {
+ public NewTripSegmentDTO(Modality modality, Instant startTime, float distanceMeters) {
this.modality = modality;
this.startTime = startTime;
this.distanceMeters = distanceMeters;
@@ -27,7 +27,7 @@ public class NewTripSegmentDTO {
return modality;
}
- public LocalDateTime getStartTime() {
+ public Instant getStartTime() {
return startTime;
}
diff --git a/src/main/java/SuMoC/backend/trip/dtos/RegularTripDetectionDTO.java b/src/main/java/SuMoC/backend/trip/dtos/RegularTripDetectionDTO.java
new file mode 100644
index 0000000..0ce1ada
--- /dev/null
+++ b/src/main/java/SuMoC/backend/trip/dtos/RegularTripDetectionDTO.java
@@ -0,0 +1,31 @@
+package SuMoC.backend.trip.dtos;
+
+import SuMoC.backend.trip.Modality;
+import lombok.*;
+
+import java.time.Instant;
+import java.util.List;
+
+/**
+ * A DTO representing the details of a saved trip in a format suitable for regular trip detection.
+ */
+@Builder
+@Getter
+@Setter
+@NoArgsConstructor
+@AllArgsConstructor
+public class RegularTripDetectionDTO {
+ private long tripId;
+ private long userId;
+ private String startH3Cell;
+ private String endH3Cell;
+ private Instant startTime;
+ private Instant endTime;
+ private Modality mainModality;
+ private List startH3CellKRingNeighboors;
+ private List endH3CellKRingNeighboors;
+
+ public int getDayOfTheWeek() {
+ return startTime.atZone(java.time.ZoneId.systemDefault()).getDayOfWeek().getValue();
+ }
+}
diff --git a/src/main/java/SuMoC/backend/trip/dtos/TripDTO.java b/src/main/java/SuMoC/backend/trip/dtos/TripDTO.java
index b48cd3b..f215dc7 100644
--- a/src/main/java/SuMoC/backend/trip/dtos/TripDTO.java
+++ b/src/main/java/SuMoC/backend/trip/dtos/TripDTO.java
@@ -6,7 +6,7 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
-import java.time.LocalDateTime;
+import java.time.Instant;
import java.util.List;
@Schema(description = "Represents a trip uploaded to the backend by a user that is already stored in the DB.")
@@ -23,8 +23,8 @@ public class TripDTO {
private String endPlace;
private double endLatitude;
private double endLongitude;
- private LocalDateTime startTime;
- private LocalDateTime endTime;
+ private Instant startTime;
+ private Instant endTime;
private double mobilityScore;
private double co2Emissions;
private List tripSegments;
diff --git a/src/main/java/SuMoC/backend/trip/dtos/TripSegmentDTO.java b/src/main/java/SuMoC/backend/trip/dtos/TripSegmentDTO.java
index e13aa76..9224647 100644
--- a/src/main/java/SuMoC/backend/trip/dtos/TripSegmentDTO.java
+++ b/src/main/java/SuMoC/backend/trip/dtos/TripSegmentDTO.java
@@ -4,7 +4,7 @@ import SuMoC.backend.trip.Modality;
import lombok.Getter;
import lombok.Setter;
-import java.time.LocalDateTime;
+import java.time.Instant;
/**
* DTO representing a trip segment already persisted in the database.
@@ -15,12 +15,13 @@ public class TripSegmentDTO {
private long tripSegmentId;
private long tripId;
private Modality modality;
- private LocalDateTime startTime;
+ private Instant startTime;
private float distanceMeters;
- public TripSegmentDTO() {}
+ public TripSegmentDTO() {
+ }
- public TripSegmentDTO(long tripSegmentId, long tripId, Modality modality, LocalDateTime startTime, float distanceMeters) {
+ public TripSegmentDTO(long tripSegmentId, long tripId, Modality modality, Instant startTime, float distanceMeters) {
this.tripSegmentId = tripSegmentId;
this.tripId = tripId;
this.modality = modality;
diff --git a/src/main/java/SuMoC/backend/trip/models/Trip.java b/src/main/java/SuMoC/backend/trip/models/Trip.java
index abc13ce..02ebb88 100644
--- a/src/main/java/SuMoC/backend/trip/models/Trip.java
+++ b/src/main/java/SuMoC/backend/trip/models/Trip.java
@@ -1,14 +1,16 @@
package SuMoC.backend.trip.models;
+import SuMoC.backend.trip.Modality;
import SuMoC.backend.user.models.User;
+import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
-import java.time.LocalDateTime;
+import java.time.Instant;
import java.util.HashSet;
import java.util.Set;
@@ -36,6 +38,9 @@ public class Trip {
@Column(nullable = false)
private double startLongitude;
+ @Column(nullable = false, name = "start_h3_cell", length = 15)
+ private String startH3Cell;
+
@Column(nullable = false)
private String endPlace;
@@ -45,11 +50,14 @@ public class Trip {
@Column(nullable = false)
private double endLongitude;
- @Column(nullable = false)
- private LocalDateTime startTime;
+ @Column(nullable = false, name = "end_h3_cell", length = 15)
+ private String endH3Cell;
@Column(nullable = false)
- private LocalDateTime endTime;
+ private Instant startTime;
+
+ @Column(nullable = false)
+ private Instant endTime;
/**
* Mobilityscore for the trip.
@@ -66,6 +74,11 @@ public class Trip {
@Column(nullable = false)
private boolean invalidated = false;
+ @Column(nullable = false)
+ @Enumerated(EnumType.STRING)
+ @Schema(description = "Main modality by distance.")
+ private Modality mainModality;
+
@OneToMany(mappedBy = "trip", cascade = CascadeType.ALL, orphanRemoval = true)
private Set tripSegments = new HashSet<>();
}
diff --git a/src/main/java/SuMoC/backend/trip/models/TripSegment.java b/src/main/java/SuMoC/backend/trip/models/TripSegment.java
index fb2b77f..7d85317 100644
--- a/src/main/java/SuMoC/backend/trip/models/TripSegment.java
+++ b/src/main/java/SuMoC/backend/trip/models/TripSegment.java
@@ -6,7 +6,7 @@ import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
-import java.time.LocalDateTime;
+import java.time.Instant;
@Setter
@Getter
@@ -26,7 +26,7 @@ public class TripSegment {
private Modality modality;
@Column(nullable = false)
- private LocalDateTime startTime;
+ private Instant startTime;
/**
* Distance of the segment in meters.
@@ -37,7 +37,7 @@ public class TripSegment {
public TripSegment() {
}
- public TripSegment(Long id, Trip trip, Modality modality, LocalDateTime startTime, Long distanceMeters) {
+ public TripSegment(Long id, Trip trip, Modality modality, Instant startTime, Long distanceMeters) {
this.id = id;
this.trip = trip;
this.modality = modality;
diff --git a/src/main/java/SuMoC/backend/user/dtos/FriendshipDTO.java b/src/main/java/SuMoC/backend/user/dtos/FriendshipDTO.java
index 5b80fa6..3cab722 100644
--- a/src/main/java/SuMoC/backend/user/dtos/FriendshipDTO.java
+++ b/src/main/java/SuMoC/backend/user/dtos/FriendshipDTO.java
@@ -2,7 +2,7 @@ package SuMoC.backend.user.dtos;
import SuMoC.backend.user.enums.FriendShipStatus;
-import java.time.LocalDateTime;
+import java.time.Instant;
/**
* DTO for all friendships of a user.
@@ -16,12 +16,12 @@ public class FriendshipDTO {
private Long userId;
private MinimalUserDTO friend;
private FriendShipStatus status;
- private LocalDateTime createdAt;
+ private Instant createdAt;
public FriendshipDTO() {
}
- public FriendshipDTO(Long friendshipId, Long userId, MinimalUserDTO friend, FriendShipStatus status, LocalDateTime createdAt) {
+ public FriendshipDTO(Long friendshipId, Long userId, MinimalUserDTO friend, FriendShipStatus status, Instant createdAt) {
this.friendshipId = friendshipId;
this.userId = userId;
this.friend = friend;
@@ -61,11 +61,11 @@ public class FriendshipDTO {
this.status = status;
}
- public LocalDateTime getCreatedAt() {
+ public Instant getCreatedAt() {
return createdAt;
}
- public void setCreatedAt(LocalDateTime createdAt) {
+ public void setCreatedAt(Instant createdAt) {
this.createdAt = createdAt;
}
}
diff --git a/src/main/java/SuMoC/backend/user/models/Friendship.java b/src/main/java/SuMoC/backend/user/models/Friendship.java
index 7731f95..ce899de 100644
--- a/src/main/java/SuMoC/backend/user/models/Friendship.java
+++ b/src/main/java/SuMoC/backend/user/models/Friendship.java
@@ -4,7 +4,7 @@ import SuMoC.backend.user.enums.FriendShipStatus;
import jakarta.persistence.*;
import lombok.*;
-import java.time.LocalDateTime;
+import java.time.Instant;
/**
* For explanation of statuses, also see "getFriendships" in UserController.
@@ -37,13 +37,13 @@ public class Friendship {
private FriendShipStatus status;
@Column(nullable = false)
- private LocalDateTime createdAt;
+ private Instant createdAt;
public Friendship(User user, User friend, FriendShipStatus status) {
this.user = user;
this.friend = friend;
this.status = status;
- this.createdAt = LocalDateTime.now();
+ this.createdAt = Instant.now();
}
}
diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties
index 58ec430..d6aff90 100644
--- a/src/main/resources/application.properties
+++ b/src/main/resources/application.properties
@@ -9,6 +9,19 @@ spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
logging.level.org.springframework.security=Trace
springdoc.api-docs.path=/v3/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
-carta.base-url=https://mobydex.locoslab.com/carta
+spring.profiles.active=dev
+spring.jackson.serialization.write-dates-as-timestamps=false
+# Disabled for development - TODO set reasonable rhythm
+sumoc.scheduling.calculate-trend-table-cron=-
+# Trend detection settings
+trenddetection.negative-threshold=-25.0
+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
+# Base URL to external services
+carta.base-url=https://www.innamoruhr.de/c2
nominatim.base-url=http://localhost:6666
-spring.profiles.active=dev
\ No newline at end of file
+meteo.base-url=https://api.open-meteo.com/v1
\ No newline at end of file
diff --git a/src/test/java/SuMoC/backend/routing/services/AlternativeFilterServiceTest.java b/src/test/java/SuMoC/backend/routing/services/AlternativeFilterServiceTest.java
new file mode 100644
index 0000000..baf6529
--- /dev/null
+++ b/src/test/java/SuMoC/backend/routing/services/AlternativeFilterServiceTest.java
@@ -0,0 +1,112 @@
+package SuMoC.backend.routing.services;
+
+import SuMoC.backend.routing.config.OnCallRoutingProperties;
+import SuMoC.backend.routing.dtos.RouteDTO;
+import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
+import SuMoC.backend.routing.dtos.RoutingPreferencesDTO;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import java.time.Instant;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+public class AlternativeFilterServiceTest {
+
+ @Mock(lenient = true)
+ private OnCallRoutingProperties onCallRoutingProperties;
+
+ @InjectMocks
+ private AlternativeFilterService alternativeFilterService;
+
+ private RoutingAlternativeRequestDTO request;
+ private RoutingPreferencesDTO preferences;
+
+ @BeforeEach
+ void setUp() {
+ preferences = new RoutingPreferencesDTO();
+ request = new RoutingAlternativeRequestDTO();
+ request.setDepartureTime(Instant.parse("2023-01-01T10:00:00Z"));
+ request.setArrivalTime(Instant.parse("2023-01-01T11:00:00Z")); // 1 hour
+ request.setRoutingPreferencesDTO(preferences);
+
+ when(onCallRoutingProperties.getAcceptableAdditionalMultiplierRegular()).thenReturn(1.3);
+ when(onCallRoutingProperties.getAcceptableAdditionalMultiplierPrefersPhysical()).thenReturn(1.5);
+ when(onCallRoutingProperties.getMinimumAcceptedAdditionalSecondsRegular()).thenReturn(600);
+ when(onCallRoutingProperties.getMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity()).thenReturn(900);
+ }
+
+ @Test
+ void testFilterRegularPreference_AcceptableRoutes() {
+ preferences.setPreferPhysicalActivity(false);
+ RouteDTO route1 = createRoute(3600 + 300); // delta 300 <4680
+ RouteDTO route2 = createRoute(3600 + 4000); // delta 4000 <4680
+ List alternatives = List.of(route1, route2);
+
+ List result = alternativeFilterService.filterForAdditionalTravelTime(request, alternatives, onCallRoutingProperties);
+
+ assertEquals(2, result.size());
+ }
+
+ @Test
+ void testFilterRegularPreference_UnacceptableRoutes() {
+ preferences.setPreferPhysicalActivity(false);
+ RouteDTO route1 = createRoute(3600 + 4680); // delta 4680 >=4680
+ RouteDTO route2 = createRoute(3600 + 5000); // delta 5000 >=4680
+ List alternatives = List.of(route1, route2);
+
+ List result = alternativeFilterService.filterForAdditionalTravelTime(request, alternatives, onCallRoutingProperties);
+
+ assertEquals(0, result.size());
+ }
+
+ @Test
+ void testFilterPhysicalPreference_AcceptableRoutes() {
+ preferences.setPreferPhysicalActivity(true);
+ RouteDTO route1 = createRoute(3600 + 800); // delta 800 <5400
+ RouteDTO route2 = createRoute(3600 + 5000); // delta 5000 <5400
+ List alternatives = List.of(route1, route2);
+
+ List result = alternativeFilterService.filterForAdditionalTravelTime(request, alternatives, onCallRoutingProperties);
+
+ assertEquals(1, result.size());
+ }
+
+ @Test
+ void testFilterPhysicalPreference_UnacceptableRoutes() {
+ preferences.setPreferPhysicalActivity(true);
+ RouteDTO route1 = createRoute(3600 + 5400); // delta 5400 >=5400
+ RouteDTO route2 = createRoute(3600 + 6000); // delta 6000 >=5400
+ List alternatives = List.of(route1, route2);
+
+ List result = alternativeFilterService.filterForAdditionalTravelTime(request, alternatives, onCallRoutingProperties);
+
+ assertEquals(0, result.size());
+ }
+
+ @Test
+ void testFilter_EdgeCasesAtThresholds() {
+ preferences.setPreferPhysicalActivity(false);
+ RouteDTO route1 = createRoute(3600 + 4679); // delta 4679 <4680
+ RouteDTO route2 = createRoute(3600 + 4680); // delta 4680 >=4680
+ List alternatives = List.of(route1, route2);
+
+ List result = alternativeFilterService.filterForAdditionalTravelTime(request, alternatives, onCallRoutingProperties);
+
+ assertEquals(1, result.size()); // only route1
+ }
+
+ private RouteDTO createRoute(long durationSeconds) {
+ RouteDTO route = RouteDTO.getMockRouteDTO();
+ route.setStartDateTime(Instant.parse("2023-01-01T10:00:00Z"));
+ route.setEndDateTime(Instant.parse("2023-01-01T10:00:00Z").plusSeconds(durationSeconds));
+ return route;
+ }
+}
diff --git a/src/test/java/SuMoC/backend/trend/services/TrendDetectorServiceTest.java b/src/test/java/SuMoC/backend/trend/services/TrendDetectorServiceTest.java
new file mode 100644
index 0000000..41602da
--- /dev/null
+++ b/src/test/java/SuMoC/backend/trend/services/TrendDetectorServiceTest.java
@@ -0,0 +1,165 @@
+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.enums.DeltaType;
+import SuMoC.backend.trend.enums.StatAttribute;
+import SuMoC.backend.trend.enums.TrendTimespan;
+import SuMoC.backend.trend.enums.TrendType;
+import SuMoC.backend.trend.models.WeeklyMobilityStats;
+import SuMoC.backend.user.models.User;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+public class TrendDetectorServiceTest {
+
+ @Mock
+ private WeeklyMobilityStatsRepository weeklyMobilityStatsRepository;
+
+ @Mock
+ private TrendDetectionProperties trendDetectionProperties;
+
+ @InjectMocks
+ private TrendDetectorService trendDetectorService;
+
+ private User user1;
+ private User user2;
+ private User user3;
+
+ @BeforeEach
+ void setUp() {
+ user1 = new User("Private1", "Public1", "user1@example.com", "pass1");
+ user1.setId(1L);
+
+ user2 = new User("Private2", "Public2", "user2@example.com", "pass2");
+ user2.setId(2L);
+
+ user3 = new User("Private3", "Public3", "user3@example.com", "pass3");
+ user3.setId(3L);
+ }
+
+ @Test
+ void detectWeeklyTrends_WithSignificantChanges_DetectsTrends() {
+ // Arrange
+ int year = 2026;
+ int weekNumber = 2;
+
+ // Set threshold values for this test
+ when(trendDetectionProperties.getPositiveThreshold()).thenReturn(25.0);
+ when(trendDetectionProperties.getNegativeThreshold()).thenReturn(-25.0);
+
+ // User 1: Significant increase (100m -> 400m = +300%)
+ WeeklyMobilityStats user1Previous = createWeeklyStats(user1, year, weekNumber - 1, 100L);
+ WeeklyMobilityStats user1Current = createWeeklyStats(user1, year, weekNumber, 400L);
+
+ // User 2: Significant decrease (1000m -> 200m = -80%)
+ WeeklyMobilityStats user2Previous = createWeeklyStats(user2, year, weekNumber - 1, 1000L);
+ WeeklyMobilityStats user2Current = createWeeklyStats(user2, year, weekNumber, 200L);
+
+ // User 3: No significant change (500m -> 550m = +10%)
+ WeeklyMobilityStats user3Previous = createWeeklyStats(user3, year, weekNumber - 1, 500L);
+ WeeklyMobilityStats user3Current = createWeeklyStats(user3, year, weekNumber, 550L);
+
+ 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 detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE);
+
+ // Assert
+ assertEquals(2, detectedTrends.size(), "Should detect 2 trends (1 increase, 1 decrease)");
+
+ // Verify increasing trend for user1
+ TrendDetection user1Trend = detectedTrends.stream()
+ .filter(t -> t.getUser().getId().equals(user1.getId()))
+ .findFirst()
+ .orElse(null);
+ assertNotNull(user1Trend, "User 1 should have a detected trend");
+ assertEquals(TrendType.INCREASING, user1Trend.getType());
+ assertEquals(StatAttribute.CAR_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
+ TrendDetection user2Trend = detectedTrends.stream()
+ .filter(t -> t.getUser().getId().equals(user2.getId()))
+ .findFirst()
+ .orElse(null);
+ assertNotNull(user2Trend, "User 2 should have a detected trend");
+ assertEquals(TrendType.DECREASING, user2Trend.getType());
+ assertEquals(StatAttribute.CAR_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.getUser().getId().equals(user3.getId()));
+ assertFalse(user3HasTrend, "User 3 should not have a detected trend (change below threshold)");
+ }
+
+ @Test
+ void detectWeeklyTrends_WithMissingData_HandlesGracefully() {
+ // Arrange
+ int year = 2026;
+ int weekNumber = 2;
+
+ // User 1: Has current week data but no previous week data
+ WeeklyMobilityStats user1Current = createWeeklyStats(user1, year, weekNumber, 500L);
+
+ // User 2: Has previous week data but no current week data
+ WeeklyMobilityStats user2Previous = createWeeklyStats(user2, year, weekNumber - 1, 800L);
+
+ when(weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber - 1))
+ .thenReturn(List.of(user2Previous));
+ when(weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber))
+ .thenReturn(List.of(user1Current));
+
+ // Act & Assert - should not throw any exception
+ assertDoesNotThrow(() -> {
+ List detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE);
+ assertEquals(0, detectedTrends.size(), "Should not detect any trends when matching data is missing");
+ });
+ }
+
+ /**
+ * Helper method to create WeeklyMobilityStats with specified car distance
+ */
+ private WeeklyMobilityStats createWeeklyStats(User user, int year, int weekNumber, Long carDistance) {
+ return WeeklyMobilityStats.builder()
+ .user(user)
+ .year(year)
+ .weekNumber(weekNumber)
+ .totalDistance(carDistance.doubleValue())
+ .tripCount(10)
+ .sumMobilityScore(50.0)
+ .averageMobilityScore(5.0)
+ .sumMetersTraveled(carDistance)
+ .sumMetersWalkingAndCycling(0L)
+ .sumMetersPublicTransport(0L)
+ .sumMetersWalking(0L)
+ .sumMetersBicycle(0L)
+ .sumMetersEscooter(0L)
+ .sumMetersBus(0L)
+ .sumMetersTram(0L)
+ .sumMetersTrain(0L)
+ .sumMetersCar(carDistance)
+ .sumMetersMotorcycle(0L)
+ .sumMetersTaxi(0L)
+ .build();
+ }
+}
diff --git a/src/test/java/SuMoC/backend/user/repository/FriendshipRepositoryTests.java b/src/test/java/SuMoC/backend/user/repository/FriendshipRepositoryTests.java
index d60772d..33b1369 100644
--- a/src/test/java/SuMoC/backend/user/repository/FriendshipRepositoryTests.java
+++ b/src/test/java/SuMoC/backend/user/repository/FriendshipRepositoryTests.java
@@ -9,7 +9,7 @@ import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
-import java.time.LocalDateTime;
+import java.time.Instant;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
@@ -34,13 +34,13 @@ public class FriendshipRepositoryTests {
.user(user1)
.friend(user2)
.status(FriendShipStatus.PENDING)
- .createdAt(LocalDateTime.now())
+ .createdAt(Instant.now())
.build();
Friendship friendshipReverse = Friendship.builder()
.user(user2)
.friend(user1)
.status(FriendShipStatus.REQUESTED)
- .createdAt(LocalDateTime.now())
+ .createdAt(Instant.now())
.build();
// Act
diff --git a/src/test/java/SuMoC/backend/user/service/UserServiceTest.java b/src/test/java/SuMoC/backend/user/service/UserServiceTest.java
index cfb4ead..55ec007 100644
--- a/src/test/java/SuMoC/backend/user/service/UserServiceTest.java
+++ b/src/test/java/SuMoC/backend/user/service/UserServiceTest.java
@@ -38,6 +38,7 @@ public class UserServiceTest {
@BeforeEach
void setUp() {
+ userRepository.deleteAll();
sender = userRepository.save(uniqueUser(1));
differentUser = userRepository.save(uniqueUser(2));
}
@@ -67,7 +68,7 @@ public class UserServiceTest {
assertEquals(differentUser.getPublicName(), publicSetting.getDisplayName());
- }
+ }
@Test
@@ -86,7 +87,6 @@ public class UserServiceTest {
assertTrue(userRepository.findById(differentUser.getId()).isPresent());
-
}
@@ -101,14 +101,14 @@ public class UserServiceTest {
// Check if user can change his own password
- // Too short password
- assertThrows(RuntimeException.class, () -> userService.setPassword(sender.getId(), "test"));
- // TODO: check why this assertion fails (most likely because of password encoding internals)
- // assertTrue(passwordEncoder.matches("password1", userRepository.findById(sender.getId()).get().getPassword()));
+ // Too short password
+ assertThrows(RuntimeException.class, () -> userService.setPassword(sender.getId(), "test"));
+ // TODO: check why this assertion fails (most likely because of password encoding internals)
+ // assertTrue(passwordEncoder.matches("password1", userRepository.findById(sender.getId()).get().getPassword()));
- // Valid password
- userService.setPassword(sender.getId(), newPassword);
- assertTrue(passwordEncoder.matches(newPassword, userRepository.findById(sender.getId()).get().getPassword()));
+ // Valid password
+ userService.setPassword(sender.getId(), newPassword);
+ assertTrue(passwordEncoder.matches(newPassword, userRepository.findById(sender.getId()).get().getPassword()));
}
@@ -125,17 +125,17 @@ public class UserServiceTest {
// Check if user can change his own email
- // Other user's email
- assertThrows(RuntimeException.class, () -> userService.setEmail(sender.getId(), differentUser.getEmail()));
- assertEquals(sender.getEmail(), userRepository.findById(sender.getId()).get().getEmail());
+ // Other user's email
+ assertThrows(RuntimeException.class, () -> userService.setEmail(sender.getId(), differentUser.getEmail()));
+ assertEquals(sender.getEmail(), userRepository.findById(sender.getId()).get().getEmail());
- // Invalid email format
- assertThrows(RuntimeException.class, () -> userService.setEmail(sender.getId(), invalidEmail));
- assertEquals(sender.getEmail(), userRepository.findById(sender.getId()).get().getEmail());
+ // Invalid email format
+ assertThrows(RuntimeException.class, () -> userService.setEmail(sender.getId(), invalidEmail));
+ assertEquals(sender.getEmail(), userRepository.findById(sender.getId()).get().getEmail());
- // Valid email
- userService.setEmail(sender.getId(), newEmail);
- assertEquals(newEmail, userRepository.findById(sender.getId()).get().getEmail());
+ // Valid email
+ userService.setEmail(sender.getId(), newEmail);
+ assertEquals(newEmail, userRepository.findById(sender.getId()).get().getEmail());
}
@@ -178,5 +178,4 @@ public class UserServiceTest {
}
-
}