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
63 changed files with 408 additions and 2639 deletions
+48 -656
View File
File diff suppressed because it is too large Load Diff
@@ -1,20 +0,0 @@
package SuMoC.backend.carrousel.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "sumoc.alternative-carrousel")
public class CarrouselProperties {
/**
* Maximum number of alternative suggestions to show in the carrousel.
*/
private int maxCarrouselItems = 5;
/**
* Time window in days to consider recent suggestions for a user.
*/
private int recentSuggestionWindowDays = 7;
}
@@ -1,30 +0,0 @@
package SuMoC.backend.carrousel.controller;
import SuMoC.backend.carrousel.dto.AlternativeCarrouselDTO;
import SuMoC.backend.carrousel.service.CarrouselService;
import SuMoC.backend.user.service.CurrentUserService;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Controller for providing a carrousel of alternative routes for displaying on the app startpage.
*/
@RestController
@RequestMapping("/routing/alternative/carrousel")
@RequiredArgsConstructor
public class RoutingAlternativeCarrouselController {
private final CarrouselService carrouselService;
private final CurrentUserService currentUserService;
@GetMapping("/request")
@Schema(description = "Provides a carrousel of alternative routes for displaying on the app startpage.")
public ResponseEntity<AlternativeCarrouselDTO> getAlternativeCarrousel() {
return ResponseEntity.ok(carrouselService.getCarrouselForUser(currentUserService.get().getId()));
}
}
@@ -1,21 +0,0 @@
package SuMoC.backend.carrousel.dto;
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
import SuMoC.backend.routing.dtos.RouteDTO;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Schema(description = "Context for the alternative carrousel for a ad-hoc alternative suggestion.")
public class AdHocAlternativeContext extends RouteAlternativeContext {
@Schema(description = "The trip id associated with this alternative route suggestion.")
private Long tripId;
public AdHocAlternativeContext(RouteDTO alternative, Long tripId) {
super(alternative, CarrouselCandidateType.ADHOC_ALTERNATIVE);
this.tripId = tripId;
}
}
@@ -1,16 +0,0 @@
package SuMoC.backend.carrousel.dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
@AllArgsConstructor
public class AlternativeCarrouselDTO {
private List<RouteAlternativeContext> alternatives;
}
@@ -1,26 +0,0 @@
package SuMoC.backend.carrousel.dto;
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
import SuMoC.backend.geocoding.AddressDTO;
import SuMoC.backend.regulartrip.dtos.MinimalDetectedRegularTripDTO;
import SuMoC.backend.routing.dtos.RouteDTO;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
@Getter
public class RegularTripAlternativeContext extends RouteAlternativeContext {
private final MinimalDetectedRegularTripDTO detectedRegularTrip;
@Schema(description = "The address of the departure h3 center cell. Note that this is not necessarily the actual departure location of the user, but suburb etc. should match.")
private final AddressDTO departureCenter;
@Schema(description = "The address of the arrival h3 center cell. Note that this is not necessarily the actual arrival location of the user, but suburb etc. should match.")
private final AddressDTO arrivalCenter;
public RegularTripAlternativeContext(RouteDTO alternative, MinimalDetectedRegularTripDTO detectedRegularTrip, AddressDTO departureCenter, AddressDTO arrivalCenter) {
super(alternative, CarrouselCandidateType.REGULAR_TRIP_ALTERNATIVE);
this.detectedRegularTrip = detectedRegularTrip;
this.departureCenter = departureCenter;
this.arrivalCenter = arrivalCenter;
}
}
@@ -1,24 +0,0 @@
package SuMoC.backend.carrousel.dto;
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
import SuMoC.backend.routing.dtos.RouteDTO;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Schema(description = "Wrapper for alternative routes in the carousel.")
@NoArgsConstructor
public abstract class RouteAlternativeContext {
protected CarrouselCandidateType carrouselCandidateType;
protected RouteDTO alternative;
protected RouteAlternativeContext(RouteDTO alternative, CarrouselCandidateType carrouselCandidateType) {
this.carrouselCandidateType = carrouselCandidateType;
this.alternative = alternative;
}
}
@@ -1,6 +0,0 @@
package SuMoC.backend.carrousel.enums;
public enum CarrouselCandidateType {
ADHOC_ALTERNATIVE,
REGULAR_TRIP_ALTERNATIVE,
}
@@ -1,45 +0,0 @@
package SuMoC.backend.carrousel.models;
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
import SuMoC.backend.regulartrip.dtos.MinimalDetectedRegularTripDTO;
import SuMoC.backend.routing.dtos.RouteDTO;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes;
import java.time.Instant;
/**
* Entity representing a candidate for the alternatives carrousel. We use this to keep track of alternatives we have
* suggested the user via notifications earlier, so that wen can also show them in the carrousel.
*/
@Entity
@Table(name = "carrousel_candidates")
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class CarrouselCandidate {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private CarrouselCandidateType candidateType;
@Column(nullable = false)
private Long userId;
private Long adHocTripId;
@JdbcTypeCode(SqlTypes.JSON)
private MinimalDetectedRegularTripDTO detectedRegularTrip;
@JdbcTypeCode(SqlTypes.JSON)
private RouteDTO suggestedAlternative;
private Instant suggestedAt;
}
@@ -1,20 +0,0 @@
package SuMoC.backend.carrousel.repository;
import SuMoC.backend.carrousel.models.CarrouselCandidate;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.time.Instant;
import java.util.List;
public interface CarrouselCandidateRepository extends JpaRepository<CarrouselCandidate, Long> {
@Query("""
SELECT c
FROM CarrouselCandidate c
WHERE c.userId = :userId
AND c.suggestedAt >= :cutOff
ORDER BY c.suggestedAt DESC
""")
List<CarrouselCandidate> findByUserIdDesc(Long userId, Instant cutOff);
}
@@ -1,130 +0,0 @@
package SuMoC.backend.carrousel.service;
import SuMoC.backend.carrousel.config.CarrouselProperties;
import SuMoC.backend.carrousel.dto.AdHocAlternativeContext;
import SuMoC.backend.carrousel.dto.AlternativeCarrouselDTO;
import SuMoC.backend.carrousel.dto.RegularTripAlternativeContext;
import SuMoC.backend.carrousel.dto.RouteAlternativeContext;
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
import SuMoC.backend.carrousel.models.CarrouselCandidate;
import SuMoC.backend.carrousel.repository.CarrouselCandidateRepository;
import SuMoC.backend.geocoding.AddressDTO;
import SuMoC.backend.geocoding.GeoCodingService;
import SuMoC.backend.h3.H3Service;
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
import SuMoC.backend.regulartrip.dtos.MinimalDetectedRegularTripDTO;
import SuMoC.backend.routing.dtos.RouteDTO;
import SuMoC.backend.trip.models.Trip;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
@Service
@RequiredArgsConstructor
public class CarrouselService {
private final CarrouselCandidateRepository carrouselCandidateRepository;
private final CarrouselProperties carrouselProperties;
private final H3Service h3Service;
private final GeoCodingService geoCodingService;
public void addAdHocTripCandidates(Trip trip, List<RouteDTO> suggestedAlternatives) {
for (var alternative : suggestedAlternatives) {
CarrouselCandidate candidate = CarrouselCandidate.builder()
.userId(trip.getUser().getId())
.adHocTripId(trip.getId())
.suggestedAlternative(alternative)
.suggestedAt(Instant.now())
.candidateType(CarrouselCandidateType.ADHOC_ALTERNATIVE)
.build();
carrouselCandidateRepository.save(candidate);
}
}
public List<CarrouselCandidate> getRegularTripCandidates(Long userId, DetectedRegularTripDTO detectedRegularTrip, List<RouteDTO> suggestedAlternatives) {
List<CarrouselCandidate> candidates = new ArrayList<>();
for (var alternative : suggestedAlternatives) {
CarrouselCandidate candidate = CarrouselCandidate.builder()
.userId(userId)
.detectedRegularTrip(MinimalDetectedRegularTripDTO.fromDetectedRegularTripDTO(detectedRegularTrip))
.suggestedAlternative(alternative)
.suggestedAt(Instant.now())
.candidateType(CarrouselCandidateType.REGULAR_TRIP_ALTERNATIVE)
.build();
candidates.add(candidate);
}
return candidates;
}
public AlternativeCarrouselDTO getCarrouselForUser(Long userId) {
var candidates = carrouselCandidateRepository.findByUserIdDesc(userId, Instant.now().minus(Duration.ofDays(carrouselProperties.getRecentSuggestionWindowDays())));
if (candidates.isEmpty()) {
return new AlternativeCarrouselDTO(List.of());
}
var alternativeEntries = candidates.stream()
.limit(carrouselProperties.getMaxCarrouselItems())
.map(this::mapToCarrouselAlternativeEntry)
.toList();
return new AlternativeCarrouselDTO(alternativeEntries);
}
/**
* Converts a CarrouselCandidate to a RouteAlternativeContext, which is the format expected by the frontend carousel.
*
* @param candidate
* @return
*/
private RouteAlternativeContext mapToCarrouselAlternativeEntry(CarrouselCandidate candidate) {
switch (candidate.getCandidateType()) {
case ADHOC_ALTERNATIVE -> {
return fromAdHocCandidate(candidate);
}
case REGULAR_TRIP_ALTERNATIVE -> {
return fromRegularTripCandidate(candidate);
}
default -> throw new IllegalStateException("Unimplemented candidate type: " + candidate.getCandidateType());
}
}
private RouteAlternativeContext fromAdHocCandidate(CarrouselCandidate candidate) {
return new AdHocAlternativeContext(candidate.getSuggestedAlternative(), candidate.getAdHocTripId());
}
private RouteAlternativeContext fromRegularTripCandidate(CarrouselCandidate candidate) {
var minRegularTrip = candidate.getDetectedRegularTrip();
var startLatLong = h3Service.cellToLatLng(minRegularTrip.getStartH3Center());
var endLatLong = h3Service.cellToLatLng(minRegularTrip.getEndH3Center());
// TODO we might want to remove the center addresses, we already have the start and end place names from the original trip - could save compute time and API calls here
// Fetch origin and destination addresses concurrently
var addressesMono = Mono.zip(
geoCodingService.getAddress(startLatLong.lat, startLatLong.lng),
geoCodingService.getAddress(endLatLong.lat, endLatLong.lng)
);
var addressesTuple = addressesMono.block();
AddressDTO startCenterAddress = addressesTuple.getT1();
AddressDTO endCenterAddress = addressesTuple.getT2();
return new RegularTripAlternativeContext(
candidate.getSuggestedAlternative(),
minRegularTrip,
startCenterAddress,
endCenterAddress
);
}
}
@@ -48,8 +48,6 @@ public class DirectionsService {
HashMap<String, Direction> directionMap = getPossibleDirections(requestDTO);
ArrayList<RouteDTO> suggestedRoutes = new ArrayList<>();
// TODO derive origin/destination either from address or coordinates
// Fetch origin and destination addresses concurrently
var addressesMono = Mono.zip(
geoCodingService.getAddress(requestDTO.getOriginLat(), requestDTO.getOriginLon()),
@@ -302,8 +300,6 @@ public class DirectionsService {
throw new IllegalArgumentException("Either arrivalTime or departureTime must be provided.");
}
// TODO derive origin either from address or coordinates
return cartaClient.asyncGetRoute(
requestDTO.getOriginLat() + "," + requestDTO.getOriginLon(),
requestDTO.getDestinationLat() + "," + requestDTO.getDestinationLon(),
@@ -315,7 +311,6 @@ public class DirectionsService {
null, // transferTime TODO what is default? adapt?
types,
null, // range
// TODO only if coordinates are provided directly
requestDTO.getOriginLat() + "," + requestDTO.getOriginLon()
);
}
@@ -1,39 +0,0 @@
package SuMoC.backend.config;
import SuMoC.backend.suggestion.config.RegularTripSuggestionProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync
@RequiredArgsConstructor
public class AsyncConfiguration {
private final RegularTripSuggestionProperties regularTripSuggestionProperties;
/**
* Custom thread pool executor for parallel processing of regular trip suggestions.
* Configured with parallelism setting from application properties.
*/
@Bean(name = "regularTripSuggestionExecutor")
public Executor regularTripSuggestionExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
int parallelism = regularTripSuggestionProperties.getParallelism();
executor.setCorePoolSize(parallelism);
executor.setMaxPoolSize(parallelism);
executor.setQueueCapacity(500); // Queue capacity for pending tasks
executor.setThreadNamePrefix("regular-trip-");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
executor.initialize();
return executor;
}
}
@@ -13,6 +13,8 @@ import SuMoC.backend.routing.dtos.RouteDTO;
import SuMoC.backend.scheduling.ScheduledTasks;
import SuMoC.backend.suggestion.services.RegularTripSuggestionService;
import SuMoC.backend.trend.dto.TrendDetectionDTO;
import SuMoC.backend.trend.enums.DeltaType;
import SuMoC.backend.trend.enums.StatAttribute;
import SuMoC.backend.trend.services.StatTableUpdateService;
import SuMoC.backend.user.dtos.FriendshipDTO;
import SuMoC.backend.user.dtos.MinimalUserDTO;
@@ -31,13 +33,15 @@ import org.springframework.context.annotation.Profile;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.Duration;
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")
@@ -90,9 +94,9 @@ public class DevController {
statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(day3WeeksAgo);
}
@GetMapping("/test-firebase-trend-notification/{fcm_token}")
@Operation(description = "Immediately sends a test notification of type TREND to the provided FCM token.")
public ResponseEntity<String> SendTestTrendNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
@GetMapping("/test-firebase-trend-notification-car-km/{fcm_token}")
@Operation(description = "Immediately sends a test notification of type TREND for CAR KM to the provided FCM token.")
public ResponseEntity<String> SendTestTrendNotificationCarKmFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
if (firebaseMessaging == null) {
return ResponseEntity.status(503)
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
@@ -114,6 +118,60 @@ public class DevController {
}
}
@GetMapping("/test-firebase-trend-notification-mobilityscore-per-km/{fcm_token}")
@Operation(description = "Immediately sends a test notification of type TREND for MOBILITY_SCORE_PER_KM to the provided FCM token.")
public ResponseEntity<String> SendTestTrendNotificationMobilityScoreFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
if (firebaseMessaging == null) {
return ResponseEntity.status(503)
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
}
try {
Notification notification = new Notification();
notification.setType(NotificationType.TREND);
TrendDetectionDTO dto = TrendDetectionDTO.mockTrendDetectionDTO();
dto.setDeltaType(DeltaType.PERCENTAGE);
dto.setAttribute(MOBILITY_SCORE_PER_KM);
notification.setData(objectMapper.writeValueAsString(dto));
Message mockTrendMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
// Send to a topic (no device registration needed)
String message = firebaseMessaging.sendAsync(
mockTrendMessage
).get();
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
} catch (Exception e) {
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
}
}
@GetMapping("/test-firebase-trend-notification-walk-bike-km/{fcm_token}")
@Operation(description = "Immediately sends a test notification of type TREND for WALKING_AND_CYCLING_DISTANCE to the provided FCM token.")
public ResponseEntity<String> SendTestTrendNotificationWalkBikeKmFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
if (firebaseMessaging == null) {
return ResponseEntity.status(503)
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
}
try {
Notification notification = new Notification();
notification.setType(NotificationType.TREND);
TrendDetectionDTO dto = TrendDetectionDTO.mockTrendDetectionDTO();
dto.setDeltaType(DeltaType.PERCENTAGE);
dto.setAttribute(StatAttribute.WALKING_AND_CYLING_DISTANCE);
notification.setData(objectMapper.writeValueAsString(dto));
Message mockTrendMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
// Send to a topic (no device registration needed)
String message = firebaseMessaging.sendAsync(
mockTrendMessage
).get();
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
} catch (Exception e) {
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
}
}
@GetMapping("/test-firebase-adhoc-route-notification/{fcm_token}")
@Operation(description = "Immediately sends a test notification of type ADHOC_ALTERNATIVE to the provided FCM token.")
public ResponseEntity<String> SendTestAdhocRouteNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
@@ -239,7 +297,7 @@ public class DevController {
.data(objectMapper.writeValueAsString(mockDTO))
.user(user)
.earliestTimeOfDayToSend(LocalTime.now())
.createdAt(Instant.now())
.createdAt(LocalDateTime.now())
.status(NotificationStatus.PENDING)
.build();
@@ -261,7 +319,7 @@ public class DevController {
.data(objectMapper.writeValueAsString(TrendDetectionDTO.mockTrendDetectionDTO()))
.user(user)
.earliestTimeOfDayToSend(LocalTime.now())
.createdAt(Instant.now().minus(Duration.ofDays(60)))
.createdAt(LocalDateTime.now().minusDays(60))
.status(NotificationStatus.SENT)
.build();
@@ -1,150 +0,0 @@
package SuMoC.backend.gamification.challenges;
import SuMoC.backend.gamification.challenges.Models.ChallengeDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Controller
@RequestMapping("/challenges")
class ChallengeController {
private ChallengeService challengeService;
@Autowired
public ChallengeController(ChallengeService challengeService) {
this.challengeService = challengeService;
}
// Admin Endpoints
@Operation(summary = "Create a new challenge")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Challenge created successfully",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = ChallengeDTO.class))),
@ApiResponse(responseCode = "400", description = "Invalid input data"),
})
@PostMapping("/createChallenge")
public ResponseEntity<ChallengeDTO> createChallenge(@RequestBody @Valid ChallengeDTO challengeDTO) {
ChallengeDTO createdChallenge = challengeService.createChallenge(challengeDTO);
return ResponseEntity.status(HttpStatus.CREATED).body(createdChallenge);
}
@Operation(summary = "Delete a challenge by ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Challenge deleted successfully"),
@ApiResponse(responseCode = "404", description = "Challenge not found")
})
@DeleteMapping("/deleteChallenge/{challengeId}")
public ResponseEntity<Void> deleteChallengeById(@PathVariable Long challengeId) {
challengeService.deleteChallenge(challengeId);
return ResponseEntity.ok().build();
}
@Operation(summary = "Modify a challenge by ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Challenge modified successfully",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = ChallengeDTO.class))),
@ApiResponse(responseCode = "404", description = "Challenge not found"),
@ApiResponse(responseCode = "400", description = "Invalid input data")
})
@PutMapping("/modifyChallenge")
public ResponseEntity<ChallengeDTO> modifyChallengeById(
@RequestBody @Valid ChallengeDTO challengeDTO) {
ChallengeDTO modifiedChallenge = challengeService.modifyChallenge(challengeDTO);
return ResponseEntity.status(HttpStatus.OK).body(modifiedChallenge);
}
@Operation(summary = "Get a challenge by ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Challenge retrieved successfully",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = ChallengeDTO.class))),
@ApiResponse(responseCode = "304", description = "Not modified since last request"),
@ApiResponse(responseCode = "404", description = "Challenge not found")
})
@GetMapping("/getChallenge/{challengeId}")
public ResponseEntity<ChallengeDTO> getChallengeById(@PathVariable Long challengeId) {
ChallengeDTO challengeDTO = challengeService.getChallengeById(challengeId);
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(356, TimeUnit.DAYS))
.body(challengeDTO);
}
@Operation(summary = "Get all challenges")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Challenges retrieved successfully",
content = @Content(mediaType = "application/json",
array = @ArraySchema(schema = @Schema(implementation = ChallengeDTO.class))
)),
@ApiResponse(responseCode = "304", description = "Not modified since last request"),
@ApiResponse(responseCode = "404", description = "No challenges found")
})
@GetMapping("/getAllChallenges")
public ResponseEntity<List<ChallengeDTO>> getAllChallenges(){
List<ChallengeDTO> challenges = challengeService.getAllChallenges();
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(365, TimeUnit.DAYS))
.body(challenges);
}
@Operation(summary = "Activate a challenge by ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Challenge activated successfully"),
@ApiResponse(responseCode = "404", description = "Challenge not found")
})
@PutMapping("/activateChallenge/{challengeId}")
public ResponseEntity<Void> activateChallengeById(@PathVariable Long challengeId) {
challengeService.activateChallenge(challengeId);
return ResponseEntity.ok().build();
}
@Operation(summary = "Deactivate a challenge by ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Challenge deactivated successfully"),
@ApiResponse(responseCode = "404", description = "Challenge not found")
})
@PutMapping("/deactivateChallenge/{challengeId}")
public ResponseEntity<Void> deactivateChallengeById(@PathVariable Long challengeId) {
challengeService.deactivateChallenge(challengeId);
return ResponseEntity.ok().build();
}
// User Endpoints
@Operation(summary = "Get all available challenges")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Available challenges retrieved successfully",
content = @Content(mediaType = "application/json",
array = @ArraySchema(schema = @Schema(implementation = ChallengeDTO.class))
)),
@ApiResponse(responseCode = "304", description = "Not modified since last request"),
@ApiResponse(responseCode = "404", description = "No available challenges found")
})
@GetMapping("/getAvailableChallenges")
public ResponseEntity<List<ChallengeDTO>> getAvailableChallenges() {
List<ChallengeDTO> challenges = challengeService.getAvailableChallenges();
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(7, TimeUnit.DAYS))
.body(challenges);
}
}
@@ -1,34 +0,0 @@
package SuMoC.backend.gamification.challenges;
import SuMoC.backend.gamification.challenges.Models.Challenge;
import SuMoC.backend.images.ImageEntity;
import jakarta.persistence.DiscriminatorValue;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToOne;
@Entity
@DiscriminatorValue("CHALLENGE")
public class ChallengeImageEntity extends ImageEntity {
@OneToOne
@JoinColumn(name = "challenge_id")
private Challenge challenge;
public ChallengeImageEntity() {
super();
}
public ChallengeImageEntity(Challenge challenge, byte[] imageData) {
super(imageData);
}
public Challenge getChallenge() {
return challenge;
}
public void setChallenge(Challenge challenge) {
this.challenge = challenge;
}
}
@@ -1,62 +0,0 @@
package SuMoC.backend.gamification.challenges;
import SuMoC.backend.gamification.challenges.Models.Challenge;
import SuMoC.backend.gamification.challenges.Models.ChallengeDTO;
import SuMoC.backend.images.ImageBase64Util;
import org.mapstruct.Mapper;
import java.util.Optional;
@Mapper
public interface ChallengeMapper {
static ChallengeDTO toDTO(Challenge challenge) {
ChallengeDTO dto = new ChallengeDTO();
dto.setId(challenge.getId());
dto.setName(challenge.getName());
dto.setDescription(challenge.getDescription());
dto.setCriteria(challenge.getCriteria());
dto.setReward(challenge.getReward());
dto.setBase64image(
Optional.ofNullable(challenge.getImage())
.map(ChallengeImageEntity::getImageData)
.map(ImageBase64Util::encode)
.orElse(null)
);
return dto;
}
static Challenge toEntity(ChallengeDTO dto) {
Challenge challenge = new Challenge();
challenge.setId(dto.getId());
challenge.setName(dto.getName());
challenge.setDescription(dto.getDescription());
challenge.setCriteria(dto.getCriteria());
challenge.setReward(dto.getReward());
if (dto.getBase64image() != null && !dto.getBase64image().isEmpty()) {
challenge.setImage(new ChallengeImageEntity(
challenge,
ImageBase64Util.decode(dto.getBase64image())
));
}
return challenge;
}
static void updateEntityFromDTO(Challenge challenge, ChallengeDTO dto) {
challenge.setName(dto.getName());
challenge.setDescription(dto.getDescription());
challenge.setCriteria(dto.getCriteria());
challenge.setReward(dto.getReward());
if (dto.getBase64image() != null && !dto.getBase64image().isEmpty()) {
byte[] imageData = ImageBase64Util.decode(dto.getBase64image());
if (challenge.getImage() == null) {
challenge.setImage(new ChallengeImageEntity(challenge, imageData));
} else {
challenge.getImage().setImageData(imageData);
}
}
}
}
@@ -1,23 +0,0 @@
package SuMoC.backend.gamification.challenges;
import SuMoC.backend.gamification.challenges.Models.Challenge;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface ChallengeRepository extends JpaRepository<Challenge, Long> {
List<Challenge> findAllByActiveIs(Boolean active);
@Query("""
SELECT DISTINCT c FROM Challenge c
JOIN c.criteria crit
WHERE KEY(crit) IS NOT NULL
AND VALUE(crit) IS NOT NULL
""")
List<Challenge> findAllWithValidCriteria();
Optional<Challenge> findByName(String name);
}
@@ -1,143 +0,0 @@
package SuMoC.backend.gamification.challenges;
import SuMoC.backend.gamification.Timeframe;
import SuMoC.backend.gamification.challenges.Models.Challenge;
import SuMoC.backend.gamification.challenges.Models.ChallengeDTO;
import SuMoC.backend.user.models.User;
import SuMoC.backend.user.repository.UserRepository;
import SuMoC.backend.user.service.CurrentUserService;
import jakarta.transaction.Transactional;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.util.Collections;
import java.util.List;
import static java.lang.Math.min;
@Service
public class ChallengeService {
private final CurrentUserService currentUser;
private final ChallengeRepository challengeRepository;
private final UserRepository userRepository;
public ChallengeService(CurrentUserService currentUser, ChallengeRepository challengeRepository, UserRepository userRepository) {
this.currentUser = currentUser;
this.challengeRepository = challengeRepository;
this.userRepository = userRepository;
}
// Management of Challenges
public ChallengeDTO createChallenge(ChallengeDTO challengeDTO) {
Challenge challenge = ChallengeMapper.toEntity(challengeDTO);
Challenge savedChallenge = challengeRepository.save(challenge);
return ChallengeMapper.toDTO(savedChallenge);
}
public ChallengeDTO getChallengeById(Long id) {
Challenge challenge = challengeRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Challenge not found"));
return ChallengeMapper.toDTO(challenge);
}
public List<ChallengeDTO> getAllChallenges() {
List<Challenge> challenges = challengeRepository.findAll();
return challenges.stream()
.map(ChallengeMapper::toDTO)
.toList();
}
public ChallengeDTO modifyChallenge(ChallengeDTO challengeDTO) {
Challenge existingChallenge = challengeRepository.findById(challengeDTO.getId())
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Challenge not found"));
ChallengeMapper.updateEntityFromDTO(existingChallenge, challengeDTO);
Challenge updatedChallenge = challengeRepository.save(existingChallenge);
return ChallengeMapper.toDTO(updatedChallenge);
}
public void deleteChallenge(Long id) {
Challenge challenge = challengeRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Challenge not found"));
challengeRepository.delete(challenge);
}
public void deactivateChallenge(Long id) {
Challenge challenge = challengeRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Challenge not found"));
challenge.setActive(false);
challengeRepository.save(challenge);
}
public void activateChallenge(Long id) {
Challenge challenge = challengeRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Challenge not found"));
challenge.setActive(true);
challengeRepository.save(challenge);
}
// User Requests
public List<ChallengeDTO> getAvailableChallenges() {
List<Challenge> challenges = challengeRepository.findAllByActiveIs(true);
return challenges.stream()
.map(ChallengeMapper::toDTO)
.toList();
}
public void checkAndAwardChallenges(String field, Long value) {
User user = currentUser.get();
Long currentStat = user.getStats().getStatValue(Timeframe.WEEKLY, field);
Long newStat = currentStat + value;
List<Challenge> activeChallenges = challengeRepository.findAllByActiveIs(true);
for (Challenge challenge : activeChallenges) {
Integer target = challenge.getCriteria().get(field);
if (target != null && currentStat < target && newStat >= target) {
user.getStats().addToAllStats("XP", challenge.getReward());
userRepository.save(user);
}
}
}
// Additional Methods
@Transactional
public void setActiveById(Long challengeId, Boolean active) {
Challenge challenge = challengeRepository.findById(challengeId)
.orElseThrow();
challenge.setActive(active);
}
@Transactional
@Scheduled(cron = "0 0 0 ? * MON")
public void weeklyChallengeScheduler() {
List<Challenge> activeChallenges = challengeRepository.findAllByActiveIs(true);
activeChallenges.forEach(challenge -> {
setActiveById(challenge.getId(), false);
});
List<Challenge> allChallenges = challengeRepository.findAllWithValidCriteria();
int limit = min(allChallenges.size(), 3);
if (limit == 0) {
return;
}
Collections.shuffle(allChallenges);
allChallenges.stream()
.limit(limit)
.forEach(challenge -> setActiveById(challenge.getId(), true));
}
}
@@ -1,113 +0,0 @@
package SuMoC.backend.gamification.challenges.Models;
import SuMoC.backend.gamification.challenges.ChallengeImageEntity;
import jakarta.persistence.*;
import java.util.HashMap;
import java.util.Map;
@Entity
public class Challenge {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
@OneToOne(mappedBy = "challenge", cascade = CascadeType.ALL, orphanRemoval = true)
private ChallengeImageEntity image;
@ElementCollection
@CollectionTable(name = "challenge_criteria", joinColumns = @JoinColumn(name = "challenge_id"))
@MapKeyColumn(name = "criteria_name")
@Column(name = "criteria_value")
private Map<String, Integer> criteria = new HashMap<>();
private Integer reward;
private Boolean active;
// Constructors
public Challenge(String name, String description) {
this(name, description, null, 0);
}
public Challenge(String name, String description, Map<String, Integer> criteria, Integer reward) {
this(name, description, criteria, reward, new ChallengeImageEntity(null, null));
}
public Challenge(String name, String description, Map<String, Integer> criteria, Integer reward, ChallengeImageEntity image) {
this.name = name;
this.description = description;
this.criteria = criteria;
this.reward = reward;
this.image = image;
this.active = false;
}
public Challenge() {
}
// Getter & Setter
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ChallengeImageEntity getImage() {
return image;
}
public void setImage(ChallengeImageEntity image) {
this.image = image;
}
public Map<String, Integer> getCriteria() {
return criteria;
}
public void setCriteria(Map<String, Integer> criteria) {
this.criteria = criteria;
}
public Integer getReward() {
return reward;
}
public void setReward(Integer reward) {
this.reward = reward;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
}
@@ -1,85 +0,0 @@
package SuMoC.backend.gamification.challenges.Models;
import java.util.Map;
public class ChallengeDTO {
private Long id;
private String name;
private String description;
private String base64image;
private Map<String, Integer> criteria;
private Integer reward;
// Constructors
public ChallengeDTO() {}
public ChallengeDTO(Long id, String name, String description, String base64image, Map<String, Integer> criteria, Integer reward) {
this.id = id;
this.name = name;
this.description = description;
this.base64image = base64image;
this.criteria = criteria;
this.reward = reward;
}
public ChallengeDTO(Long id, String name, String description, Map<String, Integer> criteria, Integer reward) {
this(id, name, description, null, criteria, reward);
}
public ChallengeDTO(Long id , String name, String description) {
this(id, name, description, null, 0);
}
// Getter & Setter
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getBase64image() {
return base64image;
}
public void setBase64image(String base64image) {
this.base64image = base64image;
}
public Map<String, Integer> getCriteria() {
return criteria;
}
public void setCriteria(Map<String, Integer> criteria) {
this.criteria = criteria;
}
public Integer getReward() {
return reward;
}
public void setReward(Integer reward) {
this.reward = reward;
}
}
@@ -1,21 +0,0 @@
package SuMoC.backend.images;
public class ImageRequestDTO {
private String base64ProfilePicture;
public ImageRequestDTO(String base64ProfilePicture) {
this.base64ProfilePicture = base64ProfilePicture;
}
public ImageRequestDTO() {}
public String getBase64ProfilePicture() {
return base64ProfilePicture;
}
public void setBase64ProfilePicture(String base64ProfilePicture) {
this.base64ProfilePicture = base64ProfilePicture;
}
}
@@ -1,13 +1,9 @@
package SuMoC.backend.notification.config;
import SuMoC.backend.notification.enums.NotificationType;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Data
@Component
@ConfigurationProperties(prefix = "sumoc.notification")
@@ -16,14 +12,4 @@ public class NotificationProperties {
* Maximum number of failed send attempts before giving up on a notification.
*/
private int maxFailedSendAttempts = 3;
/**
* Maximum number of notifications to send to a user per hour per notification type.
*/
private Map<NotificationType, Integer> maxNotificationsPerHourPerType = new HashMap<>(Map.of(
NotificationType.TREND, 1,
NotificationType.ADHOC_ALTERNATIVE, 1,
NotificationType.REGULAR_TRIP_ALTERNATIVE, 1,
NotificationType.FRIENDSHIP_REQUEST_RECEIVED, 3
));
}
@@ -1,9 +0,0 @@
package SuMoC.backend.notification.interfaces;
import java.time.LocalTime;
public interface NotifieableWithTime {
Long getUserId();
LocalTime getEarliestTimeOfDayToSend();
}
@@ -6,7 +6,7 @@ import SuMoC.backend.user.models.User;
import jakarta.persistence.*;
import lombok.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
@Entity
@@ -54,10 +54,8 @@ public class Notification {
private String lastFailureReason;
@Column(nullable = false)
private Instant createdAt;
@Column(nullable = true)
private Instant sentAt = null;
private LocalDateTime createdAt;
public void incrementFailedSendAttempts() {
this.failedSendAttempts++;
@@ -5,7 +5,7 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
@@ -20,20 +20,11 @@ public interface NotificationRepository extends JpaRepository<Notification, Long
""")
List<Notification> findPendingNotificationsToSend(LocalTime currentTime);
@Query("""
SELECT n
FROM Notification n
WHERE n.user.id = :userId
AND n.status = 'SENT'
AND n.createdAt >= :since
""")
List<Notification> getSentToUserSince(Long userId, Instant since);
@Modifying
@Query("""
DELETE
FROM Notification n
WHERE n.createdAt < :cutOff
""")
void deleteNotificationsOlder(Instant cutOff);
void deleteNotificationsOlder(LocalDateTime cutOff);
}
@@ -1,65 +0,0 @@
package SuMoC.backend.notification.services;
import SuMoC.backend.notification.config.NotificationProperties;
import SuMoC.backend.notification.enums.NotificationStatus;
import SuMoC.backend.notification.enums.NotificationType;
import SuMoC.backend.notification.models.Notification;
import SuMoC.backend.notification.repositories.NotificationRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
@Service
@RequiredArgsConstructor
class NotificationLimiter {
private final NotificationRepository notificationRepository;
private final NotificationProperties notificationProperties;
/**
* Filters the given list of notifications to ensure that no user exceeds the hourly limit.
* Notifications exceeding the limit are excluded and set to FAILED status.
*
* @param notifications
* @return
*/
public List<Notification> enforceHourlyLimits(List<Notification> notifications) {
List<Notification> safeToSend = new java.util.ArrayList<>();
// Avoid multiple queries if user has multiple notifications in the list
HashMap<Long, List<Notification>> notificationsByUser = new HashMap<>();
for (var notification : notifications) {
var userId = notification.getUser().getId();
notificationsByUser
.computeIfAbsent(userId,
k -> notificationRepository.getSentToUserSince(k, Instant.now().minus(Duration.ofHours(1L))));
var numberSent = getNumberSentPerType(notificationsByUser.get(userId), notification.getType());
if (numberSent < notificationProperties.getMaxNotificationsPerHourPerType().getOrDefault(notification.getType(), Integer.MAX_VALUE)) {
safeToSend.add(notification);
notificationsByUser.get(userId).add(notification); // Consider this one as sent for further checks
} else {
// Exceeded limit, mark as FAILED
notification.setStatus(NotificationStatus.FAILED);
notification.setLastFailureReason("Hourly limit exceeded for notification type");
notificationRepository.save(notification);
}
}
return safeToSend;
}
private Integer getNumberSentPerType(List<Notification> sentNotifications, NotificationType type) {
return (int) sentNotifications.stream()
.filter(n -> n.getType() == type)
.count();
}
}
@@ -3,7 +3,6 @@ package SuMoC.backend.notification.services;
import SuMoC.backend.notification.enums.NotificationStatus;
import SuMoC.backend.notification.enums.NotificationType;
import SuMoC.backend.notification.interfaces.Notifieable;
import SuMoC.backend.notification.interfaces.NotifieableWithTime;
import SuMoC.backend.notification.models.Notification;
import SuMoC.backend.notification.repositories.NotificationRepository;
import SuMoC.backend.user.models.User;
@@ -12,7 +11,7 @@ import jakarta.persistence.EntityManager;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
@@ -58,34 +57,7 @@ public class NotificationSchedulerService {
.data(dataBodyJson)
.earliestTimeOfDayToSend(earliestTimeOfDayToSend)
.status(NotificationStatus.PENDING)
.createdAt(Instant.now())
.failedSendAttempts(0)
.build();
}).toList();
notificationRepository.saveAll(notifications);
}
public void scheduleAll(List<NotifieableWithTime> dataBodies,
NotificationType notificationType
) {
List<Notification> notifications = dataBodies.stream().map(dataBody -> {
String dataBodyJson;
try {
dataBodyJson = objectMapper.writeValueAsString(dataBody);
} catch (Exception e) {
throw new RuntimeException("Failed to serialize notification data body", e);
}
User userProxy = entityManager.getReference(User.class, dataBody.getUserId());
return Notification.builder()
.user(userProxy)
.type(notificationType)
.data(dataBodyJson)
.earliestTimeOfDayToSend(dataBody.getEarliestTimeOfDayToSend())
.status(NotificationStatus.PENDING)
.createdAt(Instant.now())
.createdAt(LocalDateTime.now())
.failedSendAttempts(0)
.build();
}).toList();
@@ -127,7 +99,7 @@ public class NotificationSchedulerService {
.data(dataBodyJson)
.earliestTimeOfDayToSend(earliestTimeOfDayToSend)
.status(NotificationStatus.PENDING)
.createdAt(Instant.now())
.createdAt(LocalDateTime.now())
.failedSendAttempts(0)
.build();
@@ -16,7 +16,6 @@ import com.google.firebase.messaging.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.util.logging.Logger;
@Service
@@ -68,7 +67,6 @@ public class NotificationSender {
@Override
public void onSuccess(String messageId) {
notification.setStatus(NotificationStatus.SENT);
notification.setSentAt(Instant.now());
notificationRepository.save(notification);
logger.info("Notification sent successfully to user: " + notification.getUser().getId());
}
@@ -6,8 +6,7 @@ import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
@@ -20,18 +19,15 @@ public class NotificationWorker {
private final NotificationSender notificationSender;
private final NotificationLimiter notificationLimiter;
/**
* Process all pending notifications.
*/
public void run() {
// Get all pending notifications where earliest send time has passed and status is pending
List<Notification> pendingNotifications =
notificationRepository.findPendingNotificationsToSend(LocalTime.now());
var notificationSafeToSend = notificationLimiter.enforceHourlyLimits(pendingNotifications);
for (Notification notification : notificationSafeToSend) {
// Send them
for (Notification notification : pendingNotifications) {
notificationSender.sendNotification(notification);
}
}
@@ -41,6 +37,6 @@ public class NotificationWorker {
*/
public void cleanUpOldNotifications() {
// Delete notifications older than 30 days
notificationRepository.deleteNotificationsOlder(Instant.now().minus(Duration.ofDays(30)));
notificationRepository.deleteNotificationsOlder(LocalDateTime.now().minusDays(30));
}
}
@@ -1,79 +0,0 @@
package SuMoC.backend.regulartrip.dtos;
import SuMoC.backend.trip.Modality;
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.time.DayOfWeek;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Comparator;
import java.util.List;
/**
* Minimal version of the DetectedRegularTripDTO for the purpose of storing in the database and showing in the carousel.
*/
@NoArgsConstructor
@Getter
public class MinimalDetectedRegularTripDTO {
private Modality modality;
private DayOfWeek dayOfWeek;
@Schema(description = "Earliest departure time among the supporting trips, in the user's local time")
private LocalTime departureWindowStart;
@Schema(description = "Latest departure time among the supporting trips, in the user's local time")
private LocalTime departureWindowEnd;
@Schema(description = "Earliest arrival time among the supporting trips, in the user's local time")
private LocalTime arrivalWindowStart;
@Schema(description = "Latest arrival time among the supporting trips, in the user's local time")
private LocalTime arrivalWindowEnd;
private String startH3Center;
private String endH3Center;
public static MinimalDetectedRegularTripDTO fromDetectedRegularTripDTO(DetectedRegularTripDTO regularTrip) {
MinimalDetectedRegularTripDTO minimalDTO = new MinimalDetectedRegularTripDTO();
minimalDTO.modality = regularTrip.getModality();
minimalDTO.dayOfWeek = regularTrip.getDayOfWeek();
minimalDTO.departureWindowStart = getEarliestDeparture(regularTrip.getSupportingTrips());
minimalDTO.departureWindowEnd = getLatestDeparture(regularTrip.getSupportingTrips());
minimalDTO.arrivalWindowStart = getEarliestArrival(regularTrip.getSupportingTrips());
minimalDTO.arrivalWindowEnd = getLatestArrival(regularTrip.getSupportingTrips());
minimalDTO.startH3Center = regularTrip.getStartH3Center();
minimalDTO.endH3Center = regularTrip.getEndH3Center();
return minimalDTO;
}
private static LocalTime getEarliestArrival(List<RegularTripDetectionDTO> supportingTrips) {
var earliest = supportingTrips.stream()
.map(RegularTripDetectionDTO::getStartTime)
.min(Comparator.naturalOrder())
.orElseThrow();
return LocalTime.ofInstant(earliest, ZoneId.systemDefault());
}
private static LocalTime getLatestArrival(List<RegularTripDetectionDTO> supportingTrips) {
var latest = supportingTrips.stream()
.map(RegularTripDetectionDTO::getStartTime)
.max(Comparator.naturalOrder())
.orElseThrow();
return LocalTime.ofInstant(latest, ZoneId.systemDefault());
}
private static LocalTime getEarliestDeparture(List<RegularTripDetectionDTO> supportingTrips) {
var earliest = supportingTrips.stream()
.map(RegularTripDetectionDTO::getEndTime)
.min(Comparator.naturalOrder())
.orElseThrow();
return LocalTime.ofInstant(earliest, ZoneId.systemDefault());
}
private static LocalTime getLatestDeparture(List<RegularTripDetectionDTO> supportingTrips) {
var latest = supportingTrips.stream()
.map(RegularTripDetectionDTO::getEndTime)
.max(Comparator.naturalOrder())
.orElseThrow();
return LocalTime.ofInstant(latest, ZoneId.systemDefault());
}
}
@@ -16,8 +16,8 @@ public class AdHocRoutingProperties extends RoutingProperties {
public AdHocRoutingProperties() {
super();
setAcceptableAdditionalMultiplierRegular(2.0);
setAcceptableAdditionalMultiplierPrefersPhysical(2.0);
setAcceptableAdditionalMultiplierRegular(1.30);
setAcceptableAdditionalMultiplierPrefersPhysical(1.6);
setMinimumAcceptedAdditionalSecondsRegular(5 * 60);
setMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity(5 * 60);
}
@@ -2,7 +2,6 @@ package SuMoC.backend.routing.dtos;
import SuMoC.backend.geocoding.AddressDTO;
import SuMoC.backend.trip.Modality;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.annotation.Nullable;
import lombok.Getter;
@@ -18,7 +17,6 @@ import java.util.List;
@Setter
@NoArgsConstructor
@Schema(description = "This DTO represents a suggested route as a response to a requested alternative route.")
@JsonIgnoreProperties(ignoreUnknown = true)
public class RouteDTO {
@Schema(description = "The actual address of the start location.")
private AddressDTO startAddress;
@@ -1,8 +1,6 @@
package SuMoC.backend.routing.dtos;
import SuMoC.backend.trip.Modality;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;
@@ -13,11 +11,6 @@ import lombok.Setter;
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = TransitStepDTO.class, name = "transit"),
@JsonSubTypes.Type(value = StepDTO.class, name = "step")
})
@Schema(description = "A single step within a suggested alternative route.")
public class StepDTO {
private Modality modality;
@@ -2,16 +2,12 @@ package SuMoC.backend.routing.dtos;
import SuMoC.backend.trip.Modality;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Schema(description = "A single transit step within a suggested alternative route.")
@NoArgsConstructor
@AllArgsConstructor
public class TransitStepDTO extends StepDTO {
private String lineNumber;
private String lineHeadsign;
@@ -35,7 +35,7 @@ public class RoutingPreferences {
preferences.setPreferPhysicalActivity(false);
preferences.setConsiderWeatherConditions(true);
preferences.setModalitiesToConsider(new ArrayList<>(List.of(
Modality.WALKING,
Modality.WALKING, Modality.BICYCLE, Modality.ESCOOTER,
Modality.BUS, Modality.TRAM, Modality.TRAIN
)));
return preferences;
@@ -81,6 +81,4 @@ public class ScheduledTasks {
logger.error("Error notifying regular route alternatives.", e);
}
}
// TODO clean up task for carrousel candidates
}
@@ -100,13 +100,11 @@ public class SecurityConfiguration {
auth.requestMatchers("/friendship/**").hasAnyRole("ADMIN", "USER");
auth.requestMatchers("/trip/**").hasAnyRole("USER", "ADMIN");
auth.requestMatchers("/geocoding/**").hasAnyRole("USER", "ADMIN");
auth.requestMatchers("/routing/alternative/carrousel/**").hasAnyRole("USER", "ADMIN");
auth.requestMatchers("/routing/preferences/**").hasAnyRole("USER", "ADMIN");
// gamification
auth.requestMatchers("/badges/**").hasAnyRole("ADMIN", "USER");
auth.requestMatchers("/leaderboard/**").hasAnyRole("ADMIN", "USER");
auth.requestMatchers("/challenges/**").hasAnyRole("ADMIN", "USER");
auth.requestMatchers("/notifications/**").hasAnyRole("USER", "ADMIN");
//auth.requestMatchers("/error").permitAll();
@@ -1,166 +0,0 @@
package SuMoC.backend.seed;
import SuMoC.backend.gamification.challenges.ChallengeMapper;
import SuMoC.backend.gamification.challenges.ChallengeRepository;
import SuMoC.backend.gamification.challenges.ChallengeService;
import SuMoC.backend.gamification.challenges.Models.ChallengeDTO;
import jakarta.transaction.Transactional;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.*;
@Component
@Profile("dev")
@Order(4)
public class DevChallengeSeeder implements CommandLineRunner {
private final ChallengeService challengeService;
private final ChallengeRepository challengeRepository;
public DevChallengeSeeder(
ChallengeService challengeService,
ChallengeRepository challengeRepository
) {
this.challengeService = challengeService;
this.challengeRepository = challengeRepository;
}
@Override
@Transactional
public void run(String... args) {
List<Seed> seeds = generateSeeds();
for (Seed seed : seeds) {
challengeRepository.findByName(seed.name())
.map(ChallengeMapper::toDTO)
.ifPresentOrElse(
existingChallenge -> {
// Update existing challenge
existingChallenge.setName(seed.name());
existingChallenge.setDescription(seed.description());
existingChallenge.setCriteria(seed.criteria());
existingChallenge.setReward(seed.reward());
challengeService.modifyChallenge(existingChallenge);
},
() -> {
// Create new challenge
ChallengeDTO newChallenge = new ChallengeDTO();
newChallenge.setName(seed.name());
newChallenge.setDescription(seed.description());
newChallenge.setCriteria(seed.criteria());
newChallenge.setReward(seed.reward());
challengeService.createChallenge(newChallenge);
}
);
}
challengeService.weeklyChallengeScheduler();
}
private record Seed(String name, String description, Map<String, Integer> criteria, Integer reward) {}
private static Seed seed(
String name,
String description,
Map<String, Integer> criteria,
Integer reward
) {
return new Seed(name, description, criteria, reward);
}
private List<Seed> generateSeeds() {
List<Seed> seeds = new ArrayList<>();
seeds.add(seed(
"Feierabendrunde",
"Lege diese Woche 10 km mit dem Fahrrad zurück",
Map.of("KM_CYCLED", 10),
80
));
seeds.add(seed(
"Fahrrad-Fokus",
"Lege diese Woche 25 km mit dem Fahrrad zurück",
Map.of("KM_CYCLED", 25),
150
));
seeds.add(seed(
"Rad-Marathon",
"Lege diese Woche 60 km mit dem Fahrrad zurück",
Map.of("KM_CYCLED", 60),
320
));
seeds.add(seed(
"ÖPNV-Snack",
"Fahre diese Woche 10 km mit öffentlichen Verkehrsmitteln",
Map.of("KM_PUBLIC_TRANSPORT", 10),
80
));
seeds.add(seed(
"ÖPNV-Woche",
"Fahre diese Woche 20 km mit öffentlichen Verkehrsmitteln",
Map.of("KM_PUBLIC_TRANSPORT", 20),
150
));
seeds.add(seed(
"ÖPNV-Poweruser",
"Fahre diese Woche 50 km mit öffentlichen Verkehrsmitteln",
Map.of("KM_PUBLIC_TRANSPORT", 50),
300
));
seeds.add(seed(
"Spaziergänger",
"Gehe diese Woche 5 km zu Fuß",
Map.of("KM_WALKED", 5),
60
));
seeds.add(seed(
"Stadtläufer",
"Gehe diese Woche 15 km zu Fuß",
Map.of("KM_WALKED", 15),
140
));
seeds.add(seed(
"Weitwanderer",
"Gehe diese Woche 30 km zu Fuß",
Map.of("KM_WALKED", 30),
280
));
seeds.add(seed(
"XP-Booster",
"Sammle diese Woche 250 XP",
Map.of("XP", 250),
200
));
seeds.add(seed(
"XP-Grinder",
"Sammle diese Woche 500 XP",
Map.of("XP", 500),
350
));
seeds.add(seed(
"XP-Overkill",
"Sammle diese Woche 1000 XP",
Map.of("XP", 1000),
600
));
return seeds;
}
}
@@ -32,25 +32,21 @@ public class DevTripSeeder implements CommandLineRunner {
userRepository.findAll().forEach(user -> {
for (int week = 0; week < 5; week++) {
for (int day = 0; day < 7; day++) {
// NewTripDTO carTrip = TripFactory.newCarTripDTO(
// Instant.now()
// .minus(Duration.ofDays(week * 7 + day)).atZone(ZoneId.systemDefault()).toInstant()
// );
// This should definitly trigger regularTripDetection
NewTripDTO triggerCarTrip = TripFactory.newTriggeringCarMock(
java.time.Instant.now().minus(java.time.Duration.ofDays(week * 7 + day))
NewTripDTO carTrip = TripFactory.newCarTripDTO(
java.time.Instant.now()
.minus(java.time.Duration.ofDays(week * 7 + day))
);
tripService.addTrip(user, triggerCarTrip);
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);
// NewTripDTO newTrip = TripFactory.randomNewTripDTO(
// java.time.Instant.now().minus(java.time.Duration.ofDays((long) (Math.random() * 30))));
// tripService.addTrip(user, newTrip);
// }
for (int i = 0; i < 5; i++) {
// Create trips within each week's time range
long daysAgo = week * 7 + (long) (Math.random() * 7);
NewTripDTO newTrip = TripFactory.randomNewTripDTO(
java.time.Instant.now().minus(java.time.Duration.ofDays((long) (Math.random() * 30))));
tripService.addTrip(user, newTrip);
}
}
});
}
@@ -36,36 +36,6 @@ public class DevUserSeeder implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
seedPgMembers();
seedDefaultTestUsers();
//seedNtestUsers(10);
}
/**
* Useful for stress testing with a larger number of users. Seeds the specified number of users dummy users.
*
* @param numberOfUsers
*/
private void seedNtestUsers(int numberOfUsers) {
for (int i = 1; i <= numberOfUsers; i++) {
UserRegistrationDTO userDto = UserRegistrationDTO.builder()
.email("testuser" + i + "@email.com")
.publicName("Test User " + i)
.privateName("Test User " + i)
.password("password" + i)
.build();
authenticationService.registerUser(userDto);
User user = userRepository.findByEmail("testuser" + i + "@email.com").orElseThrow();
notificationTokenService.registerDeviceToken(
user,
NotificationProvider.FIREBASE,
devProperties.getFcmKey()
);
}
}
private void seedDefaultTestUsers() {
UserRegistrationDTO user1dto = UserRegistrationDTO.builder()
.email("user1@email.com")
.publicName("Nutzer 1 Public")
@@ -92,9 +62,6 @@ public class DevUserSeeder implements CommandLineRunner {
NotificationProvider.FIREBASE,
devProperties.getFcmKey()
);
}
private void seedPgMembers() {
UserRegistrationDTO user3dto = UserRegistrationDTO.builder()
.email("david@test.com")
.publicName("David N. Public")
@@ -14,5 +14,5 @@ public class AdHocSuggestionProperties {
* Maximum time after which an uploaded trip is considered recent enough to send
* an alternative routing suggestion for if available.
*/
private Integer recentTripThresholdSeconds = 60 * 60 * 6;
private Integer recentTripThresholdSeconds = 60 * 60;
}
@@ -14,11 +14,4 @@ public class RegularTripSuggestionProperties {
* We keep it relatively short since regular trips have a time window.
*/
private Integer notifyBeforeMinutes = 15;
/**
* Number of parallel threads to use for processing users concurrently when checking
* for regular trip alternatives. Higher values increase throughput but consume more
* resources (database connections, API rate limits, memory).
*/
private Integer parallelism = 10;
}
@@ -1,44 +0,0 @@
package SuMoC.backend.suggestion.dtos;
import SuMoC.backend.notification.interfaces.NotifieableWithTime;
import SuMoC.backend.routing.dtos.RouteDTO;
import lombok.Getter;
import java.time.LocalTime;
/**
* This DTO extends RouteDTO and implements Notifieable to be used as the data body for notifications about route suggestions.
* This allows us to use the saveAll method in NotificationSchedulerService for better performance when scheduling multiple notifications at once.
*/
public class RouteDTOtoBeNotified extends RouteDTO implements NotifieableWithTime {
private Long userId;
@Getter
private LocalTime earliestTimeOfDayToSend;
public RouteDTOtoBeNotified(RouteDTO routeDTO, Long userId, LocalTime earliestTimeOfDayToSend) {
super(
routeDTO.getStartAddress(),
routeDTO.getFirstStopName(),
routeDTO.getStartLat(),
routeDTO.getStartLon(),
routeDTO.getEndAddress(),
routeDTO.getLastStopName(),
routeDTO.getEndLat(),
routeDTO.getEndLon(),
routeDTO.getStartDateTime(),
routeDTO.getEndDateTime(),
routeDTO.getSteps(),
routeDTO.getCo2Savings(),
routeDTO.getTimeDifferenceSeconds(),
routeDTO.getCo2Emissions()
);
this.userId = userId;
this.earliestTimeOfDayToSend = earliestTimeOfDayToSend;
}
@Override
public Long getUserId() {
return this.userId;
}
}
@@ -1,7 +1,6 @@
package SuMoC.backend.suggestion.services;
import SuMoC.backend.carrousel.service.CarrouselService;
import SuMoC.backend.notification.enums.NotificationType;
import SuMoC.backend.notification.services.NotificationSchedulerService;
import SuMoC.backend.routing.dtos.RouteDTO;
@@ -32,8 +31,6 @@ public class AdHocSuggestionService {
private final NotificationSchedulerService notificationSchedulerService;
private final CarrouselService carrouselService;
/**
* Receives a trip a user has just uploaded, if it is a recent trip and there is a more sustainable alternative,
* schedules a notification to push to the user.
@@ -52,9 +49,6 @@ public class AdHocSuggestionService {
RoutingPreferencesDTO preferencesDTO = routingPreferencesService.getUserRoutingPreferences(newTrip.getUser().getId());
List<RouteDTO> bestAlternatives = pickBestAlternatives(viableAlternatives, preferencesDTO);
// add all viable alternatives to carrousel candidates, so that they can be accessed in the app even after the notification is sent
carrouselService.addAdHocTripCandidates(newTrip, bestAlternatives);
notificationSchedulerService.schedule(
newTrip.getUser().getId(),
bestAlternatives,
@@ -1,11 +1,7 @@
package SuMoC.backend.suggestion.services;
import SuMoC.backend.carrousel.models.CarrouselCandidate;
import SuMoC.backend.carrousel.repository.CarrouselCandidateRepository;
import SuMoC.backend.carrousel.service.CarrouselService;
import SuMoC.backend.h3.H3Service;
import SuMoC.backend.notification.enums.NotificationType;
import SuMoC.backend.notification.interfaces.NotifieableWithTime;
import SuMoC.backend.notification.services.NotificationSchedulerService;
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
import SuMoC.backend.regulartrip.services.RegularTripDetectionService;
@@ -14,28 +10,21 @@ import SuMoC.backend.routing.dtos.RoutingPreferencesDTO;
import SuMoC.backend.routing.services.AlternativeRoutingService;
import SuMoC.backend.routing.services.RoutingPreferencesService;
import SuMoC.backend.suggestion.config.RegularTripSuggestionProperties;
import SuMoC.backend.suggestion.dtos.RouteDTOtoBeNotified;
import com.uber.h3core.util.LatLng;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.time.*;
import java.util.ArrayList;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
@Service
@RequiredArgsConstructor
public class RegularTripSuggestionService {
private static final Logger logger = LoggerFactory.getLogger(RegularTripSuggestionService.class);
private final AlternativeRoutingService alternativeRoutingService;
private final RoutingPreferencesService routingPreferencesService;
@@ -48,13 +37,6 @@ public class RegularTripSuggestionService {
private final H3Service h3Service;
private final CarrouselService carrouselService;
private final CarrouselCandidateRepository carrouselCandidateRepository;
@Qualifier("regularTripSuggestionExecutor")
private final Executor executor;
public void detectAndNotifyRegularTripsForTodaysDayOfWeek() {
// detect
DayOfWeek dayOfWeek = LocalDateTime.now().getDayOfWeek();
@@ -65,68 +47,29 @@ public class RegularTripSuggestionService {
}
public void checkAlternativesAndNotify(HashMap<Long, List<DetectedRegularTripDTO>> detectedRegularTripsByUser) {
logger.info("Processing {} users for regular trip alternatives in parallel", detectedRegularTripsByUser.size());
// Use thread-safe collections for parallel processing
ConcurrentLinkedQueue<CarrouselCandidate> candidatesToPersist = new ConcurrentLinkedQueue<>();
ConcurrentLinkedQueue<NotifieableWithTime> alternativesToNotify = new ConcurrentLinkedQueue<>();
// Create a CompletableFuture for each user to process in parallel
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (Long userId : detectedRegularTripsByUser.keySet()) {
var detectedRegularTrips = detectedRegularTripsByUser.get(userId);
RoutingPreferencesDTO preferencesDTO = routingPreferencesService.getUserRoutingPreferences(userId);
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
processUserTrips(userId, detectedRegularTrips, candidatesToPersist, alternativesToNotify);
} catch (Exception e) {
logger.error("Error processing regular trips for user {}: {}", userId, e.getMessage(), e);
// For each detected regular trip, determine alternatives and notify the user if applicable
for (var detectedRegularTrip : detectedRegularTrips) {
var alternativeRequest = createAlternativeRequest(detectedRegularTrip);
alternativeRequest.setRoutingPreferencesDTO(preferencesDTO);
var bestAlternative = alternativeRoutingService.determineBestAlternativeRouteForRegularTrip(alternativeRequest);
// if present, schedule notification
if (bestAlternative != null) {
notificationSchedulerService.schedule(
userId,
bestAlternative,
NotificationType.REGULAR_TRIP_ALTERNATIVE,
detectedRegularTrip.getArrivalWindowEnd().minusMinutes(properties.getNotifyBeforeMinutes())
);
}
}, executor);
futures.add(future);
}
// Wait for all user processing tasks to complete
CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
allFutures.join();
logger.info("Parallel processing completed. Persisting {} carrousel candidates and scheduling {} notifications",
candidatesToPersist.size(), alternativesToNotify.size());
// Batch save all results
carrouselCandidateRepository.saveAll(candidatesToPersist);
notificationSchedulerService.scheduleAll(new ArrayList<>(alternativesToNotify), NotificationType.REGULAR_TRIP_ALTERNATIVE);
}
/**
* Process all detected regular trips for a single user.
* This method is designed to be called in parallel for multiple users.
*/
private void processUserTrips(Long userId, List<DetectedRegularTripDTO> detectedRegularTrips,
ConcurrentLinkedQueue<CarrouselCandidate> candidatesToPersist,
ConcurrentLinkedQueue<NotifieableWithTime> alternativesToNotify) {
RoutingPreferencesDTO preferencesDTO = routingPreferencesService.getUserRoutingPreferences(userId);
// For each detected regular trip, determine alternatives and notify the user if applicable
for (var detectedRegularTrip : detectedRegularTrips) {
var alternativeRequest = createAlternativeRequest(detectedRegularTrip);
alternativeRequest.setRoutingPreferencesDTO(preferencesDTO);
var bestAlternative = alternativeRoutingService.determineBestAlternativeRouteForRegularTrip(alternativeRequest);
// if present, schedule notification
if (bestAlternative != null) {
// save the alternative in the carrousel candidates so that it can be shown in the carrousel as well
candidatesToPersist.addAll(carrouselService.getRegularTripCandidates(userId, detectedRegularTrip, List.of(bestAlternative)));
LocalTime earliestTimeToSend = detectedRegularTrip.getDepartureWindowStart().minusMinutes(properties.getNotifyBeforeMinutes());
alternativesToNotify.add(new RouteDTOtoBeNotified(bestAlternative, userId, earliestTimeToSend));
}
}
}
private RoutingAlternativeRequestDTO createAlternativeRequest(DetectedRegularTripDTO trip) {
LatLng origin = h3Service.cellToLatLng(trip.getStartH3Center());
LatLng destination = h3Service.cellToLatLng(trip.getEndH3Center());
@@ -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();
};
}
}
@@ -10,7 +10,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.time.*;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@@ -37,12 +39,7 @@ public class StatTableUpdateService {
LocalDate weekEnd = weekStart.plusWeeks(1);
LocalDateTime startDateTime = weekStart.atStartOfDay();
LocalDateTime endDateTime = weekEnd.atStartOfDay();
// Convert LocalDateTime to Instant
Instant startInstant = startDateTime.atZone(ZoneId.systemDefault()).toInstant();
Instant endInstant = endDateTime.atZone(ZoneId.systemDefault()).toInstant();
List<Trip> trips = tripRepository.findValidTripsInWeek(startInstant, endInstant);
List<Trip> trips = tripRepository.findValidTripsInWeek(startDateTime, endDateTime);
// Groupy trips by userId
// TODO verify that we correctly set up the repository find method to avoid querying each trip's user separately (N+1 problem)
@@ -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,41 +23,6 @@ public class TripFactory {
return modalities[ThreadLocalRandom.current().nextInt(modalities.length)];
}
/**
* A dto for a car route for there have to be better sustainable alternatives available.
*
* @param startTime
* @return
*/
public static NewTripDTO newTriggeringCarMock(Instant startTime) {
String startPlace = "Essen Schuetzenbahn";
String endPlace = "Essen Hbf";
Set<NewTripSegmentDTO> segments = Set.of(
NewTripSegmentDTO.builder()
.modality(Modality.CAR)
.startTime(startTime)
.distanceMeters(5000)
.build()
);
return NewTripDTO.builder()
.startPlace(startPlace)
.endPlace(endPlace)
// Actual coordinates
.startLatitude(51.45916748046875)
.startLongitude(7.014928340911865)
.endLatitude(51.451515197753906)
.endLongitude(7.01484489440918)
.co2Emissions(20.0)
.startTime(startTime)
.endTime(startTime.plus(Duration.ofMinutes(60)))
.mobilityScore(50.0f)
.tripSegments(segments)
.build();
}
public static NewTripDTO newCarTripDTO(Instant startTime) {
String startPlace = "Cologne";
String endPlace = "Düsseldorf";
@@ -9,6 +9,7 @@ import org.springframework.data.repository.query.Param;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
@@ -21,7 +22,7 @@ public interface TripRepository extends JpaRepository<Trip, Long> {
"JOIN FETCH trip.user " +
"JOIN FETCH trip.tripSegments " +
"WHERE trip.invalidated = false AND trip.startTime >= :start AND trip.startTime < :end")
List<Trip> findValidTripsInWeek(@Param("start") Instant start, @Param("end") Instant end);
List<Trip> findValidTripsInWeek(@Param("start") LocalDateTime start, @Param("end") LocalDateTime end);
default List<Trip> findAllValidFromDateWithMainModalityOnCertainWeekday(
Instant fromDate,
@@ -1,6 +1,5 @@
package SuMoC.backend.user.controller;
import SuMoC.backend.images.ImageRequestDTO;
import SuMoC.backend.security.dtos.LoginResponseDTO;
import SuMoC.backend.user.dtos.*;
import SuMoC.backend.user.enums.VisibilityPrivacy;
@@ -174,19 +173,16 @@ public class UserController {
StatScope scope = body.getScope();
boolean awardBadges = body.getAwardBadges() == null || body.getAwardBadges();
boolean awardChallenges = body.getAwardChallenges() == null || body.getAwardChallenges();
this.statsService.addStatsToCurrentUser(
body.getStat(),
body.getValue(),
scope,
awardBadges,
awardChallenges
awardBadges
);
return ResponseEntity.ok().build();
}
@Operation(summary = "get stats of current user",
description = "Returns all stats of a user")
@ApiResponses(value = {
@@ -215,9 +211,9 @@ public class UserController {
content = @Content(mediaType = "application/json"))
})
@PutMapping("/setProfilePicture/{id}")
public ResponseEntity<Void> setProfilePicture(@RequestBody ImageRequestDTO base64ProfilePicture,
public ResponseEntity<Void> setProfilePicture(@RequestParam String base64ProfilePicture,
@PathVariable @NotNull Long id) {
this.userService.setProfilePicture(id, base64ProfilePicture.getBase64ProfilePicture());
this.userService.setProfilePicture(id, base64ProfilePicture);
return ResponseEntity.ok().build();
}
@@ -230,27 +226,12 @@ public class UserController {
@ApiResponse(responseCode = "404", description = "The user does not exist")
})
@GetMapping("/getProfilePicture/{id}")
public ResponseEntity<ImageRequestDTO> getProfilePicture(@PathVariable @NotNull Long id) {
ImageRequestDTO imageData = userService.getProfilePicture(id);
public ResponseEntity<String> getProfilePicture(@PathVariable @NotNull Long id) {
String imageData = userService.getProfilePicture(id);
return ResponseEntity.ok()
.contentType(MediaType.IMAGE_JPEG)
.cacheControl(CacheControl.maxAge(365, TimeUnit.DAYS))
.body(imageData);
}
@Operation(summary = "Get the users own xp", description = "A user can get their own xp.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "XP successfully retrieved",
content = @Content(mediaType = "application/json")),
@ApiResponse(responseCode = "403", description = "Not authorized",
content = @Content(mediaType = "application/json")),
@ApiResponse(responseCode = "404", description = "The user does not exist",
content = @Content(mediaType = "application/json"))
})
@GetMapping("/getTotalXP")
public ResponseEntity<Long> getTotalXP() {
Long xp = userService.getTotalXP();
return ResponseEntity.ok().body(xp);
}
}
@@ -17,8 +17,6 @@ public class AddStatRequestDTO {
private Boolean awardBadges;
private Boolean awardChallenges;
public String getStat() { return stat; }
public void setStat(String stat) { this.stat = stat; }
@@ -30,8 +28,5 @@ public class AddStatRequestDTO {
public void setAwardBadges(Boolean awardBadges) { this.awardBadges = awardBadges; }
public StatScope getScope() { return scope; }
public void setScope(StatScope scope) { this.scope = scope; }
public Boolean getAwardChallenges() { return awardChallenges; }
public void setAwardChallenges(Boolean awardChallenges) { this.awardChallenges = awardChallenges; }
}
@@ -1,8 +1,6 @@
package SuMoC.backend.user.service;
import SuMoC.backend.gamification.Timeframe;
import SuMoC.backend.images.ImageBase64Util;
import SuMoC.backend.images.ImageRequestDTO;
import SuMoC.backend.security.dtos.LoginResponseDTO;
import SuMoC.backend.security.services.TokenService;
import SuMoC.backend.trip.TripMapper;
@@ -235,7 +233,7 @@ public class UserService {
}
public ImageRequestDTO getProfilePicture(Long id) {
public String getProfilePicture(Long id) {
User sender = currentUser.get();
User user = userRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(
@@ -251,12 +249,6 @@ public class UserService {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Kein Profilbild vorhanden.");
}
return new ImageRequestDTO(ImageBase64Util.encode(user.getProfileImage().getImageData()));
}
public Long getTotalXP() {
User sender = currentUser.get();
return sender.getStats().getStatValue(Timeframe.TOTAL,"XP");
return ImageBase64Util.encode(user.getProfileImage().getImageData());
}
}
@@ -2,7 +2,6 @@ package SuMoC.backend.user.stats;
import SuMoC.backend.gamification.Timeframe;
import SuMoC.backend.gamification.badges.BadgeService;
import SuMoC.backend.gamification.challenges.ChallengeService;
import SuMoC.backend.user.dtos.StatScope;
import SuMoC.backend.user.models.User;
import SuMoC.backend.user.repository.UserRepository;
@@ -22,17 +21,14 @@ public class StatsService {
@Autowired
private UserRepository userRepository;
private final BadgeService badgeService;
private final ChallengeService challengeService;
private final CurrentUserService currentUserService;
public StatsService(CurrentUserService currentUserService,
UserRepository userRepository,
BadgeService badgeService,
ChallengeService challengeService) {
BadgeService badgeService) {
this.currentUserService = currentUserService;
this.userRepository = userRepository;
this.badgeService = badgeService;
this.challengeService = challengeService;
}
@Scheduled(cron = "0 0 0 ? * MON")
@@ -64,7 +60,7 @@ public class StatsService {
);
@Transactional
public void addStatsToCurrentUser(String statField, long value, StatScope scope, boolean awardBadges, boolean awardChallenges) {
public void addStatsToCurrentUser(String statField, long value, StatScope scope, boolean awardBadges) {
if (!ALLOWED_STATS.contains(statField)) {
throw new ResponseStatusException(
HttpStatus.BAD_REQUEST,
@@ -93,10 +89,6 @@ public class StatsService {
if (awardBadges) {
badgeService.checkAndAwardBadges();
}
if (awardChallenges) {
challengeService.checkAndAwardChallenges(statField, value);
}
}
public StatsList getStats() {
+2 -10
View File
@@ -16,20 +16,12 @@ sumoc.scheduling.run-notification-worker=*/15 * * * * *
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 * * *
# Regular trip suggestion settings
sumoc.regulartripsuggestion.parallelism=5
sumoc.regulartripsuggestion.notify-before-minutes=15
# 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
# Notification limits per hour TODO for development we set them extremly high
sumoc.notification.max-notifications-per-hour-per-type.adhoc-alternative=10000
sumoc.notification.max-notifications-per-hour-per-type.friendship-request-received=10000
sumoc.notification.max-notifications-per-hour-per-type.trend=10000
sumoc.notification.max-notifications-per-hour-per-type.regular-trip-alternative=10000
# Base URL to external services
carta.base-url=https://www.innamoruhr.de/c2
# Geocoding configuration
@@ -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,251 +0,0 @@
package SuMoC.backend.user.service;
import SuMoC.backend.gamification.challenges.ChallengeRepository;
import SuMoC.backend.gamification.challenges.ChallengeService;
import SuMoC.backend.gamification.challenges.Models.Challenge;
import SuMoC.backend.gamification.challenges.Models.ChallengeDTO;
import SuMoC.backend.images.ImageBase64Util;
import SuMoC.backend.user.models.User;
import SuMoC.backend.user.repository.UserRepository;
import jakarta.transaction.Transactional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.web.server.ResponseStatusException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static SuMoC.backend.Factories.UserTestFactory.uniqueUser;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
@ActiveProfiles("test")
@Transactional
public class ChallengeServiceTest {
@Autowired
private ChallengeService challengeService;
@Autowired
private ChallengeRepository challengeRepository;
@Autowired
private UserRepository userRepository;
private List<ChallengeDTO> challengeDTOList = new ArrayList<>();
private User sender;
@BeforeEach
void setUp() {
sender = userRepository.save(uniqueUser(1));
// without criteria
for(int i = 0; i < 5; i++) {
ChallengeDTO challengeDTO = new ChallengeDTO();
challengeDTO.setName("badgeName" + i);
challengeDTO.setDescription("badgeDescription" + i);
challengeDTO.setReward(i);
ChallengeDTO created = challengeService.createChallenge(challengeDTO);
challengeDTOList.add(created);
}
// with criteria and image
String dummyBase64 = ImageBase64Util.encode(new byte[]{1, 2, 3, 4, 5});
for(int i = 5; i < 10; i++) {
ChallengeDTO challengeDTO = new ChallengeDTO();
challengeDTO.setName("badgeName" + i);
challengeDTO.setDescription("badgeDescription" + i);
challengeDTO.setCriteria(new HashMap<>(Map.of("XP", (i * 10))));
challengeDTO.setReward(i);
challengeDTO.setBase64image(dummyBase64);
ChallengeDTO created = challengeService.createChallenge(challengeDTO);
challengeDTOList.add(created);
}
}
@Test
@WithMockUser(username = "test1@test.de", roles = {"USER"})
public void testCreateChallenge() {
List<Challenge> reproChallenges = challengeRepository.findAll();
assertNotNull(reproChallenges);
assertEquals(10, reproChallenges.size());
reproChallenges.forEach(challenge -> {
ChallengeDTO dto = challengeDTOList.stream()
.filter(c -> c.getName().equals(challenge.getName()))
.findFirst()
.orElse(null);
assertNotNull(dto);
assertEquals(dto.getId(), challenge.getId());
assertEquals(dto.getName(), challenge.getName());
assertEquals(dto.getDescription(), challenge.getDescription());
assertEquals(dto.getCriteria(), challenge.getCriteria());
assertEquals(dto.getReward(), challenge.getReward());
if (dto.getBase64image() != null) {
assertNotNull(challenge.getImage());
assertEquals(dto.getBase64image(),
ImageBase64Util.encode(challenge.getImage().getImageData()));
} else {
assertNull(challenge.getImage());
}
});
}
@Test
@WithMockUser(username = "test1@test.de", roles = {"USER"})
public void testGetChallenge() {
// 1. ALL
List<ChallengeDTO> allChallenges = challengeService.getAllChallenges();
assertNotNull(allChallenges);
assertEquals(10, allChallenges.size());
allChallenges.forEach(challenge -> {
ChallengeDTO dto = challengeDTOList.stream()
.filter(c -> c.getName().equals(challenge.getName()))
.findFirst()
.orElse(null);
assertNotNull(dto);
assertEquals(dto.getId(), challenge.getId());
assertEquals(dto.getName(), challenge.getName());
assertEquals(dto.getDescription(), challenge.getDescription());
assertEquals(dto.getCriteria(), challenge.getCriteria());
assertEquals(dto.getReward(), challenge.getReward());
assertEquals(dto.getBase64image(), challenge.getBase64image());
});
// 2. BY ID
allChallenges.forEach(challenge -> {
ChallengeDTO dto = challengeService.getChallengeById(challenge.getId());
assertNotNull(dto);
assertEquals(dto.getId(), challenge.getId());
assertEquals(dto.getName(), challenge.getName());
assertEquals(dto.getDescription(), challenge.getDescription());
assertEquals(dto.getCriteria(), challenge.getCriteria());
assertEquals(dto.getReward(), challenge.getReward());
assertEquals(dto.getBase64image(), challenge.getBase64image());
});
// 3. non-existing
ResponseStatusException getException = assertThrows(
ResponseStatusException.class,
() -> challengeService.getChallengeById(999L)
);
assertEquals(HttpStatus.NOT_FOUND, getException.getStatusCode());
assertEquals("Challenge not found", getException.getReason());
}
@Test
@WithMockUser(username = "test1@test.de", roles = {"USER"})
public void testModifyChallenge() {
List<ChallengeDTO> allChallenges = challengeService.getAllChallenges();
ChallengeDTO toModify = allChallenges.get(0);
toModify.setName("ModifiedName");
toModify.setDescription("ModifiedDescription");
toModify.setCriteria(new HashMap<>(Map.of("XP", 1000)));
toModify.setReward(1000);
ChallengeDTO modified = challengeService.modifyChallenge(toModify);
assertNotNull(modified);
assertEquals(toModify.getId(), modified.getId());
assertEquals("ModifiedName", modified.getName());
assertEquals("ModifiedDescription", modified.getDescription());
assertEquals(new HashMap<>(Map.of("XP", 1000)), modified.getCriteria());
assertEquals(1000, modified.getReward());
Challenge inRepo = challengeRepository.findById(modified.getId()).orElse(null);
assertNotNull(inRepo);
assertEquals(modified.getId(), inRepo.getId());
assertEquals("ModifiedName", inRepo.getName());
assertEquals("ModifiedDescription", inRepo.getDescription());
assertEquals(new HashMap<>(Map.of("XP", 1000)), inRepo.getCriteria());
assertEquals(1000, inRepo.getReward());
// non-existing
ChallengeDTO nonExisting = new ChallengeDTO();
nonExisting.setId(999L);
nonExisting.setName("x");
nonExisting.setDescription("y");
nonExisting.setCriteria(new HashMap<>(Map.of("XP", 1000)));
nonExisting.setReward(0);
ResponseStatusException ex = assertThrows(
ResponseStatusException.class,
() -> challengeService.modifyChallenge(nonExisting)
);
assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
assertEquals("Challenge not found", ex.getReason());
}
@Test
@WithMockUser(username = "test1@test.de", roles = {"USER"})
public void testDeleteChallenge() {
List<ChallengeDTO> allChallenges = challengeService.getAllChallenges();
for(ChallengeDTO challenge : allChallenges) {
challengeService.deleteChallenge(challenge.getId());
}
List<ChallengeDTO> afterDelete = challengeService.getAllChallenges();
assertTrue(afterDelete.isEmpty());
// non-existing
ResponseStatusException deleteException = assertThrows(
ResponseStatusException.class,
() -> challengeService.deleteChallenge(999L)
);
assertEquals(HttpStatus.NOT_FOUND, deleteException.getStatusCode());
assertEquals("Challenge not found", deleteException.getReason());
}
@Test
@WithMockUser(username = "test1@test.de", roles = {"USER"})
public void testGetAvailableChallenges() {
challengeService.weeklyChallengeScheduler();
challengeDTOList = challengeService.getAllChallenges();
List<ChallengeDTO> availableChallenges = challengeService.getAvailableChallenges();
assertNotNull(availableChallenges);
assertEquals(3, availableChallenges.size());
availableChallenges.forEach(challenge -> {
assertTrue(challengeDTOList.stream()
.anyMatch(c -> c.getId().equals(challenge.getId()))
);
assertNotNull(challenge.getCriteria());
});
// Deactivate one
Long activeId = availableChallenges.get(0).getId();
challengeService.deactivateChallenge(activeId);
availableChallenges = challengeService.getAvailableChallenges();
assertEquals(2, availableChallenges.size());
// Activate one
challengeService.activateChallenge(activeId);
availableChallenges = challengeService.getAvailableChallenges();
assertNotNull(availableChallenges);
assertEquals(3, availableChallenges.size());
}
}
@@ -196,7 +196,7 @@ public class UserServiceTest {
userService.setProfilePicture(sender.getId(), base64Image);
// Get profile picture
String profilePicture = userService.getProfilePicture(sender.getId()).getBase64ProfilePicture();
String profilePicture = userService.getProfilePicture(sender.getId());
assertNotNull(profilePicture);
assertEquals(base64Image.getBytes().length, profilePicture.length());
assertEquals(base64Image, profilePicture);
@@ -214,7 +214,7 @@ public class UserServiceTest {
userRepository.save(anotherUser);
byte[] secondImage = new byte[]{10,20,30,40,50};
anotherUser.getProfileImage().setImageData(secondImage);
byte[] profilePicture2 = ImageBase64Util.decode(userService.getProfilePicture(anotherUser.getId()).getBase64ProfilePicture());
byte[] profilePicture2 = ImageBase64Util.decode(userService.getProfilePicture(anotherUser.getId()));
assertNotNull(profilePicture2);
assertEquals(secondImage.length, profilePicture2.length);
assertArrayEquals(secondImage, profilePicture2);