Author SHA1 Message Date
neuhauss e3b218637b WIP - upload shelf from work computer
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-03 18:37:31 +01:00
neuhauss 4fe86b6845 remove call to currentUserService to prevent 401 on not logged in users
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-02 10:39:07 +01:00
neuhauss c43101e5dc test bugfix
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-02 10:26:56 +01:00
neuhauss d882c8e3b3 align with directions controller for testing
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-02 10:21:32 +01:00
neuhauss 14cb4f4f88 reorder routes
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-02 10:11:06 +01:00
neuhauss e5e6dc9e2a Merge branch 'routing_endpoint'
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-01 19:37:22 +01:00
neuhauss 8eaea03b47 fix bug, carta needs to handle arrivalTime OR departureTime being null
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-01 19:36:08 +01:00
neuhauss ff4d352e08 extend todo comment
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-01 19:23:45 +01:00
neuhauss 657acbc736 refactor routeDTO creation + handle different time cases 2026-02-01 19:15:00 +01:00
neuhauss 6393a4a650 reformat RouteDTO 2026-02-01 19:14:29 +01:00
neuhauss cb397e7e63 implement routing/drections endpoint for requesting routes without alternatives logic, includes refactoring of previous alternative routing logic into carta DirectionsService to reuse code
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-01 18:07:37 +01:00
harb 69347f8f56 Merge pull request 'StatsListAdd' (#16) from StatsListAdd into main
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Reviewed-on: #16
2026-02-01 01:06:35 +01:00
Elias Harb e68e163214 Prevent Json nesting for stats
LocationBasedServices/sumoc-backend/pipeline/pr-main Build queued...
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
- stats are cyclic which is awful for transmitting the stats to the client

Could not write JSON: Document nesting depth (1001) exceeds the maximum allowed (1000, from StreamWriteConstraints.getMaxNestingDepth())
2026-02-01 00:52:55 +01:00
Elias Harb 5e16591913 Added Endpoint to retrieve all stats 2026-01-31 23:26:14 +01:00
neuhauss 6aaff14c0d Merge branch 'main' into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-30 16:22:22 +01:00
neuhauss 1b39185454 Merge branch 'notifications_for_friendship_request'
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-30 16:22:16 +01:00
neuhauss 43ab63f77d add testing endpoint for friendship request notification
LocationBasedServices/sumoc-backend/pipeline/head Build started...
2026-01-30 16:22:10 +01:00
neuhauss d72a12d089 Merge branch 'main' into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-30 16:12:39 +01:00
neuhauss 39e385cac3 add testing endpoint for regular trip detection (very slow yet)
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-30 16:11:55 +01:00
neuhauss e41fff0840 add correct test for dow conversion 2026-01-30 16:11:29 +01:00
neuhauss 256145f65b fix bug in day of week conversion 2026-01-30 16:11:17 +01:00
neuhauss c636d04fea fix test by switching to springboottest 2026-01-30 12:30:07 +01:00
neuhauss 5490958d6e add README for notification system 2026-01-30 11:50:10 +01:00
neuhauss 06b35c13b6 add notification for received friendship request 2026-01-30 11:49:53 +01:00
neuhauss 48063d442c switch to currentUserService 2026-01-30 11:49:34 +01:00
harb 29b6ac052f Merge pull request 'add friendCode to userDTOs' (#15) from friendCodeFix into main
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Reviewed-on: #15
2026-01-29 23:40:27 +01:00
Elias Harb c3f291a08b add friendCode to userDTOs
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
LocationBasedServices/sumoc-backend/pipeline/pr-main Build started...
2026-01-29 23:21:57 +01:00
laaser 30fe944387 Merge branch 'deploy' of https://project.nes.uni-due.de/gitea/lbs/sumoc-backend into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-29 20:53:44 +01:00
laaser 43cf5239fc Merge branch 'deploy' 2026-01-29 20:51:38 +01:00
neuhauss a8f95b680a fix entrypoint
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-28 10:15:43 +01:00
neuhauss f051efa9eb Merge branch 'main' into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-27 21:41:59 +01:00
laaser 7bbbf903de Merge branch 'main' into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-27 17:52:03 +01:00
neuhauss a691e911a2 Merge branch 'main' into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-27 11:15:41 +01:00
neuhauss 0564733c39 stop resetting db
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-26 16:25:24 +01:00
neuhauss 9aed0a2703 Merge branch 'main' into deploy 2026-01-26 16:24:37 +01:00
neuhauss 23e5affa71 Merge branch 'main' into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
# Conflicts:
#	docker-compose.yml
2026-01-25 19:49:04 +01:00
laaser 00cbff062e Merge branch 'main' into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-23 15:12:02 +01:00
laaser 75af061871 Merge main
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-23 14:29:01 +01:00
51 changed files with 1177 additions and 443 deletions
Vendored
+2 -2
View File
@@ -25,8 +25,8 @@ node('built-in') {
sh 'scp -i $KEYFILE docker-compose.yml pg-sumoc@apps-dev.nes:~'
sh 'scp -i $KEYFILE docker-load.sh pg-sumoc@apps-dev.nes:~'
sh 'scp -i $KEYFILE -r docker_images pg-sumoc@apps-dev.nes:~'
echo "Resetting database..."
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose down -v"'
// echo "Resetting database..."
// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose down -v"'
// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"'
// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm -f sumoc-backend_postgres_data"'
echo "Load docker images on server ..."
@@ -53,7 +53,7 @@ public class CartaClient {
origin,
destination,
mode.toLowerCase(), // possible values: walking, driving, cycling
arrivalTime.getEpochSecond(),
arrivalTime != null ? arrivalTime.getEpochSecond() : null,
departureTime != null ? departureTime.getEpochSecond() : null,
alternatives,
walkingSpeed,
@@ -0,0 +1,32 @@
package SuMoC.backend.carta;
public interface DirectionsRequest {
Double getOriginLat();
void setOriginLat(Double originLat);
Double getOriginLon();
void setOriginLon(Double originLon);
Double getDestinationLat();
void setDestinationLat(Double destinationLat);
Double getDestinationLon();
void setDestinationLon(Double destinationLon);
java.time.Instant getArrivalTime();
void setArrivalTime(java.time.Instant arrivalTime);
java.time.Instant getDepartureTime();
void setDepartureTime(java.time.Instant departureTime);
SuMoC.backend.routing.dtos.RoutingPreferencesDTO getRoutingPreferencesDTO();
void setRoutingPreferencesDTO(SuMoC.backend.routing.dtos.RoutingPreferencesDTO routingPreferencesDTO);
}
@@ -1,15 +1,12 @@
package SuMoC.backend.routing.services;
package SuMoC.backend.carta;
import SuMoC.backend.carta.CartaClient;
import SuMoC.backend.geocoding.AddressDTO;
import SuMoC.backend.geocoding.GeoCodingService;
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.routing.services.CartaTransitRouteProcessor;
import SuMoC.backend.trip.Modality;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@@ -17,48 +14,208 @@ import reactor.core.publisher.Mono;
import sumoc.backend.carta.client.model.Direction;
import sumoc.backend.carta.client.model.Route;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import static SuMoC.backend.trip.Modality.BICYCLE;
import static SuMoC.backend.trip.Modality.CAR;
@Service
@RequiredArgsConstructor
public class RoutingService {
private final GeoCodingService geoCodingService;
public class DirectionsService {
private final CartaClient cartaClient;
private final AlternativeFilterService alternativeFilterService;
private final GeoCodingService geoCodingService;
private final OnCallRoutingProperties onCallRoutingProperties;
private final AdHocRoutingProperties adHocRoutingProperties;
public List<RouteDTO> getPossibleAlternativeRoutes(DirectionsRequest requestDTO) {
return getPossibleRoutes(requestDTO, false);
}
/**
* Makes an individual call to the CARTA API and returns a direction future.
* Returns possible routes for the request - no sanity filtering regarding travel times etc. is applied.
* TODO this does not handle the case where origin/destination is provided as address only -> geocoding call to carta needed -> do in directions controller
*/
private CompletableFuture<Direction> getCartaFuture(
RoutingAlternativeRequestDTO requestDTO,
String mode,
String types,
int alternatives
) {
return cartaClient.asyncGetRoute(
requestDTO.getOriginLat() + "," + requestDTO.getOriginLon(),
requestDTO.getDestinationLat() + "," + requestDTO.getDestinationLon(),
mode,
requestDTO.getArrivalTime(),
null,
alternatives, // alternatives
null, // walkingSpeed
null, // transferTime TODO what is default? adapt?
types,
null, // range
requestDTO.getOriginLat() + "," + requestDTO.getOriginLon()
public List<RouteDTO> getPossibleRoutes(DirectionsRequest requestDTO, boolean includeCarRoute) {
assert requestDTO.getRoutingPreferencesDTO() != null;
HashMap<String, Direction> directionMap = getPossibleDirections(requestDTO);
ArrayList<RouteDTO> suggestedRoutes = new ArrayList<>();
// Fetch origin and destination addresses concurrently
var addressesMono = Mono.zip(
geoCodingService.getAddress(requestDTO.getOriginLat(), requestDTO.getOriginLon()),
geoCodingService.getAddress(requestDTO.getDestinationLat(), requestDTO.getDestinationLon())
);
var addressesTuple = addressesMono.block();
AddressDTO originAddress = addressesTuple.getT1();
AddressDTO destinationAddress = addressesTuple.getT2();
// Setting up car data for baseline
Route carRoute;
try {
carRoute = directionMap.get("car").getRoutes().getFirst();
} catch (NullPointerException e) {
throw new NoCarRouteFoundException("No car route to compare to was found.");
}
double carCarbondDioxide;
try {
carCarbondDioxide = carRoute.getEmission().getCarbonDioxide();
} catch (NullPointerException e) {
throw new NoCarbonEmissionFoundException("No carbon emission was provided for the car route.");
}
double carDuration = carRoute.getDuration();
// Creating RouteDTOs for all available modes
if (includeCarRoute) {
Direction carDirection = directionMap.get("car");
if (carDirection.getRoutes() != null && !carDirection.getRoutes().isEmpty()) {
suggestedRoutes.add(createRouteDTO(
requestDTO,
carRoute,
List.of(new StepDTO(CAR, carRoute.getDistance())),
originAddress,
destinationAddress,
null,
null,
carCarbondDioxide,
carDuration,
false
));
}
}
if (directionMap.containsKey("bike")) {
Direction bikeDirection = directionMap.get("bike");
if (bikeDirection.getRoutes() != null && !bikeDirection.getRoutes().isEmpty()) {
Route bikeRoute = bikeDirection.getRoutes().getFirst();
suggestedRoutes.add(createRouteDTO(
requestDTO,
bikeRoute,
List.of(new StepDTO(BICYCLE, bikeRoute.getDistance())),
originAddress,
destinationAddress,
null,
null,
carCarbondDioxide,
carDuration,
false
));
}
}
if (directionMap.containsKey("walk")) {
Direction walkDirection = directionMap.get("walk");
if (walkDirection.getRoutes() != null && !walkDirection.getRoutes().isEmpty()) {
Route walkRoute = walkDirection.getRoutes().getFirst();
suggestedRoutes.add(createRouteDTO(
requestDTO,
walkRoute,
List.of(new StepDTO(Modality.WALKING, walkRoute.getDistance())),
originAddress,
destinationAddress,
null,
null,
carCarbondDioxide,
carDuration,
false
));
}
}
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);
suggestedRoutes.add(createRouteDTO(
requestDTO,
route,
routeProcessor.getSteps(),
originAddress,
destinationAddress,
routeProcessor.getFirstStopName(),
routeProcessor.getLastStopName(),
carCarbondDioxide,
carDuration,
true
));
}
}
}
return suggestedRoutes;
}
private RouteDTO createRouteDTO(
DirectionsRequest requestDTO,
Route route,
List<StepDTO> steps,
AddressDTO originAddress,
AddressDTO destinationAddress,
String firstStopName,
String lastStopName,
double carVariantco2Emission,
double carVariantTimeSeconds,
boolean isTransit
) {
Instant arrivalTime;
Instant departureTime;
// Baseline is comparing with car version, except for alternative route requests
double timeDifferenceSeconds = route.getDuration() - carVariantTimeSeconds;
if (requestDTO.getArrivalTime() != null && requestDTO.getDepartureTime() != null) {
// Case 1: both arrival and departure time provided -> must be alternative route request
if (isTransit) { // for transit routes, we need to look up the exact arrival time at the last stop
arrivalTime = cartaTimeToInstant(route.getSteps().getLast().getStopTime(), requestDTO.getArrivalTime());
} else {
arrivalTime = requestDTO.getArrivalTime();
}
departureTime = arrivalTime.minusSeconds(route.getDuration());
timeDifferenceSeconds = route.getDuration() - (requestDTO.getArrivalTime().getEpochSecond() - requestDTO.getDepartureTime().getEpochSecond());
} else if (requestDTO.getArrivalTime() != null) {
// Case 2: only arrival time provided
if (isTransit) {
arrivalTime = cartaTimeToInstant(route.getSteps().getLast().getStopTime(), requestDTO.getArrivalTime());
} else {
arrivalTime = requestDTO.getArrivalTime();
}
departureTime = arrivalTime.minusSeconds(route.getDuration());
} else {
// Case 3: only departure time provided
if (isTransit) {
departureTime = cartaTimeToInstant(route.getSteps().getFirst().getStartTime(), requestDTO.getDepartureTime());
} else {
departureTime = requestDTO.getDepartureTime();
}
arrivalTime = departureTime.plusSeconds(route.getDuration());
}
double co2savings = carVariantco2Emission - route.getEmission().getCarbonDioxide();
RouteDTO routeDTO = new RouteDTO(
originAddress,
firstStopName,
route.getSourceCoordinate().getLatitude(),
route.getSourceCoordinate().getLongitude(),
destinationAddress,
lastStopName,
route.getTargetCoordinate().getLatitude(),
route.getTargetCoordinate().getLongitude(),
departureTime,
arrivalTime,
steps,
co2savings,
timeDifferenceSeconds,
route.getEmission().getCarbonDioxide()
);
return routeDTO;
}
/**
@@ -69,7 +226,7 @@ public class RoutingService {
* - bike (optional)
* - transit (optional)
*/
private HashMap<String, Direction> getPossibleDirectionsFromCarta(RoutingAlternativeRequestDTO requestDTO) {
private HashMap<String, Direction> getPossibleDirections(DirectionsRequest requestDTO) {
Map<String, CompletableFuture<Direction>> futuresByMode = new HashMap<>();
assert requestDTO.getRoutingPreferencesDTO() != null;
@@ -113,188 +270,48 @@ public class RoutingService {
}
/**
* 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.
* Converts a Carta time (seconds since midnight of current day) to an Instant.
*
* @return
*/
public List<RouteDTO> determineAlternativeRoutesOnUserRequest(RoutingAlternativeRequestDTO requestDTO) {
List<RouteDTO> routes = getPossibleAlternativeRoutes(requestDTO);
routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, onCallRoutingProperties);
return routes;
private Instant cartaTimeToInstant(Integer secondsSinceMidnight, Instant instantOfReferenceDay) {
LocalDate date = instantOfReferenceDay.atZone(ZoneId.systemDefault()).toLocalDate();
LocalDateTime startOfDay = date.atStartOfDay();
LocalDateTime resultDateTime = startOfDay.plusSeconds(secondsSinceMidnight);
return resultDateTime.atZone(ZoneId.systemDefault()).toInstant();
}
/**
* 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.
* Makes an individual call to the CARTA API and returns a direction future.
*/
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);
private CompletableFuture<Direction> getCartaFuture(
DirectionsRequest requestDTO,
String mode,
String types,
int alternatives
) {
Instant departureTime = null;
Instant arrivalTime = null;
if (requestDTO.getArrivalTime() != null) {
arrivalTime = requestDTO.getArrivalTime();
} else if (requestDTO.getDepartureTime() != null) {
departureTime = requestDTO.getDepartureTime();
} else {
throw new IllegalArgumentException("Either arrivalTime or departureTime must be provided.");
}
return routes;
}
public RouteDTO determineBestAlternativeRouteForRegularTrip(RoutingAlternativeRequestDTO requestDTO) {
assert requestDTO.getRoutingPreferencesDTO() != null;
// TODO for now we use adHocRoutingProperties here, in the future we might want to have separate properties for regular trip alternatives
List<RouteDTO> routes = getPossibleAlternativeRoutes(requestDTO);
routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, adHocRoutingProperties);
if (requestDTO.getRoutingPreferencesDTO().isConsiderWeatherConditions()) {
routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties);
}
RouteDTO bestRoute = null;
// if users wants physical activity, we pick the fastest physical activity route, if any
if (requestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity()) {
bestRoute = routes.stream()
.filter(RouteDTO::isPhysicalActivity)
.min((r1, r2) -> Long.compare(
r1.getDurationSeconds(),
r2.getDurationSeconds()
)).orElse(null);
if (bestRoute != null) {
return bestRoute;
}
}
// else we pick the fastest route overall
bestRoute = routes.stream()
.min((r1, r2) -> Long.compare(
r1.getDurationSeconds(),
r2.getDurationSeconds()
)).orElse(null);
return bestRoute;
}
/**
* Returns possible alternative routes for the request - no sanity filtering regarding travel times etc. is applied.
*/
private List<RouteDTO> getPossibleAlternativeRoutes(RoutingAlternativeRequestDTO requestDTO) {
assert requestDTO.getRoutingPreferencesDTO() != null;
HashMap<String, Direction> directionMap = getPossibleDirectionsFromCarta(requestDTO);
ArrayList<RouteDTO> suggestedAlternatives = new ArrayList<>();
// Fetch origin and destination addresses concurrently
var addressesMono = Mono.zip(
geoCodingService.getAddress(requestDTO.getOriginLat(), requestDTO.getOriginLon()),
geoCodingService.getAddress(requestDTO.getDestinationLat(), requestDTO.getDestinationLon())
return cartaClient.asyncGetRoute(
requestDTO.getOriginLat() + "," + requestDTO.getOriginLon(),
requestDTO.getDestinationLat() + "," + requestDTO.getDestinationLon(),
mode,
arrivalTime,
departureTime,
alternatives, // alternatives
null, // walkingSpeed
null, // transferTime TODO what is default? adapt?
types,
null, // range
requestDTO.getOriginLat() + "," + requestDTO.getOriginLon()
);
var addressesTuple = addressesMono.block();
AddressDTO originAddress = addressesTuple.getT1();
AddressDTO destinationAddress = addressesTuple.getT2();
// Setting up car data for baseline
Route carRoute;
try {
carRoute = directionMap.get("car").getRoutes().getFirst();
} catch (NullPointerException e) {
throw new NoCarRouteFoundException("No car route to compare to was found.");
}
double carCarbondDioxide;
try {
carCarbondDioxide = carRoute.getEmission().getCarbonDioxide();
} catch (NullPointerException e) {
throw new NoCarbonEmissionFoundException("No carbon emission was provided for the car route.");
}
if (directionMap.containsKey("bike")) {
Direction bikeDirection = directionMap.get("bike");
if (bikeDirection.getRoutes() != null && !bikeDirection.getRoutes().isEmpty()) {
Route bikeRoute = bikeDirection.getRoutes().getFirst();
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(),
0.0
);
suggestedAlternatives.add(routeDTO);
}
}
if (directionMap.containsKey("walk")) {
Direction walkDirection = directionMap.get("walk");
if (walkDirection.getRoutes() != null && !walkDirection.getRoutes().isEmpty()) {
Route walkRoute = walkDirection.getRoutes().getFirst();
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,
routeProcessor.getFirstStopName(),
route.getSourceCoordinate().getLatitude(),
route.getSourceCoordinate().getLongitude(),
destinationAddress,
routeProcessor.getLastStopName(),
route.getTargetCoordinate().getLatitude(),
route.getTargetCoordinate().getLongitude(),
requestDTO.getArrivalTime().minusSeconds(route.getDuration()),
requestDTO.getArrivalTime(),
routeProcessor.getSteps(),
carCarbondDioxide - route.getEmission().getCarbonDioxide(),
route.getDuration() - carRoute.getDuration(),
route.getEmission().getCarbonDioxide()
);
suggestedAlternatives.add(routeDTO);
}
}
}
return suggestedAlternatives;
}
}
@@ -2,11 +2,12 @@ package SuMoC.backend.common.converter;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import java.time.DayOfWeek;
/**
* This converter handles the conversion between Java's DayOfWeek enum and the SQL DAY_OF_WEEK integer representation.
* In Java, DayOfWeek uses 1 (Monday) to 7 (Sunday), while SQL's DAY_OF_WEEK function returns 1 (Sunday) to 7 (Saturday).
* In Java, DayOfWeek uses 1 (Monday) to 7 (Sunday), while SQL's DAY_OF_WEEK function returns 0 (Sunday) to 6 (Saturday).
*/
@Converter(autoApply = true)
public class DayOfWeekConverter implements AttributeConverter<DayOfWeek, Integer> {
@@ -16,8 +17,8 @@ public class DayOfWeekConverter implements AttributeConverter<DayOfWeek, Integer
if (attribute == null) {
return null;
}
// Convert Java DayOfWeek (1=Monday) to SQL format (1=Sunday)
return (attribute.getValue() % 7) + 1;
// Convert Java DayOfWeek (1=Monday, ..., 7=Sunday) to SQL DOW (0=Sunday, ..., 6=Saturday)
return attribute.getValue() % 7;
}
@Override
@@ -25,10 +26,7 @@ public class DayOfWeekConverter implements AttributeConverter<DayOfWeek, Integer
if (dbData == null) {
return null;
}
// Convert SQL format (1=Sunday) back to Java DayOfWeek (1=Monday)
// Example: SQL 1 (Sunday) -> Java 7
// SQL 7 (Saturday) -> Java 6
// SQL 2 (Monday) -> Java 1
return DayOfWeek.of(((dbData + 5) % 7) + 1);
// Convert SQL DOW (0=Sunday, ..., 6=Saturday) to Java DayOfWeek (1=Monday, ..., 7=Sunday)
return DayOfWeek.of(dbData == 0 ? 7 : dbData);
}
}
@@ -13,7 +13,12 @@ import SuMoC.backend.routing.dtos.RouteDTO;
import SuMoC.backend.scheduling.ScheduledTasks;
import SuMoC.backend.suggestion.services.RegularTripSuggestionService;
import SuMoC.backend.trend.dto.TrendDetectionDTO;
import SuMoC.backend.trend.enums.DeltaType;
import SuMoC.backend.trend.enums.StatAttribute;
import SuMoC.backend.trend.services.StatTableUpdateService;
import SuMoC.backend.user.dtos.FriendshipDTO;
import SuMoC.backend.user.dtos.MinimalUserDTO;
import SuMoC.backend.user.enums.FriendShipStatus;
import SuMoC.backend.user.mapper.UserMapper;
import SuMoC.backend.user.models.User;
import SuMoC.backend.user.repository.UserRepository;
@@ -28,12 +33,15 @@ import org.springframework.context.annotation.Profile;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import static SuMoC.backend.trend.enums.StatAttribute.MOBILITY_SCORE_PER_KM;
@RestController
@RequestMapping("/dev")
@Profile("dev")
@@ -86,9 +94,9 @@ public class DevController {
statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(day3WeeksAgo);
}
@GetMapping("/test-firebase-trend-notification/{fcm_token}")
@Operation(description = "Immediately sends a test notification of type TREND to the provided FCM token.")
public ResponseEntity<String> SendTestTrendNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
@GetMapping("/test-firebase-trend-notification-car-km/{fcm_token}")
@Operation(description = "Immediately sends a test notification of type TREND for CAR KM to the provided FCM token.")
public ResponseEntity<String> SendTestTrendNotificationCarKmFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
if (firebaseMessaging == null) {
return ResponseEntity.status(503)
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
@@ -110,6 +118,60 @@ public class DevController {
}
}
@GetMapping("/test-firebase-trend-notification-mobilityscore-per-km/{fcm_token}")
@Operation(description = "Immediately sends a test notification of type TREND for MOBILITY_SCORE_PER_KM to the provided FCM token.")
public ResponseEntity<String> SendTestTrendNotificationMobilityScoreFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
if (firebaseMessaging == null) {
return ResponseEntity.status(503)
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
}
try {
Notification notification = new Notification();
notification.setType(NotificationType.TREND);
TrendDetectionDTO dto = TrendDetectionDTO.mockTrendDetectionDTO();
dto.setDeltaType(DeltaType.PERCENTAGE);
dto.setAttribute(MOBILITY_SCORE_PER_KM);
notification.setData(objectMapper.writeValueAsString(dto));
Message mockTrendMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
// Send to a topic (no device registration needed)
String message = firebaseMessaging.sendAsync(
mockTrendMessage
).get();
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
} catch (Exception e) {
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
}
}
@GetMapping("/test-firebase-trend-notification-walk-bike-km/{fcm_token}")
@Operation(description = "Immediately sends a test notification of type TREND for WALKING_AND_CYCLING_DISTANCE to the provided FCM token.")
public ResponseEntity<String> SendTestTrendNotificationWalkBikeKmFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
if (firebaseMessaging == null) {
return ResponseEntity.status(503)
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
}
try {
Notification notification = new Notification();
notification.setType(NotificationType.TREND);
TrendDetectionDTO dto = TrendDetectionDTO.mockTrendDetectionDTO();
dto.setDeltaType(DeltaType.PERCENTAGE);
dto.setAttribute(StatAttribute.WALKING_AND_CYLING_DISTANCE);
notification.setData(objectMapper.writeValueAsString(dto));
Message mockTrendMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
// Send to a topic (no device registration needed)
String message = firebaseMessaging.sendAsync(
mockTrendMessage
).get();
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
} catch (Exception e) {
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
}
}
@GetMapping("/test-firebase-adhoc-route-notification/{fcm_token}")
@Operation(description = "Immediately sends a test notification of type ADHOC_ALTERNATIVE to the provided FCM token.")
public ResponseEntity<String> SendTestAdhocRouteNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
@@ -158,6 +220,37 @@ public class DevController {
}
}
@GetMapping("/test-firebase-friendship-request-notification/{fcm_token}")
@Operation(description = "Immediately sends a test notification of type FRIENDSHIP_REQUEST_RECEIVED to the provided FCM token.")
public ResponseEntity<String> SendTestRFriendshipRequestReceivedNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
if (firebaseMessaging == null) {
return ResponseEntity.status(503)
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
}
try {
Notification notification = new Notification();
notification.setType(NotificationType.FRIENDSHIP_REQUEST_RECEIVED);
FriendshipDTO friendshipDTO = new FriendshipDTO(
1L,
2L,
new MinimalUserDTO(
2L,
"request_public_name"
),
FriendShipStatus.PENDING,
Instant.now()
);
notification.setData(objectMapper.writeValueAsString(friendshipDTO));
Message mockRegularTripMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
String message = firebaseMessaging.sendAsync(
mockRegularTripMessage
).get();
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
} catch (Exception e) {
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
}
}
@GetMapping("/test-notification-from-detected-regular-trip")
@Operation(description = "Testing endpoint that mocks the detection of regular trips and then tests the alternative calculation and notification scheduling.")
public ResponseEntity<String> testNotificationFromDetectedRegularTrip() {
@@ -251,4 +344,9 @@ public class DevController {
}
}
@PostMapping("/test-detection-and-notification-regular-trips")
public void testDetectionAndNotificationOfRegularTrips() {
regularTripSuggestionService.detectAndNotifyRegularTripsForTodaysDayOfWeek();
}
}
@@ -0,0 +1,49 @@
# Notification System Overview
This document provides an overview of the notification system for client developers integrating with the backend. It
explains notification types, expected payloads, and device token registration.
## Notification Types
Notifications sent to clients are categorized by `NotificationType`:
- **TREND**: Informs users about changes in their mobility trends (e.g., reduced car usage). See
`TrendNotificationService`.
- **ADHOC_ALTERNATIVE**: Suggests a more sustainable alternative after a recent trip upload. See
`AdHocSuggestionService`.
- **REGULAR_TRIP_ALTERNATIVE**: Suggests an alternative for a detected regular trip (e.g., weekly commute). See
`RegularTripSuggestionService`.
- **FRIENDSHIP_REQUEST_RECEIVED**: Notifies about a new pending friendship request.
See `NotificationType.java` for the full enum.
## Notification Payloads
Each notification type includes a data payload. The main DTOs in the notification body are:
- **TREND**: Contains a list of `TrendDetectionDTO` objects, each describing a detected trend for the user. The
structure includes fields such as `userId`, `timespan`, `type`, `attribute`, `deltaType`, `changeValue`, and
`trendConnotation`. See `TrendDetectionDTO.java` for details.
- **ADHOC_ALTERNATIVE**: Contains a list of `RouteDTO` objects representing the best alternative(s) for a recent trip (
see `AdHocSuggestionService`).
- **REGULAR_TRIP_ALTERNATIVE**: Contains a list of 1 or 2 `RouteDTO` objects for the best alternative(s) to a detected
regular trip, depending on user preferences (e.g., if `preferPhysicalActivity` is set, two alternatives may be
included). See `RegularTripSuggestionService` and `RegularTripDetectionService` for details.
- **FRIENDSHIP_REQUEST_RECEIVED**: Contains a `friendshipDTO` where `friend` is the user who sent the request. See
`FriendshipDTO.java`.
## Device Token Registration
To receive push notifications, clients must register their device token. Token registration is handled in the
`NotificationController`. The backend stores or updates the token for the authenticated user.
---
## For Backend Developers
To queue notifications for users, use the `NotificationSchedulerService` as the main entry point. This service provides
methods to schedule notifications with the appropriate type and payload. See `NotificationSchedulerService.java` for
usage details.
---
For further details, refer to the respective service and DTO classes in the codebase.
@@ -16,5 +16,9 @@ public enum NotificationType {
* An alternative suggestion that refers to a detected regular trip.
* E.g. user drives by car every monday at 8 am and there is a sustainable alternative.
*/
REGULAR_TRIP_ALTERNATIVE
REGULAR_TRIP_ALTERNATIVE,
/**
* A notification informing the user about a new pending friendship request.
*/
FRIENDSHIP_REQUEST_RECEIVED,
}
@@ -15,6 +15,10 @@ import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
/**
* This service is the main entry point to schedule notifications to be sent to a users' mobile device.
* It creates Notification entities in the database with status PENDING which are then later processed by the notification worker.
*/
@Service
@RequiredArgsConstructor
public class NotificationSchedulerService {
@@ -25,6 +29,14 @@ public class NotificationSchedulerService {
private final EntityManager entityManager;
/**
* Can be used to schedule multiple notifications at once. Notifieable interface allows sending to multiple users.
* dataBodies need to be serializable to JSON.
*
* @param dataBodies
* @param notificationType
* @param earliestTimeOfDayToSend
*/
public void scheduleAll(List<Notifieable> dataBodies,
NotificationType notificationType,
LocalTime earliestTimeOfDayToSend
@@ -53,11 +65,20 @@ public class NotificationSchedulerService {
notificationRepository.saveAll(notifications);
}
/**
* Schedules a notification to be sent to the specified user.
* Data body needs to be serializable to JSON.
*
* @param userId
* @param dataBody
* @param notificationType
* @param earliestTimeOfDayToSend TOD from which on the notification can be sent. If null, send as soon as possible.
*/
public void schedule(
Long userId,
Object dataBody,
NotificationType notificationType,
LocalTime earliestTimeOfDayToSend
NotificationType notificationType,
LocalTime earliestTimeOfDayToSend
) {
String dataBodyJson;
try {
@@ -66,6 +87,10 @@ public class NotificationSchedulerService {
throw new RuntimeException("Failed to serialize notification data body", e);
}
if (earliestTimeOfDayToSend == null) {
earliestTimeOfDayToSend = LocalTime.now();
}
User userProxy = entityManager.getReference(User.class, userId);
Notification notification = Notification.builder()
@@ -7,6 +7,7 @@ import SuMoC.backend.trip.Modality;
import SuMoC.backend.trip.TripMapper;
import SuMoC.backend.trip.TripRepository;
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.time.DayOfWeek;
@@ -16,15 +17,16 @@ import java.util.HashMap;
import java.util.List;
@Service
@RequiredArgsConstructor
public class RegularTripDetectionService {
RegularTripDetectionProperties properties;
private final RegularTripDetectionProperties properties;
TripRepository tripRepository;
private final TripRepository tripRepository;
TripMapper tripMapper;
private final TripMapper tripMapper;
Detector tripDetector;
private final Detector tripDetector;
/**
* Detects regular trips for the current day of the week for all users based on saved trip data and RegularTripDetectionProperties.
@@ -2,8 +2,9 @@ package SuMoC.backend.routing.controller;
import SuMoC.backend.routing.dtos.RouteDTO;
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
import SuMoC.backend.routing.services.AlternativeRoutingService;
import SuMoC.backend.routing.services.RoutingPreferencesService;
import SuMoC.backend.routing.services.RoutingService;
import SuMoC.backend.user.service.CurrentUserService;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
@@ -21,24 +22,27 @@ import java.util.logging.Logger;
@RestController
@RequestMapping("/routing/alternative")
@RequiredArgsConstructor
public class RoutingController {
class RoutingAlternativeController {
private final Logger logger = Logger.getLogger(RoutingController.class.getName());
private final Logger logger = Logger.getLogger(RoutingAlternativeController.class.getName());
private final RoutingService routingService;
private final AlternativeRoutingService alternativeRoutingService;
private final RoutingPreferencesService routingPreferencesService;
private final CurrentUserService currentUserService;
@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) {
// This automatically uses default preferences for unauthenticated users
routingAlternativeRequestDTO.setRoutingPreferencesDTO(routingPreferencesService.getRoutingPreferencesForCurrentUser());
}
var routeDTOs = routingService.determineAlternativeRoutesOnUserRequest(routingAlternativeRequestDTO);
var routeDTOs = alternativeRoutingService.determineAlternativeRoutesOnUserRequest(routingAlternativeRequestDTO);
return ResponseEntity.ok(routeDTOs);
} catch (WebClientRequestException e) {
// nominatim container is not up yet, we return mock
@@ -0,0 +1,54 @@
package SuMoC.backend.routing.controller;
import SuMoC.backend.routing.dtos.RouteDTO;
import SuMoC.backend.routing.dtos.RoutingDirectionsRequestDTO;
import SuMoC.backend.routing.services.DirectionsRoutingService;
import SuMoC.backend.routing.services.RoutingPreferencesService;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/routing/directions")
@RequiredArgsConstructor
class RoutingDirectionsController {
private final DirectionsRoutingService directionsRoutingService;
private final RoutingPreferencesService routingPreferencesService;
@PostMapping("/request")
@Schema(description = "Endpoint to request routes from point A to B, also see RoutingDirectionsRequestDTO.")
public ResponseEntity<List<RouteDTO>> requestDirections(@Valid @RequestBody RoutingDirectionsRequestDTO directionsRequestDTO) {
validateRequestDTO(directionsRequestDTO);
// if routing preferences are not provided, get stored preferences or default
if (directionsRequestDTO.getRoutingPreferencesDTO() == null) {
directionsRequestDTO.setRoutingPreferencesDTO(routingPreferencesService.getRoutingPreferencesForCurrentUser());
}
return ResponseEntity.ok(directionsRoutingService.getDirections(directionsRequestDTO));
}
private void validateRequestDTO(RoutingDirectionsRequestDTO requestDTO) {
if (requestDTO.getArrivalTime() == null && requestDTO.getDepartureTime() == null) {
throw new IllegalArgumentException("Either arrivalTime or departureTime must be provided.");
}
if (requestDTO.getArrivalTime() != null && requestDTO.getDepartureTime() != null) {
throw new IllegalArgumentException("Only one of arrivalTime or departureTime should be provided.");
}
if (requestDTO.getOriginAddress() == null && (requestDTO.getOriginLat() == 0.0 || requestDTO.getOriginLon() == 0.0)) {
throw new IllegalArgumentException("Origin must be specified either by address or coordinates.");
}
if (requestDTO.getDestinationAddress() == null && (requestDTO.getDestinationLat() == 0.0 || requestDTO.getDestinationLon() == 0.0)) {
throw new IllegalArgumentException("Destination must be specified either by address or coordinates.");
}
}
}
@@ -46,10 +46,25 @@ public class RouteDTO {
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.")
@Schema(description = "The temporal difference in minutes compared to the original route (in case alternative was requested) / the car route (when simply directions requested) .")
private 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) {
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;
@@ -114,17 +129,18 @@ public class RouteDTO {
);
dto.steps.add(new StepDTO(
Modality.WALKING,
null,
400f
));
dto.steps.add(new StepDTO(
dto.steps.add(new TransitStepDTO(
Modality.TRAM,
5000f,
"106",
5000f
"Ich bin eine Testlinie",
"Ich bin ein Teststartbahnhof",
"Ich bin ein Testendbahnhof"
));
dto.steps.add(new StepDTO(
Modality.WALKING,
null,
300f
));
return dto;
@@ -1,5 +1,6 @@
package SuMoC.backend.routing.dtos;
import SuMoC.backend.carta.DirectionsRequest;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.annotation.Nullable;
import jakarta.validation.constraints.NotNull;
@@ -13,7 +14,7 @@ import java.time.Instant;
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "This DTO represents a request for alternative routes between an origin and a destination.")
public class RoutingAlternativeRequestDTO {
public class RoutingAlternativeRequestDTO implements DirectionsRequest {
@NotNull
private Double originLat;
@NotNull
@@ -0,0 +1,27 @@
package SuMoC.backend.routing.dtos;
import SuMoC.backend.carta.DirectionsRequest;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.annotation.Nullable;
import lombok.Getter;
import lombok.Setter;
import java.time.Instant;
@Getter
@Setter
@Schema(description = "DTO representing a request for routing directions between two points. Points can be specified either by coordinates or addresses." +
"If both provided, coordinates are preferred.")
public class RoutingDirectionsRequestDTO implements DirectionsRequest {
private Double originLat;
private Double originLon;
private Double destinationLat;
private Double destinationLon;
private String originAddress;
private String destinationAddress;
private Instant arrivalTime;
private Instant departureTime;
@Nullable
@Schema(description = "Routing preferences to customize the routing behavior. If null, will search for stored user preferences, if not found, use default.")
private RoutingPreferencesDTO routingPreferencesDTO;
}
@@ -12,7 +12,9 @@ import java.util.List;
@Setter
@Schema(description = "This DTO represents the user preferences for routing / alternative route suggestions.")
public class RoutingPreferencesDTO {
@Schema(description = "Whether to prefer alternative routes that involve physical activity (walking, cycling) when suggestin alternative routes.")
private boolean preferPhysicalActivity = false;
@Schema(description = "Whether to consider current weather conditions when suggesting alternative routes.")
private boolean considerWeatherConditions = true;
private List<Modality> modalitiesToConsider = new ArrayList<>(
List.of(Modality.WALKING, Modality.BICYCLE, Modality.ESCOOTER, Modality.BUS, Modality.TRAM, Modality.TRAIN)
@@ -14,6 +14,5 @@ import lombok.Setter;
@Schema(description = "A single step within a suggested alternative route.")
public class StepDTO {
private Modality modality;
private String lineNumber;
private double distanceMeters;
}
@@ -0,0 +1,24 @@
package SuMoC.backend.routing.dtos;
import SuMoC.backend.trip.Modality;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Schema(description = "A single transit step within a suggested alternative route.")
public class TransitStepDTO extends StepDTO {
private String lineNumber;
private String lineHeadsign;
private String startStop;
private String endStop;
public TransitStepDTO(Modality modality, double distanceMeters, String lineNumber, String lineHeadsign, String startStop, String endStop) {
super(modality, distanceMeters);
this.lineNumber = lineNumber;
this.lineHeadsign = lineHeadsign;
this.startStop = startStop;
this.endStop = endStop;
}
}
@@ -0,0 +1,89 @@
package SuMoC.backend.routing.services;
import SuMoC.backend.carta.DirectionsService;
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 lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Service to determine alternative routes for a given routing request.
*/
@Service
@RequiredArgsConstructor
public class AlternativeRoutingService {
private final AlternativeFilterService alternativeFilterService;
private final OnCallRoutingProperties onCallRoutingProperties;
private final AdHocRoutingProperties adHocRoutingProperties;
private final DirectionsService directionsService;
/**
* 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 = directionsService.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 = directionsService.getPossibleAlternativeRoutes(requestDTO);
routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, adHocRoutingProperties);
if (requestDTO.getRoutingPreferencesDTO().isConsiderWeatherConditions()) {
routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties);
}
return routes;
}
public RouteDTO determineBestAlternativeRouteForRegularTrip(RoutingAlternativeRequestDTO requestDTO) {
assert requestDTO.getRoutingPreferencesDTO() != null;
// TODO for now we use adHocRoutingProperties here, in the future we might want to have separate properties for regular trip alternatives
List<RouteDTO> routes = directionsService.getPossibleAlternativeRoutes(requestDTO);
routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, adHocRoutingProperties);
if (requestDTO.getRoutingPreferencesDTO().isConsiderWeatherConditions()) {
routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties);
}
RouteDTO bestRoute = null;
// if users wants physical activity, we pick the fastest physical activity route, if any
if (requestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity()) {
bestRoute = routes.stream()
.filter(RouteDTO::isPhysicalActivity)
.min((r1, r2) -> Long.compare(
r1.getDurationSeconds(),
r2.getDurationSeconds()
)).orElse(null);
if (bestRoute != null) {
return bestRoute;
}
}
// else we pick the fastest route overall
bestRoute = routes.stream()
.min((r1, r2) -> Long.compare(
r1.getDurationSeconds(),
r2.getDurationSeconds()
)).orElse(null);
return bestRoute;
}
}
@@ -1,6 +1,7 @@
package SuMoC.backend.routing.services;
import SuMoC.backend.routing.dtos.StepDTO;
import SuMoC.backend.routing.dtos.TransitStepDTO;
import SuMoC.backend.trip.Modality;
import sumoc.backend.carta.client.model.Route;
import sumoc.backend.carta.client.model.Step;
@@ -28,7 +29,7 @@ public class CartaTransitRouteProcessor {
/**
* Extracts information from the route.
*/
public void process() {
private void process() {
ArrayList<StepDTO> steps = new ArrayList<>();
assert cartaRoute.getSteps() != null;
@@ -46,11 +47,21 @@ public class CartaTransitRouteProcessor {
? 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()
));
if (step.getType().equals("TransitStep")) {
steps.add(new TransitStepDTO(
stepModality,
step.getDistance(),
step.getLine().getCode(),
step.getLine().getHeadsign(),
step.getStops().getFirst().getName(),
step.getStops().getLast().getName()
));
} else {
steps.add(new StepDTO(
stepModality,
step.getDistance()
));
}
}
this.steps = steps;
@@ -0,0 +1,24 @@
package SuMoC.backend.routing.services;
import SuMoC.backend.carta.DirectionsService;
import SuMoC.backend.routing.dtos.RouteDTO;
import SuMoC.backend.routing.dtos.RoutingDirectionsRequestDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Service for getting directions between two given points.
*/
@Service
@RequiredArgsConstructor
public class DirectionsRoutingService {
private final DirectionsService directionsService;
public List<RouteDTO> getDirections(RoutingDirectionsRequestDTO requestDTO) {
// TODO make geocoding call if address is provided instead of coordinates
return directionsService.getPossibleRoutes(requestDTO, true);
}
}
@@ -92,8 +92,9 @@ public class SecurityConfiguration {
auth.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll();
auth.requestMatchers("/dev/**").permitAll();
auth.requestMatchers("/logs").permitAll();
auth.requestMatchers("/routing/alternative/**").permitAll();
auth.requestMatchers("/auth/user/**").permitAll();
auth.requestMatchers("/routing/directions/**").permitAll();
auth.requestMatchers("/routing/alternative/**").permitAll();
auth.requestMatchers("/admin/**").hasRole("ADMIN"); //looks for "ROLE_ADMIN" //alternative: hasAuthoritiy("ADMIN")
auth.requestMatchers("/user/**").hasAnyRole("ADMIN", "USER");
auth.requestMatchers("/friendship/**").hasAnyRole("ADMIN", "USER");
@@ -28,9 +28,18 @@ public class DevTripSeeder implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// Iterate over all users and create 5 random trips for each of the last 5 weeks
// Iterate over all users and create 5 random trips for each of the last 5 weeks + adds car trips for every day at same time
userRepository.findAll().forEach(user -> {
for (int week = 0; week < 5; week++) {
for (int day = 0; day < 7; day++) {
NewTripDTO carTrip = TripFactory.newCarTripDTO(
java.time.Instant.now()
.minus(java.time.Duration.ofDays(week * 7 + day))
);
tripService.addTrip(user, carTrip);
}
// Create 5 trips per week
for (int i = 0; i < 5; i++) {
// Create trips within each week's time range
long daysAgo = week * 7 + (long) (Math.random() * 7);
@@ -6,8 +6,8 @@ import SuMoC.backend.notification.services.NotificationSchedulerService;
import SuMoC.backend.routing.dtos.RouteDTO;
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
import SuMoC.backend.routing.dtos.RoutingPreferencesDTO;
import SuMoC.backend.routing.services.AlternativeRoutingService;
import SuMoC.backend.routing.services.RoutingPreferencesService;
import SuMoC.backend.routing.services.RoutingService;
import SuMoC.backend.suggestion.config.AdHocSuggestionProperties;
import SuMoC.backend.trip.Modality;
import SuMoC.backend.trip.models.Trip;
@@ -23,7 +23,7 @@ import java.util.List;
@RequiredArgsConstructor
public class AdHocSuggestionService {
private final RoutingService routingService;
private final AlternativeRoutingService alternativeRoutingService;
private final RoutingPreferencesService routingPreferencesService;
@@ -42,7 +42,7 @@ public class AdHocSuggestionService {
return; // only suggest alternatives for trips mainly done by car, motorcycle or taxi
}
var viableAlternatives = routingService.determineAlternativeRoutesAdHoc(alternativeRequestFromTrip(newTrip));
var viableAlternatives = alternativeRoutingService.determineAlternativeRoutesAdHoc(alternativeRequestFromTrip(newTrip));
if (!viableAlternatives.isEmpty()) {
// Since notification bodies have a size limit, we only send the best alternative
@@ -7,8 +7,8 @@ import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
import SuMoC.backend.regulartrip.services.RegularTripDetectionService;
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
import SuMoC.backend.routing.dtos.RoutingPreferencesDTO;
import SuMoC.backend.routing.services.AlternativeRoutingService;
import SuMoC.backend.routing.services.RoutingPreferencesService;
import SuMoC.backend.routing.services.RoutingService;
import SuMoC.backend.suggestion.config.RegularTripSuggestionProperties;
import com.uber.h3core.util.LatLng;
import lombok.RequiredArgsConstructor;
@@ -25,7 +25,7 @@ import java.util.List;
@RequiredArgsConstructor
public class RegularTripSuggestionService {
private final RoutingService routingService;
private final AlternativeRoutingService alternativeRoutingService;
private final RoutingPreferencesService routingPreferencesService;
@@ -56,7 +56,7 @@ public class RegularTripSuggestionService {
var alternativeRequest = createAlternativeRequest(detectedRegularTrip);
alternativeRequest.setRoutingPreferencesDTO(preferencesDTO);
var bestAlternative = routingService.determineBestAlternativeRouteForRegularTrip(alternativeRequest);
var bestAlternative = alternativeRoutingService.determineBestAlternativeRouteForRegularTrip(alternativeRequest);
// if present, schedule notification
if (bestAlternative != null) {
notificationSchedulerService.schedule(
@@ -25,5 +25,5 @@ public class TrendProperties {
* Time of day from which on trend notifications might be sent.
* Useful since we dont want to inform about trend changes in the middle of night when calculating jobs might run.
*/
private LocalTime earliestTrendNotificationTimeOfDay = LocalTime.of(12, 0);
private LocalTime earliestTrendNotificationTimeOfDay = LocalTime.of(10, 0);
}
@@ -34,11 +34,15 @@ public class TrendDetectionDTO implements Notifieable {
if (this.type == TrendType.INCREASING) {
return switch (attribute) {
case CAR_DISTANCE -> TrendConnotation.NEGATIVE;
case MOBILITY_SCORE_PER_KM -> TrendConnotation.POSITIVE;
case WALKING_AND_CYLING_DISTANCE -> TrendConnotation.POSITIVE;
default -> TrendConnotation.NEUTRAL;
};
} else if (type == TrendType.DECREASING) {
return switch (attribute) {
case CAR_DISTANCE -> TrendConnotation.POSITIVE;
case MOBILITY_SCORE_PER_KM -> TrendConnotation.NEGATIVE;
case WALKING_AND_CYLING_DISTANCE -> TrendConnotation.NEGATIVE;
default -> TrendConnotation.NEUTRAL;
};
} else {
@@ -5,4 +5,6 @@ package SuMoC.backend.trend.enums;
*/
public enum StatAttribute {
CAR_DISTANCE,
MOBILITY_SCORE_PER_KM,
WALKING_AND_CYLING_DISTANCE
}
@@ -79,9 +79,11 @@ public class WeeklyMobilityStats {
@Column(nullable = false)
private Long sumMetersTaxi = 0L;
public Long getValueFor(StatAttribute attribute) {
public Double getValueFor(StatAttribute attribute) {
return switch (attribute) {
case CAR_DISTANCE -> sumMetersCar;
case MOBILITY_SCORE_PER_KM -> totalDistance == 0 ? 0.0 : (sumMobilityScore * 1000.0) / totalDistance;
case WALKING_AND_CYLING_DISTANCE -> sumMetersWalkingAndCycling.doubleValue();
case CAR_DISTANCE -> sumMetersCar.doubleValue();
};
}
}
@@ -24,7 +24,16 @@ public class TrendDetectorService {
private final TrendProperties trendProperties;
public List<TrendDetectionDTO> detectWeeklyTrends(Integer year, Integer weekNumber, StatAttribute attribute) {
/**
* Detect weekly trends for the given year, week number, attribute, and delta type.
*
* @param year Specified year
* @param weekNumber Specified week number
* @param attribute The attribute to analyze
* @param deltaType The type of delta reported in the detected trend, detection is always based on percentage change.
* @return List of detected trends
*/
public List<TrendDetectionDTO> detectWeeklyTrends(Integer year, Integer weekNumber, StatAttribute attribute, DeltaType deltaType) {
// Fetch stats for current and previous week
List<WeeklyMobilityStats> previousWeekStatsList;
if (weekNumber > 1) {
@@ -55,24 +64,29 @@ public class TrendDetectorService {
if (previousValue != 0) {
double percentageChange = ((currentValue - previousValue) / previousValue) * 100.0;
double absoluteChange = currentValue - previousValue;
if (percentageChange >= trendProperties.getPositiveThreshold()) {
var changeValue = deltaType == DeltaType.PERCENTAGE ? percentageChange : absoluteChange;
detectedTrends.add(new TrendDetectionDTO(
currentStats.getUser().getId(),
TrendTimespan.WEEKLY,
TrendType.INCREASING,
StatAttribute.CAR_DISTANCE,
DeltaType.PERCENTAGE,
percentageChange
attribute,
deltaType,
changeValue
));
} else if (percentageChange <= trendProperties.getNegativeThreshold()) {
var changeValue = deltaType == DeltaType.PERCENTAGE ? percentageChange : absoluteChange;
detectedTrends.add(new TrendDetectionDTO(
previousStats.getUser().getId(),
TrendTimespan.WEEKLY,
TrendType.DECREASING,
StatAttribute.CAR_DISTANCE,
DeltaType.PERCENTAGE,
percentageChange
attribute,
deltaType,
changeValue
));
}
}
@@ -3,6 +3,7 @@ package SuMoC.backend.trend.services;
import SuMoC.backend.notification.enums.NotificationType;
import SuMoC.backend.notification.services.NotificationSchedulerService;
import SuMoC.backend.trend.config.TrendProperties;
import SuMoC.backend.trend.enums.DeltaType;
import SuMoC.backend.trend.enums.StatAttribute;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@@ -23,9 +24,14 @@ public class TrendNotificationService {
* Detects trends for the given year and week number and sends notifications to users.
*/
public void detectAndNotifyTrends(int year, int weekNumber) {
// TODO for now we only consider CAR_DISTANCE, but this can be extended later
var detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE);
var detectedCarKmTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE, DeltaType.PERCENTAGE);
var detectedWalkBikeKmTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.WALKING_AND_CYLING_DISTANCE, DeltaType.PERCENTAGE);
var detectedMobilityScorePerKmTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.MOBILITY_SCORE_PER_KM, DeltaType.PERCENTAGE);
// we create a new list so the java type system is happy
notificationSchedulerService.scheduleAll(new ArrayList<>(detectedTrends), NotificationType.TREND, trendProperties.getEarliestTrendNotificationTimeOfDay());
// We space out the notifications in case a user has multiple trends detected - this should be improved if we add more trend types
notificationSchedulerService.scheduleAll(new ArrayList<>(detectedCarKmTrends), NotificationType.TREND, trendProperties.getEarliestTrendNotificationTimeOfDay());
notificationSchedulerService.scheduleAll(new ArrayList<>(detectedWalkBikeKmTrends), NotificationType.TREND, trendProperties.getEarliestTrendNotificationTimeOfDay().plusHours(2));
notificationSchedulerService.scheduleAll(new ArrayList<>(detectedMobilityScorePerKmTrends), NotificationType.TREND, trendProperties.getEarliestTrendNotificationTimeOfDay().plusHours(4));
}
}
@@ -23,6 +23,33 @@ public class TripFactory {
return modalities[ThreadLocalRandom.current().nextInt(modalities.length)];
}
public static NewTripDTO newCarTripDTO(Instant startTime) {
String startPlace = "Cologne";
String endPlace = "Düsseldorf";
Set<NewTripSegmentDTO> segments = Set.of(
NewTripSegmentDTO.builder()
.modality(Modality.CAR)
.startTime(startTime)
.distanceMeters(50000)
.build()
);
return NewTripDTO.builder()
.startPlace(startPlace)
.endPlace(endPlace)
.startLatitude(51.4617108)
.startLongitude(7.0170745)
.endLatitude(51.2277411)
.endLongitude(6.7734556)
.co2Emissions(120.0)
.startTime(startTime)
.endTime(startTime.plus(Duration.ofMinutes(45)))
.mobilityScore(75.0f)
.tripSegments(segments)
.build();
}
/**
* Generates a random NewTripDTO that always consists of two random segments that start at the given startTime,
* take 2 hours in total, and have random start and end places from a predefined list of NRW cities.
@@ -32,12 +32,15 @@ public interface TripRepository extends JpaRepository<Trip, Long> {
DayOfWeekConverter converter = new DayOfWeekConverter();
return findAllValidFromDateWithMainModalityOnCertainWeekdayInt(
fromDate,
modality,
modality.toString(),
converter.convertToDatabaseColumn(dayOfWeek)
);
}
@Query("SELECT t FROM Trip t WHERE t.invalidated = false AND t.startTime >= :fromDate AND t.mainModality = :modality AND FUNCTION('day_of_week', t.startTime) = :dayOfWeek")
List<Trip> findAllValidFromDateWithMainModalityOnCertainWeekdayInt(Instant fromDate, Modality modality, int dayOfWeek);
@Query(
value = "SELECT * FROM trips t WHERE t.invalidated = false AND t.start_time >= :fromDate AND t.main_modality = :modality AND EXTRACT(DOW from t.start_time) = :dayOfWeek",
nativeQuery = true
)
List<Trip> findAllValidFromDateWithMainModalityOnCertainWeekdayInt(Instant fromDate, String modality, int dayOfWeek);
}
@@ -6,13 +6,10 @@ import SuMoC.backend.user.models.User;
import SuMoC.backend.user.repository.UserRepository;
import SuMoC.backend.user.service.CurrentUserService;
import SuMoC.backend.user.service.FriendshipService;
import SuMoC.backend.user.service.PrivacyService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@@ -23,18 +20,13 @@ import java.util.concurrent.TimeUnit;
public class FriendshipController {
private final UserRepository userRepository;
private final FriendshipService friendshipService;
private final CurrentUserService currentUser;
private final CurrentUserService currentUserService;
@Autowired
public FriendshipController(UserRepository userRepository, FriendshipService friendshipService, CurrentUserService currentUser) {
public FriendshipController(UserRepository userRepository, FriendshipService friendshipService, CurrentUserService currentUserService) {
this.userRepository = userRepository;
this.friendshipService = friendshipService;
this.currentUser = currentUser;
}
// TODO extend security context with user id to avoid unnecessary db query
private User getAuthenticatedUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return userRepository.findByEmail(authentication.getName()).get();
this.currentUserService = currentUserService;
}
@Operation(summary = "Return all friendships of the logged in user.",
@@ -51,7 +43,7 @@ public class FriendshipController {
""")
@GetMapping("/all")
public ResponseEntity<List<FriendshipDTO>> getFriendships() {
User user = currentUser.get();
User user = currentUserService.get();
List<FriendshipDTO> friendships = friendshipService.getFriendships(user.getId());
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
@@ -61,7 +53,7 @@ public class FriendshipController {
@Operation(summary = "Return all accepted friends of the logged in user.", description = "Returns all friends with accepted status.")
@GetMapping("/accepted")
public ResponseEntity<List<FriendshipDTO>> getAcceptedFriendships() {
User user = currentUser.get();
User user = currentUserService.get();
List<FriendshipDTO> friendships = friendshipService.getAcceptedFriendships(user.getId());
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
@@ -71,7 +63,7 @@ public class FriendshipController {
@Operation(summary = "Request a friendship with another user.", description = "Sends a friendship request to another user from the logged in user.")
@PostMapping("/request/{friendId}")
public ResponseEntity<Void> requestFriendship(@PathVariable Long friendId) {
User user = getAuthenticatedUser();
User user = currentUserService.get();
checkSelfAction(user.getId(), friendId);
friendshipService.requestFriendship(user, friendId);
return ResponseEntity.ok().build();
@@ -80,7 +72,7 @@ public class FriendshipController {
@Operation(summary = "Request a friendship with another user by friend code.", description = "Sends a friendship request to another user identified by their friend code from the logged in user.")
@PostMapping("/request/by-friendcode/{friendCode}")
public ResponseEntity<Void> requestFriendshipByFriendcode(@PathVariable String friendCode) {
User user = getAuthenticatedUser();
User user = currentUserService.get();
User requestedFriend = userRepository.findByFriendCode(friendCode).orElseThrow();
checkSelfAction(user.getId(), requestedFriend.getId());
friendshipService.requestFriendship(user, requestedFriend.getId());
@@ -90,7 +82,7 @@ public class FriendshipController {
@Operation(summary = "Accept a friendship request.", description = "Accepts a pending friendship request for the logged in user from user with friendId.")
@PostMapping("/accept/{friendId}")
public ResponseEntity<Void> acceptFriendship(@PathVariable Long friendId) {
User user = getAuthenticatedUser();
User user = currentUserService.get();
friendshipService.acceptFriendship(user, friendId);
return ResponseEntity.ok().build();
}
@@ -98,7 +90,7 @@ public class FriendshipController {
@Operation(summary = "Reject a friendship request.", description = "Rejects a pending friendship request for the logged in user from user with friendId.")
@PostMapping("/reject/{friendId}")
public ResponseEntity<Void> rejectFriendship(@PathVariable Long friendId) {
User user = getAuthenticatedUser();
User user = currentUserService.get();
friendshipService.rejectFriendship(user, friendId);
return ResponseEntity.ok().build();
}
@@ -106,7 +98,7 @@ public class FriendshipController {
@Operation(summary = "Unfriend a user.", description = "Removes an accepted friendship between the logged in user and user with friendId.")
@DeleteMapping("/unfriend/{friendId}")
public ResponseEntity<Void> unfriend(@PathVariable Long friendId) {
User user = getAuthenticatedUser();
User user = currentUserService.get();
friendshipService.unfriend(user, friendId);
return ResponseEntity.ok().build();
}
@@ -114,7 +106,7 @@ public class FriendshipController {
@Operation(summary = "Block a user.", description = "Blocks the user with friendId for the logged in user.")
@PostMapping("/block/{friendId}")
public ResponseEntity<Void> blockUser(@PathVariable Long friendId) {
User user = getAuthenticatedUser();
User user = currentUserService.get();
checkSelfAction(user.getId(), friendId);
friendshipService.blockUser(user, friendId);
return ResponseEntity.ok().build();
@@ -123,7 +115,7 @@ public class FriendshipController {
@Operation(summary = "Unblock a user.", description = "Unblocks the user with friendId for the logged in user.")
@PostMapping("/unblock/{friendId}")
public ResponseEntity<Void> unblockUser(@PathVariable Long friendId) {
User user = getAuthenticatedUser();
User user = currentUserService.get();
friendshipService.unblockUser(user, friendId);
return ResponseEntity.ok().build();
}
@@ -131,7 +123,7 @@ public class FriendshipController {
@Operation(summary = "Get all users the logged in user has blocked.", description = "Returns a list of all users that have been blocked by the logged in user.")
@GetMapping("/blocked")
public ResponseEntity<List<MinimalUserDTO>> blockedUsers() {
User user = currentUser.get();
User user = currentUserService.get();
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
.body(friendshipService.getBlockedUsers(user.getId()));
@@ -1,12 +1,10 @@
package SuMoC.backend.user.controller;
import SuMoC.backend.security.dtos.LoginResponseDTO;
import SuMoC.backend.user.dtos.AddStatRequestDTO;
import SuMoC.backend.user.dtos.MaximalUserDTO;
import SuMoC.backend.user.dtos.MinimalUserDTO;
import SuMoC.backend.user.dtos.StatScope;
import SuMoC.backend.user.dtos.*;
import SuMoC.backend.user.enums.VisibilityPrivacy;
import SuMoC.backend.user.service.UserService;
import SuMoC.backend.user.stats.StatsList;
import SuMoC.backend.user.stats.StatsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
@@ -24,7 +22,6 @@ import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.TimeUnit;
@Validated
@@ -186,7 +183,20 @@ public class UserController {
return ResponseEntity.ok().build();
}
@Operation(summary = "get stats of current user",
description = "Returns all stats of a user")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Stats were found",
content = @Content(mediaType = "application/json")),
@ApiResponse(responseCode = "403", description = "Not authorized",
content = @Content(mediaType = "application/json"))
})
@RolesAllowed({"USER", "ADMIN"})
@GetMapping("/stats")
public ResponseEntity<StatsList> getStats() {
StatsList stats = this.statsService.getStats();
return ResponseEntity.ok().body(stats);
}
@Operation(summary = "Add a profile Picture to the user.", description = "A user can add or update a profile picture to be displayed on his profile.")
@@ -1,6 +1,8 @@
package SuMoC.backend.user.dtos;
import SuMoC.backend.user.enums.FriendShipStatus;
import lombok.Getter;
import lombok.Setter;
import java.time.Instant;
@@ -11,6 +13,8 @@ import java.time.Instant;
* The MinimalUserDTO of the friend represents the friend depending on the relationship.
* So only if friendship is accepted the private name of the friend is used as displayname.
*/
@Setter
@Getter
public class FriendshipDTO {
private Long friendshipId;
private Long userId;
@@ -29,43 +33,4 @@ public class FriendshipDTO {
this.createdAt = createdAt;
}
public Long getFriendshipId() {
return friendshipId;
}
public void setFriendshipId(Long friendshipId) {
this.friendshipId = friendshipId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public MinimalUserDTO getFriend() {
return friend;
}
public void setFriend(MinimalUserDTO friend) {
this.friend = friend;
}
public FriendShipStatus getStatus() {
return status;
}
public void setStatus(FriendShipStatus status) {
this.status = status;
}
public Instant getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Instant createdAt) {
this.createdAt = createdAt;
}
}
@@ -23,10 +23,20 @@ public class MaximalUserDTO {
private Set<Friendship> friendships;
private String base64ProfilePicture;
public String getFriendCode() {
return friendCode;
}
public void setFriendCode(String friendCode) {
this.friendCode = friendCode;
}
private String friendCode;
public MaximalUserDTO() {
}
public MaximalUserDTO(Long id, String publicName, String privateName, String email, VisibilityPrivacy visibilityPrivacy, Set<Trip> trips, Set<Friendship> friendships, String base64ProfilePicture) {
public MaximalUserDTO(Long id, String publicName, String privateName, String email, VisibilityPrivacy visibilityPrivacy, Set<Trip> trips, Set<Friendship> friendships, String friendCode,String base64ProfilePicture) {
this.id = id;
this.publicName = publicName;
this.privateName = privateName;
@@ -35,6 +45,7 @@ public class MaximalUserDTO {
this.trips = trips;
this.friendships = friendships;
this.base64ProfilePicture = base64ProfilePicture;
this.friendCode = friendCode;
}
@@ -9,14 +9,14 @@ public class UserDTO {
private String privateName;
private String publicName;
private Set<RoleName> roles;
private String friendCode;
public UserDTO(Long userId, String privateName, String publicName, Set<RoleName> roles){
public UserDTO(Long userId, String privateName, String publicName, Set<RoleName> roles, String friendCode) {
this.userId = userId;
this.privateName = privateName;
this.publicName = publicName;
this.roles = roles;
this.friendCode = friendCode;
}
public UserDTO(){}
@@ -57,4 +57,13 @@ public class UserDTO {
public void setPublicName(String publicName) {
this.publicName = publicName;
}
public String getFriendCode() {
return friendCode;
}
public void setFriendCode(String friendCode) {
this.friendCode = friendCode;
}
}
@@ -23,6 +23,7 @@ public interface UserMapper {
user.getVisibilityPrivacy(),
user.getTrips(),
user.getFriendships(),
user.getFriendCode(),
ImageBase64Util.encode(user.getProfileImage().getImageData())
);
return maximalUserDTO;
@@ -33,6 +33,7 @@ public class CurrentUserService {
}
public boolean isAuthenticated() {
// TODO request with auth no auth really result in not authenticated?
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return auth != null && auth.isAuthenticated();
}
@@ -1,5 +1,6 @@
package SuMoC.backend.user.service;
import SuMoC.backend.notification.services.NotificationSchedulerService;
import SuMoC.backend.user.dtos.FriendshipDTO;
import SuMoC.backend.user.dtos.MinimalUserDTO;
import SuMoC.backend.user.enums.FriendShipStatus;
@@ -8,25 +9,22 @@ import SuMoC.backend.user.models.User;
import SuMoC.backend.user.repository.FriendshipRepository;
import SuMoC.backend.user.repository.UserRepository;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.jspecify.annotations.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static SuMoC.backend.notification.enums.NotificationType.FRIENDSHIP_REQUEST_RECEIVED;
@Service
@Transactional
@RequiredArgsConstructor
public class FriendshipService {
private final FriendshipRepository friendshipRepository;
private final UserRepository userRepository;
@Autowired
public FriendshipService(FriendshipRepository friendshipRepository, UserRepository userRepository) {
this.friendshipRepository = friendshipRepository;
this.userRepository = userRepository;
}
private final NotificationSchedulerService notificationSchedulerService;
private static @NonNull MinimalUserDTO getMinimalUserDTOforFriend(Friendship friendship) {
User friend = friendship.getFriend();
@@ -156,6 +154,36 @@ public class FriendshipService {
Friendship reverseFriendship = new Friendship(requestedFriend, sender, FriendShipStatus.PENDING);
friendshipRepository.save(friendship);
friendshipRepository.save(reverseFriendship);
// Send notification to requestedFriend about new friendship request
notifyAboutFriendshipRequest(reverseFriendship, sender, requestedFriend);
}
/**
* Converts pending friendship into a dto and schedules a notification to the requested friend.
* This method should be called with the reverse friendship, so that the client receives the friendshipDto
* with a MinimalUserDTO of the sender.
*/
public void notifyAboutFriendshipRequest(Friendship requestFriendship, User sender, User requestedFriend) {
MinimalUserDTO senderMinimalUserDTO = new MinimalUserDTO(
sender.getId(),
sender.getPrivateName()
);
FriendshipDTO friendshipDTO = new FriendshipDTO(
requestFriendship.getId(),
requestedFriend.getId(),
senderMinimalUserDTO,
requestFriendship.getStatus(),
requestFriendship.getCreatedAt()
);
notificationSchedulerService.schedule(
requestedFriend.getId(),
friendshipDTO,
FRIENDSHIP_REQUEST_RECEIVED,
null
);
}
public void acceptFriendship(User sender, long friendId) {
@@ -272,14 +300,6 @@ public class FriendshipService {
return dtoList;
}
public record NameWithFriendship(
Long id,
String name,
boolean friendship
) {}
public List<NameWithFriendship> getPrivateNameIfFriendshipAccepted(User user, List<Long> otherUserIds) {
List<NameWithFriendship> result = new ArrayList<>();
@@ -323,4 +343,11 @@ public class FriendshipService {
return friends;
}
public record NameWithFriendship(
Long id,
String name,
boolean friendship
) {
}
}
@@ -1,5 +1,6 @@
package SuMoC.backend.user.stats;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.*;
@@ -13,6 +14,7 @@ public class Stats {
@Schema(description = "The StatsList to which these stats belong.", required = true)
@ManyToOne
@JsonIgnore
private StatsList statsList;
@@ -4,6 +4,7 @@ import java.lang.reflect.Field;
import SuMoC.backend.gamification.Timeframe;
import SuMoC.backend.user.models.User;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.*;
import lombok.Getter;
@@ -21,6 +22,7 @@ public class StatsList {
@OneToOne
@MapsId
@JoinColumn(name = "user_id")
@JsonIgnore
private User user;
@Schema(description = "Total stats of the user.")
@@ -90,4 +90,9 @@ public class StatsService {
badgeService.checkAndAwardBadges();
}
}
public StatsList getStats() {
User user = currentUserService.get();
return user.getStats();
}
}
+2 -4
View File
@@ -17,8 +17,8 @@ sumoc.scheduling.notify-weekly-mobility-stats=1 30 0 * * 1
sumoc.scheduling.clean-up-old-notifications=0 0 3 * * *
sumoc.scheduling.notify-regular-route-alternatives=0 0 4 * * *
# Trend detection settings
sumoc.trenddetection.positive-threshold=-25.0
sumoc.trenddetection.negative-threshold=-25.0
sumoc.trenddetection.positive-threshold=10.0
sumoc.trenddetection.negative-threshold=-10.0
# FireBase
firebase.config.enabled=true
firebase.config.service-account=file:./secrets/fcm-key.json
@@ -31,9 +31,7 @@ geocoding.carta.base-url=https://mobydex.locoslab.com/carta
meteo.base-url=https://api.open-meteo.com/v1
# Dev debug settings
sumoc.dev.fcm-key=dmydW4a_RjKCDjcBLZ9Kl8:APA91bFjBIjw8NcjeMIsNkfPuW9jhMlK3n_LHoG5UBW0E_76nTp1yV6jkdiBIvle7Txj_mLY3W9e9gy_op6YWyxJksqZrJFgapruCdBdg9ACYDJAANGTWJk
# RSA key paths (file paths, not directories)
security.rsa.private-key-path=${RSA_PRIVATE_KEY_PATH:${user.home}/.sumoc/keys/jwt-private.pem}
security.rsa.public-key-path=${RSA_PUBLIC_KEY_PATH:${user.home}/.sumoc/keys/jwt-public.pem}
logging.file.name=logs/app.log
@@ -67,7 +67,8 @@ public class UserTestFactory {
user.getId(),
user.getPrivateName(),
user.getPublicName(),
user.getRoles()
user.getRoles(),
user.getFriendCode()
);
}
@@ -0,0 +1,33 @@
package SuMoC.backend.common.converter;
import org.junit.jupiter.api.Test;
import java.time.DayOfWeek;
import static org.junit.jupiter.api.Assertions.assertEquals;
class DayOfWeekConverterTest {
private final DayOfWeekConverter converter = new DayOfWeekConverter();
@Test
void testConvertToDatabaseColumn() {
assertEquals(1, converter.convertToDatabaseColumn(DayOfWeek.MONDAY));
assertEquals(2, converter.convertToDatabaseColumn(DayOfWeek.TUESDAY));
assertEquals(3, converter.convertToDatabaseColumn(DayOfWeek.WEDNESDAY));
assertEquals(4, converter.convertToDatabaseColumn(DayOfWeek.THURSDAY));
assertEquals(5, converter.convertToDatabaseColumn(DayOfWeek.FRIDAY));
assertEquals(6, converter.convertToDatabaseColumn(DayOfWeek.SATURDAY));
assertEquals(0, converter.convertToDatabaseColumn(DayOfWeek.SUNDAY));
}
@Test
void testConvertToEntityAttribute() {
assertEquals(DayOfWeek.MONDAY, converter.convertToEntityAttribute(1));
assertEquals(DayOfWeek.TUESDAY, converter.convertToEntityAttribute(2));
assertEquals(DayOfWeek.WEDNESDAY, converter.convertToEntityAttribute(3));
assertEquals(DayOfWeek.THURSDAY, converter.convertToEntityAttribute(4));
assertEquals(DayOfWeek.FRIDAY, converter.convertToEntityAttribute(5));
assertEquals(DayOfWeek.SATURDAY, converter.convertToEntityAttribute(6));
assertEquals(DayOfWeek.SUNDAY, converter.convertToEntityAttribute(0));
}
}
@@ -50,7 +50,7 @@ public class TrendDetectorServiceTest {
}
@Test
void detectWeeklyTrends_WithSignificantChanges_DetectsTrends() {
void detectWeeklyTrends_WithSignificantChanges_DetectsCarKmTrends() {
// Arrange
int year = 2026;
int weekNumber = 2;
@@ -77,7 +77,7 @@ public class TrendDetectorServiceTest {
.thenReturn(List.of(user1Current, user2Current, user3Current));
// Act
List<TrendDetectionDTO> detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE);
List<TrendDetectionDTO> detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE, DeltaType.PERCENTAGE);
// Assert
assertEquals(2, detectedTrends.size(), "Should detect 2 trends (1 increase, 1 decrease)");
@@ -131,11 +131,143 @@ public class TrendDetectorServiceTest {
// Act & Assert - should not throw any exception
assertDoesNotThrow(() -> {
List<TrendDetectionDTO> detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE);
List<TrendDetectionDTO> detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE, DeltaType.PERCENTAGE);
assertEquals(0, detectedTrends.size(), "Should not detect any trends when matching data is missing");
});
}
@Test
void detectWeeklyTrends_WithSignificantChanges_DetectsMobilityScorePerKmTrends() {
// Arrange
int year = 2026;
int weekNumber = 2;
// Set threshold values for this test
when(trendProperties.getPositiveThreshold()).thenReturn(25.0);
when(trendProperties.getNegativeThreshold()).thenReturn(-25.0);
// User 1: Significant increase in mobility score per km
// Previous: score=50, distance=1000m -> 50/1000 = 0.05 per meter
// Current: score=100, distance=1000m -> 100/1000 = 0.10 per meter (+100%)
WeeklyMobilityStats user1Previous = createWeeklyStatsWithMobilityScore(user1, year, weekNumber - 1, 1000.0, 50.0);
WeeklyMobilityStats user1Current = createWeeklyStatsWithMobilityScore(user1, year, weekNumber, 1000.0, 100.0);
// User 2: Significant decrease in mobility score per km
// Previous: score=100, distance=1000m -> 100/1000 = 0.10 per meter
// Current: score=20, distance=1000m -> 20/1000 = 0.02 per meter (-80%)
WeeklyMobilityStats user2Previous = createWeeklyStatsWithMobilityScore(user2, year, weekNumber - 1, 1000.0, 100.0);
WeeklyMobilityStats user2Current = createWeeklyStatsWithMobilityScore(user2, year, weekNumber, 1000.0, 20.0);
// User 3: No significant change
// Previous: score=50, distance=1000m -> 50/1000 = 0.05 per meter
// Current: score=55, distance=1000m -> 55/1000 = 0.055 per meter (+10%)
WeeklyMobilityStats user3Previous = createWeeklyStatsWithMobilityScore(user3, year, weekNumber - 1, 1000.0, 50.0);
WeeklyMobilityStats user3Current = createWeeklyStatsWithMobilityScore(user3, year, weekNumber, 1000.0, 55.0);
when(weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber - 1))
.thenReturn(List.of(user1Previous, user2Previous, user3Previous));
when(weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber))
.thenReturn(List.of(user1Current, user2Current, user3Current));
// Act
List<TrendDetectionDTO> detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.MOBILITY_SCORE_PER_KM, DeltaType.PERCENTAGE);
// Assert
assertEquals(2, detectedTrends.size(), "Should detect 2 trends (1 increase, 1 decrease)");
// Verify increasing trend for user1
TrendDetectionDTO user1Trend = detectedTrends.stream()
.filter(t -> t.getUserId().equals(user1.getId()))
.findFirst()
.orElse(null);
assertNotNull(user1Trend, "User 1 should have a detected trend");
assertEquals(TrendType.INCREASING, user1Trend.getType());
assertEquals(StatAttribute.MOBILITY_SCORE_PER_KM, user1Trend.getAttribute());
assertEquals(TrendTimespan.WEEKLY, user1Trend.getTimespan());
assertEquals(DeltaType.PERCENTAGE, user1Trend.getDeltaType());
assertEquals(100.0, user1Trend.getChangeValue(), 0.01);
// Verify decreasing trend for user2
TrendDetectionDTO user2Trend = detectedTrends.stream()
.filter(t -> t.getUserId().equals(user2.getId()))
.findFirst()
.orElse(null);
assertNotNull(user2Trend, "User 2 should have a detected trend");
assertEquals(TrendType.DECREASING, user2Trend.getType());
assertEquals(StatAttribute.MOBILITY_SCORE_PER_KM, user2Trend.getAttribute());
assertEquals(TrendTimespan.WEEKLY, user2Trend.getTimespan());
assertEquals(DeltaType.PERCENTAGE, user2Trend.getDeltaType());
assertEquals(-80.0, user2Trend.getChangeValue(), 0.01);
// Verify no trend detected for user3
boolean user3HasTrend = detectedTrends.stream()
.anyMatch(t -> t.getUserId().equals(user3.getId()));
assertFalse(user3HasTrend, "User 3 should not have a detected trend (change below threshold)");
}
@Test
void detectWeeklyTrends_WithSignificantChanges_DetectsWalkingAndCyclingDistanceTrends() {
// Arrange
int year = 2026;
int weekNumber = 2;
// Set threshold values for this test
when(trendProperties.getPositiveThreshold()).thenReturn(25.0);
when(trendProperties.getNegativeThreshold()).thenReturn(-25.0);
// User 1: Significant increase in walking and cycling distance (1000m -> 4000m = +300%)
WeeklyMobilityStats user1Previous = createWeeklyStatsWithWalkingAndCycling(user1, year, weekNumber - 1, 1000L);
WeeklyMobilityStats user1Current = createWeeklyStatsWithWalkingAndCycling(user1, year, weekNumber, 4000L);
// User 2: Significant decrease in walking and cycling distance (5000m -> 1000m = -80%)
WeeklyMobilityStats user2Previous = createWeeklyStatsWithWalkingAndCycling(user2, year, weekNumber - 1, 5000L);
WeeklyMobilityStats user2Current = createWeeklyStatsWithWalkingAndCycling(user2, year, weekNumber, 1000L);
// User 3: No significant change (2000m -> 2200m = +10%)
WeeklyMobilityStats user3Previous = createWeeklyStatsWithWalkingAndCycling(user3, year, weekNumber - 1, 2000L);
WeeklyMobilityStats user3Current = createWeeklyStatsWithWalkingAndCycling(user3, year, weekNumber, 2200L);
when(weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber - 1))
.thenReturn(List.of(user1Previous, user2Previous, user3Previous));
when(weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber))
.thenReturn(List.of(user1Current, user2Current, user3Current));
// Act
List<TrendDetectionDTO> detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.WALKING_AND_CYLING_DISTANCE, DeltaType.PERCENTAGE);
// Assert
assertEquals(2, detectedTrends.size(), "Should detect 2 trends (1 increase, 1 decrease)");
// Verify increasing trend for user1
TrendDetectionDTO user1Trend = detectedTrends.stream()
.filter(t -> t.getUserId().equals(user1.getId()))
.findFirst()
.orElse(null);
assertNotNull(user1Trend, "User 1 should have a detected trend");
assertEquals(TrendType.INCREASING, user1Trend.getType());
assertEquals(StatAttribute.WALKING_AND_CYLING_DISTANCE, user1Trend.getAttribute());
assertEquals(TrendTimespan.WEEKLY, user1Trend.getTimespan());
assertEquals(DeltaType.PERCENTAGE, user1Trend.getDeltaType());
assertEquals(300.0, user1Trend.getChangeValue(), 0.01);
// Verify decreasing trend for user2
TrendDetectionDTO user2Trend = detectedTrends.stream()
.filter(t -> t.getUserId().equals(user2.getId()))
.findFirst()
.orElse(null);
assertNotNull(user2Trend, "User 2 should have a detected trend");
assertEquals(TrendType.DECREASING, user2Trend.getType());
assertEquals(StatAttribute.WALKING_AND_CYLING_DISTANCE, user2Trend.getAttribute());
assertEquals(TrendTimespan.WEEKLY, user2Trend.getTimespan());
assertEquals(DeltaType.PERCENTAGE, user2Trend.getDeltaType());
assertEquals(-80.0, user2Trend.getChangeValue(), 0.01);
// Verify no trend detected for user3
boolean user3HasTrend = detectedTrends.stream()
.anyMatch(t -> t.getUserId().equals(user3.getId()));
assertFalse(user3HasTrend, "User 3 should not have a detected trend (change below threshold)");
}
/**
* Helper method to create WeeklyMobilityStats with specified car distance
*/
@@ -162,4 +294,58 @@ public class TrendDetectorServiceTest {
.sumMetersTaxi(0L)
.build();
}
/**
* Helper method to create WeeklyMobilityStats with specified mobility score and total distance
*/
private WeeklyMobilityStats createWeeklyStatsWithMobilityScore(User user, int year, int weekNumber, Double totalDistance, Double mobilityScore) {
return WeeklyMobilityStats.builder()
.user(user)
.year(year)
.weekNumber(weekNumber)
.totalDistance(totalDistance)
.tripCount(10)
.sumMobilityScore(mobilityScore)
.averageMobilityScore(mobilityScore / 10)
.sumMetersTraveled(totalDistance.longValue())
.sumMetersWalkingAndCycling(0L)
.sumMetersPublicTransport(0L)
.sumMetersWalking(0L)
.sumMetersBicycle(0L)
.sumMetersEscooter(0L)
.sumMetersBus(0L)
.sumMetersTram(0L)
.sumMetersTrain(0L)
.sumMetersCar(0L)
.sumMetersMotorcycle(0L)
.sumMetersTaxi(0L)
.build();
}
/**
* Helper method to create WeeklyMobilityStats with specified walking and cycling distance
*/
private WeeklyMobilityStats createWeeklyStatsWithWalkingAndCycling(User user, int year, int weekNumber, Long walkingAndCyclingDistance) {
return WeeklyMobilityStats.builder()
.user(user)
.year(year)
.weekNumber(weekNumber)
.totalDistance(walkingAndCyclingDistance.doubleValue())
.tripCount(10)
.sumMobilityScore(50.0)
.averageMobilityScore(5.0)
.sumMetersTraveled(walkingAndCyclingDistance)
.sumMetersWalkingAndCycling(walkingAndCyclingDistance)
.sumMetersPublicTransport(0L)
.sumMetersWalking(walkingAndCyclingDistance / 2)
.sumMetersBicycle(walkingAndCyclingDistance / 2)
.sumMetersEscooter(0L)
.sumMetersBus(0L)
.sumMetersTram(0L)
.sumMetersTrain(0L)
.sumMetersCar(0L)
.sumMetersMotorcycle(0L)
.sumMetersTaxi(0L)
.build();
}
}
@@ -1,70 +0,0 @@
package SuMoC.backend.trip;
import SuMoC.backend.Factories.TripTestFactory;
import SuMoC.backend.Factories.UserTestFactory;
import SuMoC.backend.common.converter.DayOfWeekConverter;
import SuMoC.backend.trip.models.Trip;
import SuMoC.backend.user.models.User;
import SuMoC.backend.user.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.TestPropertySource;
import java.time.DayOfWeek;
import java.time.Instant;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
@DataJpaTest
@TestPropertySource(properties = {
"spring.jpa.hibernate.ddl-auto=create-drop",
"spring.datasource.url=jdbc:h2:mem:testdb"
})
public class TripRepositoryTest {
@Autowired
private TripRepository tripRepository;
@Autowired
private UserRepository userRepository;
@Test
void testDayOfWeekConverterAppliedInQuery() {
// Create a user
User user = UserTestFactory.validUser();
userRepository.save(user);
// Create trips on different days of the week
// 2025-01-13 is a Monday
Trip mondayTrip = TripTestFactory.getValidTrip(Instant.parse("2025-01-13T10:00:00Z"), Instant.parse("2025-01-13T11:00:00Z"), user);
tripRepository.save(mondayTrip);
// 2025-01-19 is a Sunday
Trip sundayTrip = TripTestFactory.getValidTrip(Instant.parse("2025-01-19T10:00:00Z"), Instant.parse("2025-01-19T11:00:00Z"), user);
tripRepository.save(sundayTrip);
// Query for trips on Monday
List<Trip> mondayTrips = tripRepository.findAllValidFromDateWithMainModalityOnCertainWeekday(
Instant.parse("2025-01-01T00:00:00Z"),
Modality.CAR,
DayOfWeek.MONDAY
);
// Verify only Monday trip is returned
assertEquals(1, mondayTrips.size());
assertEquals(mondayTrip.getId(), mondayTrips.get(0).getId());
// Query for trips on Sunday
List<Trip> sundayTrips = tripRepository.findAllValidFromDateWithMainModalityOnCertainWeekday(
Instant.parse("2025-01-01T00:00:00Z"),
Modality.CAR,
DayOfWeek.SUNDAY
);
// Verify only Tuesday trip is returned
assertEquals(1, sundayTrips.size());
assertEquals(sundayTrip.getId(), sundayTrips.get(0).getId());
}
}
@@ -5,18 +5,15 @@ import SuMoC.backend.user.models.Friendship;
import SuMoC.backend.user.models.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Profile;
import java.time.Instant;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
@DataJpaTest
@ActiveProfiles("test")
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@SpringBootTest
@Profile("test")
public class FriendshipRepositoryTests {
@Autowired
private FriendshipRepository friendshipRepository;
@@ -1,5 +1,6 @@
package SuMoC.backend.user.service;
import SuMoC.backend.notification.services.NotificationSchedulerService;
import SuMoC.backend.user.enums.FriendShipStatus;
import SuMoC.backend.user.models.Friendship;
import SuMoC.backend.user.models.User;
@@ -20,6 +21,7 @@ import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@@ -31,6 +33,9 @@ public class FriendshipServiceTest {
@Mock
private UserRepository userRepository;
@Mock
private NotificationSchedulerService notificationSchedulerService;
@InjectMocks
private FriendshipService friendshipService;
@@ -69,6 +74,21 @@ public class FriendshipServiceTest {
// Verify one friendship: friend -> sender, PENDING
assertTrue(capturedFriendships.stream()
.anyMatch(f -> f.getUser().equals(friend) && f.getFriend().equals(sender) && f.getStatus().equals(FriendShipStatus.PENDING)));
// Verify notificationSchedulerService.schedule called with correct params
verify(notificationSchedulerService, times(1)).schedule(
eq(friend.getId()),
argThat(arg -> {
// Check FriendshipDTO fields
if (!(arg instanceof SuMoC.backend.user.dtos.FriendshipDTO dto)) return false;
return dto.getUserId().equals(friend.getId()) &&
dto.getFriend().getId().equals(sender.getId()) &&
dto.getFriend().getDisplayName().equals(sender.getPrivateName()) &&
dto.getStatus() == FriendShipStatus.PENDING;
}),
eq(SuMoC.backend.notification.enums.NotificationType.FRIENDSHIP_REQUEST_RECEIVED),
isNull()
);
}
@Test