Merge remote-tracking branch 'origin/main' into gamification/scoretables

This commit is contained in:
2026-01-13 12:14:22 +01:00
83 changed files with 2546 additions and 199 deletions
@@ -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) {
@@ -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,
@@ -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<String> 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) {
}
}
}
@@ -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();
}
}
}
@@ -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
) {
}
@@ -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;
}
@@ -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<String> 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<String> getRoutePatternNeighbors(String cellId) {
return getKRingNeighbors(cellId, config.getRoutePatternNeighborRings());
}
}
@@ -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<Integer> 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<WeatherCondition> 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<WeatherCondition>();
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<LocalDateTime> time,
@JsonProperty("weather_code") List<Integer> weatherCode
) {
}
}
@@ -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();
}
}
@@ -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<ForecastResponse> 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);
}
}
@@ -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();
}
}
@@ -0,0 +1,9 @@
package SuMoC.backend.meteo;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "meteo")
public record MeteoProperties(
String baseUrl
) {
}
@@ -0,0 +1,7 @@
package SuMoC.backend.meteo;
public class UnknownWeatherCodeException extends RuntimeException {
public UnknownWeatherCodeException(String message) {
super(message);
}
}
@@ -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<Integer> codes;
WeatherCondition(Set<Integer> 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.");
}
}
@@ -0,0 +1,7 @@
package SuMoC.backend.notification.enums;
public enum NotificationStatus {
PENDING,
SENT,
FAILED
}
@@ -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();
}
}
@@ -0,0 +1,4 @@
package SuMoC.backend.notification.interfaces;
public interface NotificationPublisher {
}
@@ -0,0 +1,4 @@
package SuMoC.backend.notification.interfaces;
public interface NotificationSender {
}
@@ -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;
}
@@ -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<Notification, Long> {
}
@@ -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<Notification> generateTrendNotifications(List<TrendDetection> trendList) {
List<Notification> notificationList = trendList.stream().map(trendNotificationFactory::createNotification).toList();
return List.of();
}
}
@@ -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);
}
}
@@ -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";
}
@@ -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<DetectedRegularTripDTO> detectRegularTrips(List<RegularTripDetectionDTO> trips);
}
@@ -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<DetectedRegularTripDTO> detectRegularTrips(List<RegularTripDetectionDTO> trips) {
// Step 1: Init potential detected trip for all trips
HashMap<Long, DetectedRegularTripDTO> baseDetectedTripsMap = initDetectedTripsMap(trips);
// Step 2: Find trips supported by min number of supporters
List<List<DetectedRegularTripDTO>> iterationResults = new ArrayList<>();
for (int i = 0; i < properties.getIterativeShuffleAmounts(); i++) {
// Deep copy the map for each iteration
HashMap<Long, DetectedRegularTripDTO> iterationMap = deepCopyDetectedTripsMap(baseDetectedTripsMap);
Collections.shuffle(trips);
iterationResults.add(aggregateToSupportedDetections(iterationMap, trips, properties.getMinTripsForRegularity()));
}
List<DetectedRegularTripDTO> bestIteration = pickBestIteration(iterationResults);
return deduplicateOverlappingDetections(bestIteration);
}
/**
* Picks the best detection results by picking iteration with the highest total number of supporters.
*/
private List<DetectedRegularTripDTO> pickBestIteration(List<List<DetectedRegularTripDTO>> 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<DetectedRegularTripDTO> deduplicateOverlappingDetections(List<DetectedRegularTripDTO> detections) {
// Sort by supporter count (descending)
List<DetectedRegularTripDTO> sorted = new ArrayList<>(detections);
sorted.sort(Comparator.comparingInt(d -> -d.getSupportingTrips().size()));
List<DetectedRegularTripDTO> result = new ArrayList<>();
Set<Long> usedTripIds = new HashSet<>();
for (DetectedRegularTripDTO detection : sorted) {
// Get all trip IDs involved in this detection
Set<Long> 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<DetectedRegularTripDTO> aggregateToSupportedDetections(
HashMap<Long, DetectedRegularTripDTO> potentialDetectedRegularTrips,
List<RegularTripDetectionDTO> trips,
int necessarySupporters
) {
// We need to dupe deletions with this list since we cant modify other list entries while iterating over it
Set<Long> deletedDetections = new HashSet<>();
for (Map.Entry<Long, DetectedRegularTripDTO> 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<DetectedRegularTripDTO> detectedTrips = new ArrayList<>();
for (Map.Entry<Long, DetectedRegularTripDTO> 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<Long, DetectedRegularTripDTO> initDetectedTripsMap(List<RegularTripDetectionDTO> trips) {
HashMap<Long, DetectedRegularTripDTO> 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<RegularTripDetectionDTO>(List.of(trip)))
.build());
}
return potentialDetectedTrips;
}
private HashMap<Long, DetectedRegularTripDTO> deepCopyDetectedTripsMap(
HashMap<Long, DetectedRegularTripDTO> original) {
HashMap<Long, DetectedRegularTripDTO> copy = new HashMap<>();
for (Map.Entry<Long, DetectedRegularTripDTO> 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;
}
}
@@ -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<String> startH3neighbours;
private List<String> endH3Neighbours;
private List<RegularTripDetectionDTO> supportingTrips;
}
@@ -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<Long, List<DetectedRegularTripDTO>> detectRegularCarTrips() {
var tripsByUser = getTripsByUser(Modality.CAR);
// TODO this could be parallelized in the future
HashMap<Long, List<DetectedRegularTripDTO>> results = new HashMap<>();
for (Long userId : tripsByUser.keySet()) {
results.put(userId, tripDetector.detectRegularTrips(tripsByUser.get(userId)));
}
return results;
}
private HashMap<Long, List<RegularTripDetectionDTO>> getTripsByUser(Modality modality) {
Instant fromDate = Instant.now().minusSeconds(properties.getDetectionTimeWindowDays() * 24 * 60 * 60);
List<RegularTripDetectionDTO> dtoList = tripMapper.toRegularTripDetectionDTOS(tripRepository.findAllValidFromDateWithMainModality(fromDate, modality));
HashMap<Long, List<RegularTripDetectionDTO>> tripsByUser = new HashMap<>();
for (RegularTripDetectionDTO dto : dtoList) {
tripsByUser.computeIfAbsent(dto.getUserId(), k -> new ArrayList<>()).add(dto);
}
return tripsByUser;
}
}
@@ -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<List<RouteDTO>> 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<RouteDTO> mockDTOs = new ArrayList<>();
mockDTOs.add(RouteDTO.getMockRouteDTO());
mockDTOs.add(RouteDTO.getMockRouteDTO());
@@ -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);
}
}
@@ -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);
}
}
@@ -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 {
}
@@ -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<WeatherCondition> acceptableWalkingConditions;
private List<WeatherCondition> 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
);
}
}
@@ -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<StepDTO> 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<StepDTO> 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<StepDTO> 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<StepDTO>(),
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);
}
}
@@ -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;
}
@@ -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<RouteDTO> filterForAdditionalTravelTime(
RoutingAlternativeRequestDTO alternativeRequestDTO,
List<RouteDTO> alternatives,
RoutingProperties routingProperties
) {
List<RouteDTO> 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<RouteDTO> filterForBadWeather(
RoutingAlternativeRequestDTO requestDTO,
List<RouteDTO> alternatives,
RoutingProperties routingProperties
) {
try {
ForecastResponse forecast = forecastService.getTodayYesterdayForecast(requestDTO.getOriginLat(), requestDTO.getOriginLon());
ArrayList<RouteDTO> 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<WeatherCondition> conditions, List<WeatherCondition> acceptableConditions) {
return new HashSet<>(acceptableConditions).containsAll(conditions);
}
}
@@ -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<StepDTO> 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<StepDTO> 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<StepDTO> 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;
}
}
@@ -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<RouteDTO> 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<RouteDTO> determineAlternativeRoutesOnUserRequest(RoutingAlternativeRequestDTO requestDTO) {
List<RouteDTO> 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<RouteDTO> determineAlternativeRoutesAdHoc(RoutingAlternativeRequestDTO requestDTO) {
assert requestDTO.getRoutingPreferencesDTO() != null;
List<RouteDTO> 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<RouteDTO> getPossibleAlternativeRoutes(RoutingAlternativeRequestDTO requestDTO) {
assert requestDTO.getRoutingPreferencesDTO() != null;
HashMap<String, Direction> directionMap = getPossibleDirectionsFromCarta(requestDTO);
ArrayList<RouteDTO> 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<StepDTO> steps = new ArrayList<>();
steps.add(new StepDTO(
Modality.BICYCLE,
null,
bikeRoute.getDistance()
)
);
ArrayList<StepDTO> 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<StepDTO> steps = new ArrayList<>();
steps.add(new StepDTO(
Modality.WALKING,
null,
walkRoute.getDistance()
));
ArrayList<StepDTO> 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;
}
}
@@ -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);
}
}
}
@@ -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;
}
}
@@ -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
}
@@ -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")
@@ -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);
}
}
});
}
@@ -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;
}
@@ -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();
}
}
@@ -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;
}
}
}
@@ -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<WeeklyMobilityStats, WeeklyMobilityStatsId> {
@Query("SELECT wms FROM WeeklyMobilityStats wms JOIN FETCH wms.user WHERE wms.year = :year AND wms.weekNumber = :weekNumber")
List<WeeklyMobilityStats> findAllByYearAndWeekNumberWithUser(@Param("year") Integer year, @Param("weekNumber") Integer weekNumber);
}
@@ -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;
}
@@ -0,0 +1,6 @@
package SuMoC.backend.trend.enums;
public enum DeltaType {
ABSOLUTE,
PERCENTAGE
}
@@ -0,0 +1,8 @@
package SuMoC.backend.trend.enums;
/**
* Represents statistical attributes a detected trend can pertain to.
*/
public enum StatAttribute {
CAR_DISTANCE,
}
@@ -0,0 +1,7 @@
package SuMoC.backend.trend.enums;
public enum TrendConnotation {
POSITIVE,
NEGATIVE,
NEUTRAL
}
@@ -0,0 +1,5 @@
package SuMoC.backend.trend.enums;
public enum TrendTimespan {
WEEKLY,
}
@@ -0,0 +1,7 @@
package SuMoC.backend.trend.enums;
public enum TrendType {
INCREASING,
DECREASING,
STABLE
}
@@ -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;
};
}
}
@@ -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;
}
@@ -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<Trip> 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<Long, List<Trip>> 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<Long, List<Trip>> entry : tripsByUser.entrySet()) {
Long userId = entry.getKey();
List<Trip> userTrips = entry.getValue();
var stats = WeeklyMobilityStatsCalculator.calculateStats(year, weekNumber, userTrips);
weeklyMobilityStatsRepository.save(stats);
}
logger.info("Finished calculation of weekly mobility stats for all users.");
}
}
@@ -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<TrendDetection> detectWeeklyTrends(Integer year, Integer weekNumber, StatAttribute attribute) {
// Fetch stats for current and previous week
List<WeeklyMobilityStats> 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<WeeklyMobilityStats> currentWeekStatsList = weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber);
// Convert to maps for easy userId-based lookup
Map<Long, WeeklyMobilityStats> previousWeekStats = previousWeekStatsList.stream()
.collect(Collectors.toMap(stats -> stats.getUser().getId(), stats -> stats));
Map<Long, WeeklyMobilityStats> currentWeekStats = currentWeekStatsList.stream()
.collect(Collectors.toMap(stats -> stats.getUser().getId(), stats -> stats));
// Detect trends for provided attribute
List<TrendDetection> detectedTrends = new ArrayList<>();
for (Map.Entry<Long, WeeklyMobilityStats> 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;
}
}
@@ -0,0 +1,8 @@
package SuMoC.backend.trend.services;
import org.springframework.stereotype.Component;
@Component
public class TrendMessageGenerator {
}
@@ -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<Trip> 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();
}
}
+15 -1
View File
@@ -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);
};
}
}
@@ -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<Void> 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();
}
@@ -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();
@@ -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<TripDTO> toTripDTOs(List<Trip> trips);
public abstract List<TripDTO> toTripDTOs(List<Trip> 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<RegularTripDetectionDTO> toRegularTripDetectionDTOS(List<Trip> 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<String> calculateStartH3KRingNeighboords(Trip trip) {
return h3service.getRoutePatternNeighbors(trip.getStartH3Cell());
}
protected List<String> calculateEndtH3KRingNeighboords(Trip trip) {
return h3service.getRoutePatternNeighbors(trip.getEndH3Cell());
}
protected Modality mainModalityByDistance(NewTripDTO newTripDTO) {
HashMap<Modality, Float> 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);
}
}
@@ -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<Trip,Long> {
public interface TripRepository extends JpaRepository<Trip, Long> {
Optional<Trip> findTripById(Long id);
Optional<List<Trip>> 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<Trip> 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<Trip> findAllValidFromDateWithMainModality(Instant fromDate, Modality modality);
}
@@ -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<TripDTO> getAllTripsOfUser(User user) {
@@ -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
@@ -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;
}
@@ -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<String> startH3CellKRingNeighboors;
private List<String> endH3CellKRingNeighboors;
public int getDayOfTheWeek() {
return startTime.atZone(java.time.ZoneId.systemDefault()).getDayOfWeek().getValue();
}
}
@@ -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<TripSegmentDTO> tripSegments;
@@ -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;
@@ -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<TripSegment> tripSegments = new HashSet<>();
}
@@ -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;
@@ -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;
}
}
@@ -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();
}
}