Compare commits
189
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
932fc88b2e | ||
|
|
7c347caea9 | ||
|
|
29fb04d6ec | ||
|
|
82014b1d9c | ||
|
|
57e9beb33f | ||
|
|
30de34b47a | ||
|
|
007680fccf | ||
|
|
cf7d847993 | ||
|
|
dad0077279 | ||
|
|
0bc692d64a | ||
|
|
16bf41beaa | ||
|
|
98cb2536a2 | ||
|
|
776b8857b6 | ||
|
|
b6ce9a73ce | ||
|
|
906050ad89 | ||
|
|
46a6b2fb7a | ||
|
|
e333b3b9ce | ||
|
|
b64eff7ae6 | ||
|
|
f04e5d7c06 | ||
|
|
4fb02a3f69 | ||
|
|
e1f8cf123b | ||
|
|
cc6028bab5 | ||
|
|
80ba4c33b6 | ||
|
|
3d4f6a4d26 | ||
|
|
2c0dfaf77b | ||
|
|
3051bda1e4 | ||
|
|
a2acdd88f8 | ||
|
|
9e41239ef8 | ||
|
|
8d65e35f88 | ||
|
|
8f62d853e4 | ||
|
|
d5c8342729 | ||
|
|
9d5ad0ca6d | ||
|
|
a2aa22a34a | ||
|
|
82ddcb193c | ||
|
|
8b2de7b9c3 | ||
|
|
c165fce833 | ||
|
|
20d948bcdf | ||
|
|
1b549cc5fc | ||
|
|
18e8d10f6b | ||
|
|
e84269390e | ||
|
|
5eb157b435 | ||
|
|
b95355c10f | ||
|
|
f7d7f6bc53 | ||
|
|
a401b9a6c1 | ||
|
|
cc6990a2a1 | ||
|
|
f88f5a03ef | ||
|
|
d5ef781162 | ||
|
|
1c6caa71ce | ||
|
|
b1ac1619d2 | ||
|
|
6f9f7c1ba0 | ||
|
|
f961b3c2b3 | ||
|
|
2d39c0bef8 | ||
|
|
1a8961831f | ||
|
|
82017e3c50 | ||
|
|
f0dd32c22f | ||
|
|
99b5882c82 | ||
|
|
b60e900e24 | ||
|
|
fb41f80061 | ||
|
|
e2a6b5919a | ||
|
|
60d335f16d | ||
|
|
4fe86b6845 | ||
|
|
c43101e5dc | ||
|
|
d882c8e3b3 | ||
|
|
14cb4f4f88 | ||
|
|
e5e6dc9e2a | ||
|
|
8eaea03b47 | ||
|
|
ff4d352e08 | ||
|
|
657acbc736 | ||
|
|
6393a4a650 | ||
|
|
cb397e7e63 | ||
|
|
69347f8f56 | ||
|
|
e68e163214 | ||
|
|
5e16591913 | ||
|
|
6aaff14c0d | ||
|
|
1b39185454 | ||
|
|
43ab63f77d | ||
|
|
d72a12d089 | ||
|
|
39e385cac3 | ||
|
|
e41fff0840 | ||
|
|
256145f65b | ||
|
|
c636d04fea | ||
|
|
5490958d6e | ||
|
|
06b35c13b6 | ||
|
|
48063d442c | ||
|
|
29b6ac052f | ||
|
|
c3f291a08b | ||
|
|
30fe944387 | ||
|
|
43cf5239fc | ||
|
|
53cfce5359 | ||
|
|
fb94421247 | ||
|
|
4567ca16f0 | ||
|
|
88fcbfb728 | ||
|
|
400c31cc34 | ||
|
|
a8f95b680a | ||
|
|
f051efa9eb | ||
|
|
522393bdd7 | ||
|
|
768acc1841 | ||
|
|
7bbbf903de | ||
|
|
850410ec46 | ||
|
|
85ca90fa7c | ||
|
|
46a8ca67a0 | ||
|
|
a691e911a2 | ||
|
|
c6fe80145b | ||
|
|
5b6cc1c679 | ||
|
|
43e91670b3 | ||
|
|
e2e1cc48a0 | ||
|
|
0564733c39 | ||
|
|
9aed0a2703 | ||
|
|
fb0989ef95 | ||
|
|
607ce804da | ||
|
|
72efa472fa | ||
|
|
23e5affa71 | ||
|
|
9b475a37e1 | ||
|
|
fb49fa2130 | ||
|
|
00cbff062e | ||
|
|
edabef4fb3 | ||
|
|
75af061871 | ||
|
|
b4d6c1ea13 | ||
|
|
cd07bf16cf | ||
|
|
de2f7af6c7 | ||
|
|
a2be274ca3 | ||
|
|
cc15245680 | ||
|
|
0d7f97af5e | ||
|
|
ebc5de34cd | ||
|
|
c117b7a049 | ||
|
|
c61d870173 | ||
|
|
d56bdd97d7 | ||
|
|
8e0c2cfc3e | ||
|
|
321b7c8035 | ||
|
|
b18878fcb2 | ||
|
|
0cdf4a09f3 | ||
|
|
e7b6295dad | ||
|
|
3c83274d4f | ||
|
|
6b56ecb5cb | ||
|
|
add016b51e | ||
|
|
98d940625b | ||
|
|
2af94e6b65 | ||
|
|
7253576a53 | ||
|
|
a0a3dd4e28 | ||
|
|
3f60692987 | ||
|
|
f39d24e2d1 | ||
|
|
94858282da | ||
|
|
6c4a2f7176 | ||
|
|
90a3297873 | ||
|
|
846bbbbea6 | ||
|
|
218ceeada3 | ||
|
|
923a123f33 | ||
|
|
6f407a26fd | ||
|
|
1a15dd5a60 | ||
|
|
76e9251001 | ||
|
|
fb9276ca15 | ||
|
|
4c1476944a | ||
|
|
abb8211e16 | ||
|
|
8e4d6bf820 | ||
|
|
917ed77a95 | ||
|
|
59a43be9ee | ||
|
|
14e77cbf0f | ||
|
|
5d695b35ba | ||
|
|
72828c9a0d | ||
|
|
c70059b366 | ||
|
|
3a1752573e | ||
|
|
2eab549360 | ||
|
|
2b9ce78e1c | ||
|
|
159c03142a | ||
|
|
f3bd4dddc2 | ||
|
|
a78ebbfbb5 | ||
|
|
2f88a611b8 | ||
|
|
8d0210b210 | ||
|
|
7986f39d36 | ||
|
|
c8410a8231 | ||
|
|
95e496ab85 | ||
|
|
140945dbc2 | ||
|
|
106bdbe220 | ||
|
|
7098fbe8cc | ||
|
|
9f854ce3ab | ||
|
|
d099909aab | ||
|
|
b08d9dd22d | ||
|
|
56e594b625 | ||
|
|
8ee6992f88 | ||
|
|
ddbf925caf | ||
|
|
41f04620ba | ||
|
|
ce665d143f | ||
|
|
51c742b746 | ||
|
|
11ce10a8d8 | ||
|
|
521a4ba957 | ||
|
|
bc3dd9b59b | ||
|
|
06aa0ce3cc | ||
|
|
bef418d77d | ||
|
|
ba642d10a5 |
@@ -41,3 +41,7 @@ build/
|
||||
### Secrets ###
|
||||
src/main/resources/firebase-private-key.json
|
||||
src/main/resources/firebase-private-key_disable.json
|
||||
/secrets/fcm-key.json
|
||||
/data/keys/jwt-public.pem
|
||||
/data/keys/jwt-private.pem
|
||||
/logs/app.log
|
||||
|
||||
+9
-2
@@ -17,5 +17,12 @@ COPY --from=build /app/target/*SNAPSHOT.jar app.jar
|
||||
# Port freigeben
|
||||
EXPOSE 8080
|
||||
|
||||
# App starten
|
||||
CMD ["java", "-jar", "app.jar"]
|
||||
# Copy entrypoint script
|
||||
COPY entrypoint.sh .
|
||||
RUN chmod +x entrypoint.sh
|
||||
|
||||
# Copy secrets
|
||||
COPY secrets/ ./secrets/
|
||||
|
||||
# Start entrypoint first for key decryption
|
||||
ENTRYPOINT ["./entrypoint.sh"]
|
||||
Vendored
+14
-1
@@ -16,16 +16,29 @@ node('built-in') {
|
||||
// deploy the build output on the server
|
||||
stage ('Deploy') {
|
||||
if (env.BRANCH_NAME == "deploy") {
|
||||
withCredentials([sshUserPrivateKey(credentialsId: "sumoc-server-key", keyFileVariable: "KEYFILE")]) {
|
||||
withCredentials([
|
||||
sshUserPrivateKey(credentialsId: "sumoc-server-key", keyFileVariable: "KEYFILE")
|
||||
// file(credentialsId: "firebase-messaging-key", variable: "FIREBASE_MESSAGING_KEYFILE")
|
||||
]) {
|
||||
echo "Copy docker images to server ..."
|
||||
sh 'scp -i $KEYFILE .env pg-sumoc@apps-dev.nes:~'
|
||||
sh 'scp -i $KEYFILE docker-compose.yml pg-sumoc@apps-dev.nes:~'
|
||||
sh 'scp -i $KEYFILE docker-load.sh pg-sumoc@apps-dev.nes:~'
|
||||
sh 'scp -i $KEYFILE -r docker_images pg-sumoc@apps-dev.nes:~'
|
||||
echo "Resetting database..."
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose down -v"'
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"'
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm -f sumoc-backend_postgres_data"'
|
||||
echo "Load docker images on server ..."
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"'
|
||||
echo "Restarting docker containers on server ..."
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "sudo systemctl restart sumoc-docker"'
|
||||
echo "Waiting for containers to start..."
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "sleep 10 && docker ps"'
|
||||
echo "Database logs:"
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker logs sumoc_db"'
|
||||
echo "Backend logs:"
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker logs sumoc-backend"'
|
||||
}
|
||||
} else {
|
||||
echo "Skipping deployment for non-deploy branch."
|
||||
|
||||
+11
-11
@@ -16,14 +16,14 @@ services:
|
||||
- "5432:5432"
|
||||
restart: always
|
||||
|
||||
nominatim:
|
||||
image: mediagis/nominatim:5.2
|
||||
container_name: nominatim
|
||||
environment:
|
||||
PBF_URL: https://download.geofabrik.de/europe/germany/nordrhein-westfalen-latest.osm.pbf
|
||||
REPLICATION_ENABLED: false
|
||||
volumes:
|
||||
- nominatim-data:/var/lib/postgresql/14/main
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "6666:8080"
|
||||
# nominatim:
|
||||
# image: mediagis/nominatim:5.2
|
||||
# container_name: nominatim
|
||||
# environment:
|
||||
# PBF_URL: https://download.geofabrik.de/europe/germany/nordrhein-westfalen-latest.osm.pbf
|
||||
# REPLICATION_ENABLED: false
|
||||
# volumes:
|
||||
# - nominatim-data:/var/lib/postgresql/14/main
|
||||
# restart: unless-stopped
|
||||
# ports:
|
||||
# - "6666:8080"
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
volumes:
|
||||
nominatim-data:
|
||||
postgres_data:
|
||||
|
||||
services:
|
||||
backend:
|
||||
build: .
|
||||
image: backend:latest
|
||||
container_name: sumoc-backend
|
||||
ports:
|
||||
- "8080:8080"
|
||||
env_file:
|
||||
- .env
|
||||
depends_on:
|
||||
- db
|
||||
restart: unless-stopped
|
||||
|
||||
db:
|
||||
image: postgres:16.2-alpine
|
||||
container_name: sumoc_db
|
||||
environment:
|
||||
- POSTGRES_USER=postgres
|
||||
- POSTGRES_PASSWORD=admin
|
||||
- POSTGRES_DB=sumoc
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
ports:
|
||||
- "5432:5432"
|
||||
restart: always
|
||||
|
||||
nominatim:
|
||||
image: mediagis/nominatim:5.2
|
||||
container_name: nominatim
|
||||
environment:
|
||||
PBF_URL: https://download.geofabrik.de/europe/germany/nordrhein-westfalen-latest.osm.pbf
|
||||
REPLICATION_ENABLED: false
|
||||
volumes:
|
||||
- nominatim-data:/var/lib/postgresql/14/main
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "6666:8080"
|
||||
+30
-12
@@ -1,6 +1,7 @@
|
||||
volumes:
|
||||
nominatim-data:
|
||||
postgres_data:
|
||||
jwt_keys:
|
||||
# nominatim-data:
|
||||
|
||||
services:
|
||||
backend:
|
||||
@@ -11,6 +12,22 @@ services:
|
||||
- "8080:8080"
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
TZ: Europe/Berlin
|
||||
FCM_DECRYPTION_KEY: ${FCM_DECRYPTION_KEY}
|
||||
RSA_PRIVATE_KEY_PATH: /data/keys/jwt-private.pem
|
||||
RSA_PUBLIC_KEY_PATH: /data/keys/jwt-public.pem
|
||||
volumes:
|
||||
- jwt_keys:/data/keys
|
||||
depends_on:
|
||||
- db
|
||||
restart: unless-stopped
|
||||
|
||||
adminer:
|
||||
image: adminer:5.4.1-standalone
|
||||
container_name: sumoc-adminer
|
||||
ports:
|
||||
- "8079:8080"
|
||||
depends_on:
|
||||
- db
|
||||
restart: unless-stopped
|
||||
@@ -19,6 +36,7 @@ services:
|
||||
image: postgres:16.2-alpine
|
||||
container_name: sumoc_db
|
||||
environment:
|
||||
- TZ=Europe/Berlin
|
||||
- POSTGRES_USER=postgres
|
||||
- POSTGRES_PASSWORD=admin
|
||||
- POSTGRES_DB=sumoc
|
||||
@@ -28,14 +46,14 @@ services:
|
||||
- "5432:5432"
|
||||
restart: always
|
||||
|
||||
nominatim:
|
||||
image: mediagis/nominatim:5.2
|
||||
container_name: nominatim
|
||||
environment:
|
||||
PBF_URL: https://download.geofabrik.de/europe/germany/nordrhein-westfalen-latest.osm.pbf
|
||||
REPLICATION_ENABLED: false
|
||||
volumes:
|
||||
- nominatim-data:/var/lib/postgresql/14/main
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "6666:8080"
|
||||
# nominatim:
|
||||
# image: mediagis/nominatim:5.2
|
||||
# container_name: nominatim
|
||||
# environment:
|
||||
# PBF_URL: https://download.geofabrik.de/europe/germany/nordrhein-westfalen-latest.osm.pbf
|
||||
# REPLICATION_ENABLED: false
|
||||
# volumes:
|
||||
# - nominatim-data:/var/lib/postgresql/14/main
|
||||
# restart: unless-stopped
|
||||
# ports:
|
||||
# - "6666:8080"
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
|
||||
# Decrypt secrets if key is provided
|
||||
if [ -z "$FCM_DECRYPTION_KEY" ]; then
|
||||
echo "No decryption key provided, skipping decryption."
|
||||
else
|
||||
echo "Decryption key provided, decrypting secrets..."
|
||||
openssl enc -d -aes-256-cbc -pbkdf2 -in ./secrets/fcm-key.json.enc -out ./secrets/fcm-key.json -k "$FCM_DECRYPTION_KEY"
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "Decryption failed!"
|
||||
exit 1
|
||||
fi
|
||||
echo "Decryption successful."
|
||||
fi
|
||||
|
||||
exec java -jar app.jar
|
||||
+1
-1
@@ -19,7 +19,7 @@ curl http://localhost:8080/v3/api-docs.yaml -o openapi.yaml
|
||||
|
||||
# 3. Swift-Client generieren
|
||||
echo "Generiere Swift-Client..."
|
||||
openapi-generator-cli generate -i openapi.yaml -g swift5 -o app/ios-api
|
||||
openapi-generator-cli generate -i openapi.yaml -g swift5 -o app/ios-api --additional-properties=useClasses=true
|
||||
|
||||
# 4. Kotlin-Client generieren
|
||||
echo "Generiere Kotlin-Client..."
|
||||
|
||||
+1932
-80
File diff suppressed because it is too large
Load Diff
@@ -54,6 +54,10 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# Workflow
|
||||
|
||||
1. Encrypt key locally ```openssl enc -aes-256-cbc -pbkdf2 -salt -in KEY.json -out KEY.json.enc```
|
||||
2. Provide decryption password during runtime as env var via docker compose
|
||||
3. Decrypt key in entrypoint script
|
||||
|
||||
## Decrypt locally for development
|
||||
|
||||
```openssl enc -d -aes-256-cbc -pbkdf2 -in KEY.json.enc -out KEY.json```
|
||||
Binary file not shown.
@@ -0,0 +1,20 @@
|
||||
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;
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
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()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
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;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package SuMoC.backend.carrousel.dto;
|
||||
|
||||
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
|
||||
import SuMoC.backend.regulartrip.dtos.MinimalDetectedRegularTripDTO;
|
||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public class RegularTripAlternativeContext extends RouteAlternativeContext {
|
||||
|
||||
private final MinimalDetectedRegularTripDTO detectedRegularTrip;
|
||||
|
||||
public RegularTripAlternativeContext(RouteDTO alternative, MinimalDetectedRegularTripDTO detectedRegularTrip) {
|
||||
super(alternative, CarrouselCandidateType.REGULAR_TRIP_ALTERNATIVE);
|
||||
this.detectedRegularTrip = detectedRegularTrip;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package SuMoC.backend.carrousel.enums;
|
||||
|
||||
public enum CarrouselCandidateType {
|
||||
ADHOC_ALTERNATIVE,
|
||||
REGULAR_TRIP_ALTERNATIVE,
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
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);
|
||||
|
||||
void deleteAllByUserId(Long userId);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
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.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 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;
|
||||
|
||||
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();
|
||||
|
||||
return new RegularTripAlternativeContext(
|
||||
candidate.getSuggestedAlternative(),
|
||||
minRegularTrip
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,7 @@ public class CartaClient {
|
||||
origin,
|
||||
destination,
|
||||
mode.toLowerCase(), // possible values: walking, driving, cycling
|
||||
arrivalTime.getEpochSecond(),
|
||||
arrivalTime != null ? arrivalTime.getEpochSecond() : null,
|
||||
departureTime != null ? departureTime.getEpochSecond() : null,
|
||||
alternatives,
|
||||
walkingSpeed,
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package SuMoC.backend.carta;
|
||||
|
||||
public interface DirectionsRequest {
|
||||
|
||||
Double getOriginLat();
|
||||
|
||||
void setOriginLat(Double originLat);
|
||||
|
||||
Double getOriginLon();
|
||||
|
||||
void setOriginLon(Double originLon);
|
||||
|
||||
Double getDestinationLat();
|
||||
|
||||
void setDestinationLat(Double destinationLat);
|
||||
|
||||
Double getDestinationLon();
|
||||
|
||||
void setDestinationLon(Double destinationLon);
|
||||
|
||||
java.time.Instant getArrivalTime();
|
||||
|
||||
void setArrivalTime(java.time.Instant arrivalTime);
|
||||
|
||||
java.time.Instant getDepartureTime();
|
||||
|
||||
void setDepartureTime(java.time.Instant departureTime);
|
||||
|
||||
SuMoC.backend.routing.dtos.RoutingPreferencesDTO getRoutingPreferencesDTO();
|
||||
|
||||
void setRoutingPreferencesDTO(SuMoC.backend.routing.dtos.RoutingPreferencesDTO routingPreferencesDTO);
|
||||
}
|
||||
+228
-174
@@ -1,15 +1,12 @@
|
||||
package SuMoC.backend.routing.services;
|
||||
package SuMoC.backend.carta;
|
||||
|
||||
import SuMoC.backend.carta.CartaClient;
|
||||
import SuMoC.backend.geocoding.AddressDTO;
|
||||
import SuMoC.backend.geocoding.GeoCodingService;
|
||||
import SuMoC.backend.routing.config.AdHocRoutingProperties;
|
||||
import SuMoC.backend.routing.config.OnCallRoutingProperties;
|
||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
|
||||
import SuMoC.backend.routing.dtos.StepDTO;
|
||||
import SuMoC.backend.routing.exceptions.NoCarRouteFoundException;
|
||||
import SuMoC.backend.routing.exceptions.NoCarbonEmissionFoundException;
|
||||
import SuMoC.backend.routing.services.CartaTransitRouteProcessor;
|
||||
import SuMoC.backend.trip.Modality;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -17,48 +14,210 @@ import reactor.core.publisher.Mono;
|
||||
import sumoc.backend.carta.client.model.Direction;
|
||||
import sumoc.backend.carta.client.model.Route;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static SuMoC.backend.trip.Modality.BICYCLE;
|
||||
import static SuMoC.backend.trip.Modality.CAR;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class RoutingService {
|
||||
|
||||
private final GeoCodingService geoCodingService;
|
||||
public class DirectionsService {
|
||||
|
||||
private final CartaClient cartaClient;
|
||||
|
||||
private final AlternativeFilterService alternativeFilterService;
|
||||
private final GeoCodingService geoCodingService;
|
||||
|
||||
private final OnCallRoutingProperties onCallRoutingProperties;
|
||||
|
||||
private final AdHocRoutingProperties adHocRoutingProperties;
|
||||
public List<RouteDTO> getPossibleAlternativeRoutes(DirectionsRequest requestDTO) {
|
||||
return getPossibleRoutes(requestDTO, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes an individual call to the CARTA API and returns a direction future.
|
||||
* Returns possible routes for the request - no sanity filtering regarding travel times etc. is applied.
|
||||
* TODO this does not handle the case where origin/destination is provided as address only -> geocoding call to carta needed -> do in directions controller
|
||||
*/
|
||||
private CompletableFuture<Direction> getCartaFuture(
|
||||
RoutingAlternativeRequestDTO requestDTO,
|
||||
String mode,
|
||||
String types,
|
||||
int alternatives
|
||||
) {
|
||||
return cartaClient.asyncGetRoute(
|
||||
requestDTO.getOriginLat() + "," + requestDTO.getOriginLon(),
|
||||
requestDTO.getDestinationLat() + "," + requestDTO.getDestinationLon(),
|
||||
mode,
|
||||
requestDTO.getArrivalTime(),
|
||||
null,
|
||||
alternatives, // alternatives
|
||||
null, // walkingSpeed
|
||||
null, // transferTime TODO what is default? adapt?
|
||||
types,
|
||||
null, // range
|
||||
requestDTO.getOriginLat() + "," + requestDTO.getOriginLon()
|
||||
public List<RouteDTO> getPossibleRoutes(DirectionsRequest requestDTO, boolean includeCarRoute) {
|
||||
assert requestDTO.getRoutingPreferencesDTO() != null;
|
||||
HashMap<String, Direction> directionMap = getPossibleDirections(requestDTO);
|
||||
ArrayList<RouteDTO> suggestedRoutes = new ArrayList<>();
|
||||
|
||||
// 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()),
|
||||
geoCodingService.getAddress(requestDTO.getDestinationLat(), requestDTO.getDestinationLon())
|
||||
);
|
||||
var addressesTuple = addressesMono.block();
|
||||
AddressDTO originAddress = addressesTuple.getT1();
|
||||
AddressDTO destinationAddress = addressesTuple.getT2();
|
||||
|
||||
// Setting up car data for baseline
|
||||
Route carRoute;
|
||||
try {
|
||||
carRoute = directionMap.get("car").getRoutes().getFirst();
|
||||
} catch (NullPointerException e) {
|
||||
throw new NoCarRouteFoundException("No car route to compare to was found.");
|
||||
}
|
||||
double carCarbondDioxide;
|
||||
try {
|
||||
carCarbondDioxide = carRoute.getEmission().getCarbonDioxide();
|
||||
} catch (NullPointerException e) {
|
||||
throw new NoCarbonEmissionFoundException("No carbon emission was provided for the car route.");
|
||||
}
|
||||
double carDuration = carRoute.getDuration();
|
||||
|
||||
// Creating RouteDTOs for all available modes
|
||||
if (includeCarRoute) {
|
||||
Direction carDirection = directionMap.get("car");
|
||||
if (carDirection.getRoutes() != null && !carDirection.getRoutes().isEmpty()) {
|
||||
suggestedRoutes.add(createRouteDTO(
|
||||
requestDTO,
|
||||
carRoute,
|
||||
List.of(new StepDTO(CAR, carRoute.getDistance())),
|
||||
originAddress,
|
||||
destinationAddress,
|
||||
null,
|
||||
null,
|
||||
carCarbondDioxide,
|
||||
carDuration,
|
||||
false
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (directionMap.containsKey("bike")) {
|
||||
Direction bikeDirection = directionMap.get("bike");
|
||||
if (bikeDirection.getRoutes() != null && !bikeDirection.getRoutes().isEmpty()) {
|
||||
Route bikeRoute = bikeDirection.getRoutes().getFirst();
|
||||
suggestedRoutes.add(createRouteDTO(
|
||||
requestDTO,
|
||||
bikeRoute,
|
||||
List.of(new StepDTO(BICYCLE, bikeRoute.getDistance())),
|
||||
originAddress,
|
||||
destinationAddress,
|
||||
null,
|
||||
null,
|
||||
carCarbondDioxide,
|
||||
carDuration,
|
||||
false
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (directionMap.containsKey("walk")) {
|
||||
Direction walkDirection = directionMap.get("walk");
|
||||
if (walkDirection.getRoutes() != null && !walkDirection.getRoutes().isEmpty()) {
|
||||
Route walkRoute = walkDirection.getRoutes().getFirst();
|
||||
suggestedRoutes.add(createRouteDTO(
|
||||
requestDTO,
|
||||
walkRoute,
|
||||
List.of(new StepDTO(Modality.WALKING, walkRoute.getDistance())),
|
||||
originAddress,
|
||||
destinationAddress,
|
||||
null,
|
||||
null,
|
||||
carCarbondDioxide,
|
||||
carDuration,
|
||||
false
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (directionMap.containsKey("transit")) {
|
||||
Direction transitDirection = directionMap.get("transit");
|
||||
if (transitDirection.getRoutes() != null && !transitDirection.getRoutes().isEmpty()) {
|
||||
for (Route route : transitDirection.getRoutes()) {
|
||||
CartaTransitRouteProcessor routeProcessor = new CartaTransitRouteProcessor(route);
|
||||
suggestedRoutes.add(createRouteDTO(
|
||||
requestDTO,
|
||||
route,
|
||||
routeProcessor.getSteps(),
|
||||
originAddress,
|
||||
destinationAddress,
|
||||
routeProcessor.getFirstStopName(),
|
||||
routeProcessor.getLastStopName(),
|
||||
carCarbondDioxide,
|
||||
carDuration,
|
||||
true
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return suggestedRoutes;
|
||||
}
|
||||
|
||||
private RouteDTO createRouteDTO(
|
||||
DirectionsRequest requestDTO,
|
||||
Route route,
|
||||
List<StepDTO> steps,
|
||||
AddressDTO originAddress,
|
||||
AddressDTO destinationAddress,
|
||||
String firstStopName,
|
||||
String lastStopName,
|
||||
double carVariantco2Emission,
|
||||
double carVariantTimeSeconds,
|
||||
boolean isTransit
|
||||
) {
|
||||
|
||||
Instant arrivalTime;
|
||||
Instant departureTime;
|
||||
// Baseline is comparing with car version, except for alternative route requests
|
||||
double timeDifferenceSeconds = route.getDuration() - carVariantTimeSeconds;
|
||||
if (requestDTO.getArrivalTime() != null && requestDTO.getDepartureTime() != null) {
|
||||
// Case 1: both arrival and departure time provided -> must be alternative route request
|
||||
if (isTransit) { // for transit routes, we need to look up the exact arrival time at the last stop
|
||||
arrivalTime = cartaTimeToInstant(route.getSteps().getLast().getStopTime(), requestDTO.getArrivalTime());
|
||||
} else {
|
||||
arrivalTime = requestDTO.getArrivalTime();
|
||||
}
|
||||
departureTime = arrivalTime.minusSeconds(route.getDuration());
|
||||
timeDifferenceSeconds = route.getDuration() - (requestDTO.getArrivalTime().getEpochSecond() - requestDTO.getDepartureTime().getEpochSecond());
|
||||
} else if (requestDTO.getArrivalTime() != null) {
|
||||
// Case 2: only arrival time provided
|
||||
if (isTransit) {
|
||||
arrivalTime = cartaTimeToInstant(route.getSteps().getLast().getStopTime(), requestDTO.getArrivalTime());
|
||||
} else {
|
||||
arrivalTime = requestDTO.getArrivalTime();
|
||||
}
|
||||
departureTime = arrivalTime.minusSeconds(route.getDuration());
|
||||
} else {
|
||||
// Case 3: only departure time provided
|
||||
if (isTransit) {
|
||||
departureTime = cartaTimeToInstant(route.getSteps().getFirst().getStartTime(), requestDTO.getDepartureTime());
|
||||
} else {
|
||||
departureTime = requestDTO.getDepartureTime();
|
||||
}
|
||||
arrivalTime = departureTime.plusSeconds(route.getDuration());
|
||||
}
|
||||
|
||||
double co2savings = carVariantco2Emission - route.getEmission().getCarbonDioxide();
|
||||
|
||||
RouteDTO routeDTO = new RouteDTO(
|
||||
originAddress,
|
||||
firstStopName,
|
||||
route.getSourceCoordinate().getLatitude(),
|
||||
route.getSourceCoordinate().getLongitude(),
|
||||
destinationAddress,
|
||||
lastStopName,
|
||||
route.getTargetCoordinate().getLatitude(),
|
||||
route.getTargetCoordinate().getLongitude(),
|
||||
departureTime,
|
||||
arrivalTime,
|
||||
steps,
|
||||
co2savings,
|
||||
timeDifferenceSeconds,
|
||||
route.getEmission().getCarbonDioxide()
|
||||
);
|
||||
return routeDTO;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -69,7 +228,7 @@ public class RoutingService {
|
||||
* - bike (optional)
|
||||
* - transit (optional)
|
||||
*/
|
||||
private HashMap<String, Direction> getPossibleDirectionsFromCarta(RoutingAlternativeRequestDTO requestDTO) {
|
||||
private HashMap<String, Direction> getPossibleDirections(DirectionsRequest requestDTO) {
|
||||
Map<String, CompletableFuture<Direction>> futuresByMode = new HashMap<>();
|
||||
assert requestDTO.getRoutingPreferencesDTO() != null;
|
||||
|
||||
@@ -113,156 +272,51 @@ public class RoutingService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets possible routes from CARTA, converts them to our format and applies filter to only provide acceptable solutions without excessive additional travel time.
|
||||
* This is the public method for alternatives explicitly asked for by the client.
|
||||
* Converts a Carta time (seconds since midnight of current day) to an Instant.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public List<RouteDTO> determineAlternativeRoutesOnUserRequest(RoutingAlternativeRequestDTO requestDTO) {
|
||||
List<RouteDTO> routes = getPossibleAlternativeRoutes(requestDTO);
|
||||
routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, onCallRoutingProperties);
|
||||
|
||||
return routes;
|
||||
private Instant cartaTimeToInstant(Integer secondsSinceMidnight, Instant instantOfReferenceDay) {
|
||||
LocalDate date = instantOfReferenceDay.atZone(ZoneId.systemDefault()).toLocalDate();
|
||||
LocalDateTime startOfDay = date.atStartOfDay();
|
||||
LocalDateTime resultDateTime = startOfDay.plusSeconds(secondsSinceMidnight);
|
||||
return resultDateTime.atZone(ZoneId.systemDefault()).toInstant();
|
||||
}
|
||||
|
||||
/**
|
||||
* Public alternative retrieval method which is used to check for alternatives we suggest to user via notification
|
||||
* right after user finished the trip.
|
||||
* Similar to determineAlternativeRoutesOnUserRequest but here we apply stricter thresholds for alternatives
|
||||
* and also apply weather filtering (if enabled) to not suggest routes the user definitly would not have consideres.
|
||||
* Makes an individual call to the CARTA API and returns a direction future.
|
||||
*/
|
||||
public List<RouteDTO> determineAlternativeRoutesAdHoc(RoutingAlternativeRequestDTO requestDTO) {
|
||||
assert requestDTO.getRoutingPreferencesDTO() != null;
|
||||
|
||||
List<RouteDTO> routes = getPossibleAlternativeRoutes(requestDTO);
|
||||
routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, adHocRoutingProperties);
|
||||
|
||||
if (requestDTO.getRoutingPreferencesDTO().isConsiderWeatherConditions()) {
|
||||
routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties);
|
||||
private CompletableFuture<Direction> getCartaFuture(
|
||||
DirectionsRequest requestDTO,
|
||||
String mode,
|
||||
String types,
|
||||
int alternatives
|
||||
) {
|
||||
Instant departureTime = null;
|
||||
Instant arrivalTime = null;
|
||||
if (requestDTO.getArrivalTime() != null) {
|
||||
arrivalTime = requestDTO.getArrivalTime();
|
||||
} else if (requestDTO.getDepartureTime() != null) {
|
||||
departureTime = requestDTO.getDepartureTime();
|
||||
} else {
|
||||
throw new IllegalArgumentException("Either arrivalTime or departureTime must be provided.");
|
||||
}
|
||||
|
||||
return routes;
|
||||
}
|
||||
// TODO derive origin either from address or coordinates
|
||||
|
||||
/**
|
||||
* Returns possible alternative routes for the request - no sanity filtering regarding travel times etc. is applied.
|
||||
*/
|
||||
private List<RouteDTO> getPossibleAlternativeRoutes(RoutingAlternativeRequestDTO requestDTO) {
|
||||
assert requestDTO.getRoutingPreferencesDTO() != null;
|
||||
HashMap<String, Direction> directionMap = getPossibleDirectionsFromCarta(requestDTO);
|
||||
ArrayList<RouteDTO> suggestedAlternatives = new ArrayList<>();
|
||||
|
||||
// Fetch origin and destination addresses concurrently
|
||||
var addressesMono = Mono.zip(
|
||||
geoCodingService.getAddress(requestDTO.getOriginLat(), requestDTO.getOriginLon()),
|
||||
geoCodingService.getAddress(requestDTO.getDestinationLat(), requestDTO.getDestinationLon())
|
||||
return cartaClient.asyncGetRoute(
|
||||
requestDTO.getOriginLat() + "," + requestDTO.getOriginLon(),
|
||||
requestDTO.getDestinationLat() + "," + requestDTO.getDestinationLon(),
|
||||
mode,
|
||||
arrivalTime,
|
||||
departureTime,
|
||||
alternatives, // alternatives
|
||||
null, // walkingSpeed
|
||||
null, // transferTime TODO what is default? adapt?
|
||||
types,
|
||||
null, // range
|
||||
// TODO only if coordinates are provided directly
|
||||
requestDTO.getOriginLat() + "," + requestDTO.getOriginLon()
|
||||
);
|
||||
var addressesTuple = addressesMono.block();
|
||||
AddressDTO originAddress = addressesTuple.getT1();
|
||||
AddressDTO destinationAddress = addressesTuple.getT2();
|
||||
|
||||
// Setting up car data for baseline
|
||||
Route carRoute;
|
||||
try {
|
||||
carRoute = directionMap.get("car").getRoutes().getFirst();
|
||||
} catch (NullPointerException e) {
|
||||
throw new NoCarRouteFoundException("No car route to compare to was found.");
|
||||
}
|
||||
double carCarbondDioxide;
|
||||
try {
|
||||
carCarbondDioxide = carRoute.getEmission().getCarbonDioxide();
|
||||
} catch (NullPointerException e) {
|
||||
throw new NoCarbonEmissionFoundException("No carbon emission was provided for the car route.");
|
||||
}
|
||||
|
||||
if (directionMap.containsKey("bike")) {
|
||||
Direction bikeDirection = directionMap.get("bike");
|
||||
if (bikeDirection.getRoutes() != null && !bikeDirection.getRoutes().isEmpty()) {
|
||||
Route bikeRoute = bikeDirection.getRoutes().getFirst();
|
||||
ArrayList<StepDTO> steps = new ArrayList<>();
|
||||
steps.add(new StepDTO(
|
||||
Modality.BICYCLE,
|
||||
null,
|
||||
bikeRoute.getDistance()
|
||||
)
|
||||
);
|
||||
|
||||
RouteDTO routeDTO = new RouteDTO(
|
||||
originAddress,
|
||||
null,
|
||||
bikeRoute.getSourceCoordinate().getLatitude(),
|
||||
bikeRoute.getSourceCoordinate().getLongitude(),
|
||||
destinationAddress,
|
||||
null,
|
||||
bikeRoute.getTargetCoordinate().getLatitude(),
|
||||
bikeRoute.getTargetCoordinate().getLongitude(),
|
||||
requestDTO.getArrivalTime().minusSeconds(bikeRoute.getDuration()),
|
||||
requestDTO.getArrivalTime(),
|
||||
steps,
|
||||
carCarbondDioxide,
|
||||
bikeRoute.getDuration() - carRoute.getDuration(),
|
||||
0.0
|
||||
);
|
||||
suggestedAlternatives.add(routeDTO);
|
||||
}
|
||||
}
|
||||
|
||||
if (directionMap.containsKey("walk")) {
|
||||
Direction walkDirection = directionMap.get("walk");
|
||||
if (walkDirection.getRoutes() != null && !walkDirection.getRoutes().isEmpty()) {
|
||||
Route walkRoute = walkDirection.getRoutes().getFirst();
|
||||
ArrayList<StepDTO> steps = new ArrayList<>();
|
||||
steps.add(new StepDTO(
|
||||
Modality.WALKING,
|
||||
null,
|
||||
walkRoute.getDistance()
|
||||
));
|
||||
|
||||
RouteDTO routeDTO = new RouteDTO(
|
||||
originAddress,
|
||||
null,
|
||||
walkRoute.getSourceCoordinate().getLatitude(),
|
||||
walkRoute.getSourceCoordinate().getLongitude(),
|
||||
destinationAddress,
|
||||
null,
|
||||
walkRoute.getTargetCoordinate().getLatitude(),
|
||||
walkRoute.getTargetCoordinate().getLongitude(),
|
||||
requestDTO.getArrivalTime().minusSeconds(walkRoute.getDuration()),
|
||||
requestDTO.getArrivalTime(),
|
||||
steps,
|
||||
carCarbondDioxide,
|
||||
walkRoute.getDuration() - carRoute.getDuration(),
|
||||
0.0
|
||||
);
|
||||
suggestedAlternatives.add(routeDTO);
|
||||
}
|
||||
}
|
||||
|
||||
if (directionMap.containsKey("transit")) {
|
||||
Direction transitDirection = directionMap.get("transit");
|
||||
if (transitDirection.getRoutes() != null && !transitDirection.getRoutes().isEmpty()) {
|
||||
for (Route route : transitDirection.getRoutes()) {
|
||||
CartaTransitRouteProcessor routeProcessor = new CartaTransitRouteProcessor(route);
|
||||
|
||||
RouteDTO routeDTO = new RouteDTO(
|
||||
originAddress,
|
||||
routeProcessor.getFirstStopName(),
|
||||
route.getSourceCoordinate().getLatitude(),
|
||||
route.getSourceCoordinate().getLongitude(),
|
||||
destinationAddress,
|
||||
routeProcessor.getLastStopName(),
|
||||
route.getTargetCoordinate().getLatitude(),
|
||||
route.getTargetCoordinate().getLongitude(),
|
||||
requestDTO.getArrivalTime().minusSeconds(route.getDuration()),
|
||||
requestDTO.getArrivalTime(),
|
||||
routeProcessor.getSteps(),
|
||||
carCarbondDioxide - route.getEmission().getCarbonDioxide(),
|
||||
route.getDuration() - carRoute.getDuration(),
|
||||
route.getEmission().getCarbonDioxide()
|
||||
);
|
||||
suggestedAlternatives.add(routeDTO);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return suggestedAlternatives;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package SuMoC.backend.common.converter;
|
||||
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
|
||||
/**
|
||||
* This converter handles the conversion between Java's DayOfWeek enum and the SQL DAY_OF_WEEK integer representation.
|
||||
* In Java, DayOfWeek uses 1 (Monday) to 7 (Sunday), while SQL's DAY_OF_WEEK function returns 0 (Sunday) to 6 (Saturday).
|
||||
*/
|
||||
@Converter(autoApply = true)
|
||||
public class DayOfWeekConverter implements AttributeConverter<DayOfWeek, Integer> {
|
||||
|
||||
@Override
|
||||
public Integer convertToDatabaseColumn(DayOfWeek attribute) {
|
||||
if (attribute == null) {
|
||||
return null;
|
||||
}
|
||||
// Convert Java DayOfWeek (1=Monday, ..., 7=Sunday) to SQL DOW (0=Sunday, ..., 6=Saturday)
|
||||
return attribute.getValue() % 7;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DayOfWeek convertToEntityAttribute(Integer dbData) {
|
||||
if (dbData == null) {
|
||||
return null;
|
||||
}
|
||||
// Convert SQL DOW (0=Sunday, ..., 6=Saturday) to Java DayOfWeek (1=Monday, ..., 7=Sunday)
|
||||
return DayOfWeek.of(dbData == 0 ? 7 : dbData);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package SuMoC.backend.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.web.filter.ShallowEtagHeaderFilter;
|
||||
|
||||
@Configuration
|
||||
public class CachingConfig {
|
||||
|
||||
/**
|
||||
* Register a filter that adds ETag headers to HTTP responses for caching purposes.
|
||||
*/
|
||||
@Bean
|
||||
public FilterRegistrationBean<ShallowEtagHeaderFilter> etagFilter() {
|
||||
FilterRegistrationBean<ShallowEtagHeaderFilter> filter = new FilterRegistrationBean<>(new ShallowEtagHeaderFilter());
|
||||
filter.addUrlPatterns("/*");
|
||||
filter.setName("etagFilter");
|
||||
filter.setOrder(1);
|
||||
return filter;
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,42 @@
|
||||
package SuMoC.backend.dev;
|
||||
|
||||
import SuMoC.backend.firebase.FirebaseMessageBuilder;
|
||||
import SuMoC.backend.h3.H3Service;
|
||||
import SuMoC.backend.meteo.ForecastService;
|
||||
import SuMoC.backend.meteo.MeteoClient;
|
||||
import SuMoC.backend.notification.enums.NotificationStatus;
|
||||
import SuMoC.backend.notification.enums.NotificationType;
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
import SuMoC.backend.notification.repositories.NotificationRepository;
|
||||
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
|
||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||
import SuMoC.backend.scheduling.ScheduledTasks;
|
||||
import SuMoC.backend.suggestion.services.RegularTripSuggestionService;
|
||||
import SuMoC.backend.trend.dto.TrendDetectionDTO;
|
||||
import SuMoC.backend.trend.services.StatTableUpdateService;
|
||||
import SuMoC.backend.user.dtos.FriendshipDTO;
|
||||
import SuMoC.backend.user.dtos.MinimalUserDTO;
|
||||
import SuMoC.backend.user.enums.FriendShipStatus;
|
||||
import SuMoC.backend.user.mapper.UserMapper;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.firebase.messaging.FirebaseMessaging;
|
||||
import com.google.firebase.messaging.Message;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/dev")
|
||||
@@ -25,18 +48,36 @@ public class DevController {
|
||||
private final FirebaseMessaging firebaseMessaging;
|
||||
private final MeteoClient meteoClient;
|
||||
private final ForecastService forecastService;
|
||||
private final FirebaseMessageBuilder firebaseMessageBuilder;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final NotificationRepository notificationRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final UserMapper userMapper;
|
||||
private final H3Service h3Service;
|
||||
private final RegularTripSuggestionService regularTripSuggestionService;
|
||||
|
||||
public DevController(
|
||||
ScheduledTasks scheduledTasks,
|
||||
StatTableUpdateService statTableUpdateService,
|
||||
@Autowired(required = false) FirebaseMessaging firebaseMessaging,
|
||||
MeteoClient meteoClient,
|
||||
ForecastService forecastService) {
|
||||
ForecastService forecastService,
|
||||
FirebaseMessageBuilder firebaseMessageBuilder,
|
||||
ObjectMapper objectMapper,
|
||||
NotificationRepository notificationRepository, UserRepository userRepository, UserMapper userMapper, H3Service h3Service, RegularTripSuggestionService regularTripSuggestionService
|
||||
) {
|
||||
this.scheduledTasks = scheduledTasks;
|
||||
this.statTableUpdateService = statTableUpdateService;
|
||||
this.firebaseMessaging = firebaseMessaging;
|
||||
this.meteoClient = meteoClient;
|
||||
this.forecastService = forecastService;
|
||||
this.firebaseMessageBuilder = firebaseMessageBuilder;
|
||||
this.objectMapper = objectMapper;
|
||||
this.notificationRepository = notificationRepository;
|
||||
this.userRepository = userRepository;
|
||||
this.userMapper = userMapper;
|
||||
this.h3Service = h3Service;
|
||||
this.regularTripSuggestionService = regularTripSuggestionService;
|
||||
}
|
||||
|
||||
@PostMapping("/trigger-trend-calculation")
|
||||
@@ -49,19 +90,23 @@ public class DevController {
|
||||
statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(day3WeeksAgo);
|
||||
}
|
||||
|
||||
@GetMapping("/test-firebase")
|
||||
public ResponseEntity<String> testFirebaseConnection() {
|
||||
@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) {
|
||||
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);
|
||||
notification.setData(objectMapper.writeValueAsString(TrendDetectionDTO.mockTrendDetectionDTO()));
|
||||
|
||||
Message mockTrendMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
|
||||
|
||||
// Send to a topic (no device registration needed)
|
||||
String message = firebaseMessaging.sendAsync(
|
||||
com.google.firebase.messaging.Message.builder()
|
||||
.setTopic("test-topic")
|
||||
.putData("test", "connection-check")
|
||||
.build()
|
||||
mockTrendMessage
|
||||
).get();
|
||||
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
|
||||
} catch (Exception e) {
|
||||
@@ -69,6 +114,164 @@ public class DevController {
|
||||
}
|
||||
}
|
||||
|
||||
@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) {
|
||||
if (firebaseMessaging == null) {
|
||||
return ResponseEntity.status(503)
|
||||
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
|
||||
}
|
||||
try {
|
||||
Notification notification = new Notification();
|
||||
notification.setType(NotificationType.ADHOC_ALTERNATIVE);
|
||||
List<RouteDTO> mockRoutes = List.of(RouteDTO.getMockRouteDTO(), RouteDTO.getMockRouteDTO());
|
||||
notification.setData(objectMapper.writeValueAsString(mockRoutes));
|
||||
|
||||
Message mockAdhocMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
|
||||
|
||||
// Send to a topic (no device registration needed)
|
||||
String message = firebaseMessaging.sendAsync(
|
||||
mockAdhocMessage
|
||||
).get();
|
||||
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/test-firebase-regular-trip-notification/{fcm_token}")
|
||||
@Operation(description = "Immediately sends a test notification of type REGULAR_TRIP_ALTERNATIVE to the provided FCM token.")
|
||||
public ResponseEntity<String> SendTestRegularTripAlternativeNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
|
||||
if (firebaseMessaging == null) {
|
||||
return ResponseEntity.status(503)
|
||||
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
|
||||
}
|
||||
try {
|
||||
Notification notification = new Notification();
|
||||
notification.setType(NotificationType.REGULAR_TRIP_ALTERNATIVE);
|
||||
RouteDTO mockRoute = RouteDTO.getMockRouteDTO();
|
||||
notification.setData(objectMapper.writeValueAsString(mockRoute));
|
||||
Message mockRegularTripMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
|
||||
// Send to a topic (no device registration needed)
|
||||
String message = firebaseMessaging.sendAsync(
|
||||
mockRegularTripMessage
|
||||
).get();
|
||||
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/test-firebase-friendship-request-notification/{fcm_token}")
|
||||
@Operation(description = "Immediately sends a test notification of type FRIENDSHIP_REQUEST_RECEIVED to the provided FCM token.")
|
||||
public ResponseEntity<String> SendTestRFriendshipRequestReceivedNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
|
||||
if (firebaseMessaging == null) {
|
||||
return ResponseEntity.status(503)
|
||||
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
|
||||
}
|
||||
try {
|
||||
Notification notification = new Notification();
|
||||
notification.setType(NotificationType.FRIENDSHIP_REQUEST_RECEIVED);
|
||||
FriendshipDTO friendshipDTO = new FriendshipDTO(
|
||||
1L,
|
||||
2L,
|
||||
new MinimalUserDTO(
|
||||
2L,
|
||||
"request_public_name"
|
||||
),
|
||||
FriendShipStatus.PENDING,
|
||||
Instant.now()
|
||||
);
|
||||
notification.setData(objectMapper.writeValueAsString(friendshipDTO));
|
||||
Message mockRegularTripMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
|
||||
String message = firebaseMessaging.sendAsync(
|
||||
mockRegularTripMessage
|
||||
).get();
|
||||
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/test-notification-from-detected-regular-trip")
|
||||
@Operation(description = "Testing endpoint that mocks the detection of regular trips and then tests the alternative calculation and notification scheduling.")
|
||||
public ResponseEntity<String> testNotificationFromDetectedRegularTrip() {
|
||||
if (firebaseMessaging == null) {
|
||||
return ResponseEntity.status(503)
|
||||
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
|
||||
}
|
||||
try {
|
||||
// we seed user 1 and 2 in the dev data loader
|
||||
HashMap<Long, List<DetectedRegularTripDTO>> detectedRegularTripsByUser = new HashMap<>();
|
||||
List<DetectedRegularTripDTO> list1 = List.of(
|
||||
DetectedRegularTripDTO.getTriggeringMock(h3Service, 1L)
|
||||
);
|
||||
List<DetectedRegularTripDTO> list2 = List.of(
|
||||
DetectedRegularTripDTO.getTriggeringMock(h3Service, 2L)
|
||||
);
|
||||
detectedRegularTripsByUser.put(1L, list1);
|
||||
detectedRegularTripsByUser.put(2L, list2);
|
||||
|
||||
regularTripSuggestionService.checkAlternativesAndNotify(detectedRegularTripsByUser);
|
||||
return ResponseEntity.ok("✓ Test notifications from detected regular trips processed.");
|
||||
|
||||
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(description = "Immediately queues a notification to the fcm key specified in application-dev.properties to be processed by the notification queue.")
|
||||
@GetMapping("/queue-test-notification")
|
||||
public ResponseEntity<String> queueTestNotification() {
|
||||
if (firebaseMessaging == null) {
|
||||
return ResponseEntity.status(503)
|
||||
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
|
||||
}
|
||||
try {
|
||||
User user = userRepository.findByEmail("user1@email.com").orElseThrow();
|
||||
|
||||
TrendDetectionDTO mockDTO = TrendDetectionDTO.mockTrendDetectionDTO();
|
||||
mockDTO.setUserId(user.getId());
|
||||
|
||||
Notification notification = Notification.builder()
|
||||
.type(NotificationType.TREND)
|
||||
.data(objectMapper.writeValueAsString(mockDTO))
|
||||
.user(user)
|
||||
.earliestTimeOfDayToSend(LocalTime.now())
|
||||
.createdAt(Instant.now())
|
||||
.status(NotificationStatus.PENDING)
|
||||
.build();
|
||||
|
||||
notificationRepository.save(notification);
|
||||
|
||||
return ResponseEntity.ok("✓ Test notification queued.");
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(description = "Tests the method cleaning old notifications from the database.")
|
||||
@GetMapping("/test-clean-old-notifications")
|
||||
public void testCleanOldNotifications() throws JsonProcessingException, InterruptedException {
|
||||
User user = userRepository.findByEmail("user1@email.com").orElseThrow();
|
||||
|
||||
Notification notification = Notification.builder()
|
||||
.type(NotificationType.TREND)
|
||||
.data(objectMapper.writeValueAsString(TrendDetectionDTO.mockTrendDetectionDTO()))
|
||||
.user(user)
|
||||
.earliestTimeOfDayToSend(LocalTime.now())
|
||||
.createdAt(Instant.now().minus(Duration.ofDays(60)))
|
||||
.status(NotificationStatus.SENT)
|
||||
.build();
|
||||
|
||||
notificationRepository.save(notification);
|
||||
|
||||
Thread.sleep(5000);
|
||||
|
||||
scheduledTasks.scheduleCleanUpOldNotifications();
|
||||
}
|
||||
|
||||
@GetMapping("/test-meteo")
|
||||
public void testMeteoClient() {
|
||||
try {
|
||||
@@ -83,4 +286,9 @@ public class DevController {
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/test-detection-and-notification-regular-trips")
|
||||
public void testDetectionAndNotificationOfRegularTrips() {
|
||||
regularTripSuggestionService.detectAndNotifyRegularTripsForTodaysDayOfWeek();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package SuMoC.backend.dev;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "sumoc.dev")
|
||||
public class DevProperties {
|
||||
/**
|
||||
* Will be used to init the seeded users with in the dev profile.
|
||||
*/
|
||||
private String fcmKey = "";
|
||||
}
|
||||
@@ -28,13 +28,18 @@ public class FirebaseConfiguration {
|
||||
|
||||
@Bean
|
||||
FirebaseApp firebaseApp(GoogleCredentials credentials) {
|
||||
FirebaseOptions options = FirebaseOptions.builder()
|
||||
.setCredentials(credentials)
|
||||
.build();
|
||||
|
||||
return FirebaseApp.initializeApp(options);
|
||||
try {
|
||||
return FirebaseApp.getInstance();
|
||||
} catch (IllegalStateException e) {
|
||||
// App doesn't exist yet, create it
|
||||
FirebaseOptions options = FirebaseOptions.builder()
|
||||
.setCredentials(credentials)
|
||||
.build();
|
||||
return FirebaseApp.initializeApp(options);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
GoogleCredentials googleCredentials(FirebaseProperties firebaseProperties) throws IOException {
|
||||
if (firebaseProperties.serviceAccount() != null) {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package SuMoC.backend.firebase;
|
||||
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
import com.google.firebase.messaging.ApnsConfig;
|
||||
import com.google.firebase.messaging.Aps;
|
||||
import com.google.firebase.messaging.ApsAlert;
|
||||
import com.google.firebase.messaging.Message;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class FirebaseMessageBuilder {
|
||||
|
||||
public Message generateMessage(Notification notification, String token) {
|
||||
var builder = Message.builder().setToken(token);
|
||||
builder.putData("type", notification.getType().toString());
|
||||
builder.putData("data", notification.getData());
|
||||
|
||||
//Setup, so iOS can receive and intercept Push Notifications
|
||||
builder.setNotification(com.google.firebase.messaging.Notification.builder()
|
||||
.setTitle("Sumoc Update")
|
||||
.setBody("Deine Nachricht ist da!")
|
||||
.build())
|
||||
.setApnsConfig(ApnsConfig.builder()
|
||||
.setAps(Aps.builder()
|
||||
.setMutableContent(true)
|
||||
.setSound("default") // WICHTIG: Ohne Sound oft keine Anzeige
|
||||
.setBadge(1)
|
||||
.build())
|
||||
.build());
|
||||
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,17 +1,22 @@
|
||||
package SuMoC.backend.gamification.badges;
|
||||
|
||||
import SuMoC.backend.gamification.badges.models.Badge;
|
||||
import SuMoC.backend.gamification.badges.models.UserBadgeDTO;
|
||||
import SuMoC.backend.gamification.badges.models.BadgeDTO;
|
||||
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.annotation.security.RolesAllowed;
|
||||
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.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/badges")
|
||||
@@ -27,13 +32,14 @@ public class BadgeController {
|
||||
|
||||
@Operation(summary = "Create a new badge")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "201", description = "Badge created successfully"),
|
||||
@ApiResponse(responseCode = "201", description = "Badge created successfully",
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = BadgeDTO.class))),
|
||||
@ApiResponse(responseCode = "400", description = "Invalid input data"),
|
||||
@ApiResponse(responseCode = "409", description = "Badge already exists")
|
||||
})
|
||||
@PostMapping("/createBadge")
|
||||
public ResponseEntity<Badge> createBadge(@RequestBody @Valid Badge badge) {
|
||||
Badge createdBadge = badgeService.createBadge(badge);
|
||||
public ResponseEntity<BadgeDTO> createBadge(@RequestBody @Valid BadgeDTO badge) {
|
||||
BadgeDTO createdBadge = badgeService.createBadge(badge);
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(createdBadge);
|
||||
}
|
||||
|
||||
@@ -53,39 +59,71 @@ public class BadgeController {
|
||||
|
||||
@Operation(summary = "Modify a badge by ID")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Badge modified successfully"),
|
||||
@ApiResponse(responseCode = "200", description = "Badge modified successfully",
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = BadgeDTO.class))),
|
||||
@ApiResponse(responseCode = "404", description = "Badge not found"),
|
||||
@ApiResponse(responseCode = "400", description = "Invalid input data")
|
||||
})
|
||||
@PutMapping("/modifyBadge")
|
||||
public ResponseEntity<Badge> modifyBadgeById(
|
||||
@RequestBody @Valid Badge badge) {
|
||||
Badge modifiedBadge = badgeService.modifyBadge(badge);
|
||||
public ResponseEntity<BadgeDTO> modifyBadgeById(
|
||||
@RequestBody @Valid BadgeDTO badge) {
|
||||
BadgeDTO modifiedBadge = badgeService.modifyBadge(badge);
|
||||
return ResponseEntity.status(HttpStatus.OK).body(modifiedBadge);
|
||||
}
|
||||
|
||||
|
||||
@Operation(summary = "Get a badge by ID")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Badge retrieved successfully"),
|
||||
@ApiResponse(responseCode = "200", description = "Badge retrieved successfully",
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = BadgeDTO.class))),
|
||||
@ApiResponse(responseCode = "304", description = "Not modified since last request"),
|
||||
@ApiResponse(responseCode = "404", description = "Badge not found")
|
||||
})
|
||||
@GetMapping("/getBadge/{badgeId}")
|
||||
public ResponseEntity<Badge> getBadgeById(@PathVariable Long badgeId) {
|
||||
Badge badge = badgeService.getBadgeById(badgeId);
|
||||
return ResponseEntity.status(HttpStatus.OK).body(badge);
|
||||
public ResponseEntity<BadgeDTO> getBadgeById(@PathVariable Long badgeId) {
|
||||
BadgeDTO badge = badgeService.getBadgeById(badgeId);
|
||||
return ResponseEntity.ok()
|
||||
.cacheControl(CacheControl.maxAge(356, TimeUnit.DAYS))
|
||||
.body(badge);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Operation(summary = "Get all badges")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Badges retrieved successfully"),
|
||||
@ApiResponse(responseCode = "200", description = "Badges retrieved successfully",
|
||||
content = @Content(mediaType = "application/json",
|
||||
array = @ArraySchema(schema = @Schema(implementation = BadgeDTO.class))
|
||||
)),
|
||||
@ApiResponse(responseCode = "304", description = "Not modified since last request"),
|
||||
@ApiResponse(responseCode = "404", description = "No badges found")
|
||||
})
|
||||
@GetMapping("/getAllBadges")
|
||||
public ResponseEntity<List<Badge>> getAllBadges(){
|
||||
List<Badge> badges = badgeService.getAllBadges();
|
||||
return ResponseEntity.status(HttpStatus.OK).body(badges);
|
||||
public ResponseEntity<List<BadgeDTO>> getAllBadges(){
|
||||
List<BadgeDTO> badges = badgeService.getAllBadges();
|
||||
return ResponseEntity.ok()
|
||||
.cacheControl(CacheControl.maxAge(365, TimeUnit.DAYS))
|
||||
.body(badges);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get Badges by user")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Badges retrieved successfully"),
|
||||
@ApiResponse(responseCode = "404", description = "No badges found for user")
|
||||
})
|
||||
@GetMapping("/getBadges/{userId}")
|
||||
public ResponseEntity<List<UserBadgeDTO>> getBadgesByUser(@PathVariable("userId") Long userId) {
|
||||
List<UserBadgeDTO> badges = badgeService.getUserBadges(userId);
|
||||
return ResponseEntity.ok(badges);
|
||||
}
|
||||
|
||||
@Operation(summary = "Check badges for current user and award newly unlocked ones")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Check successful")
|
||||
})
|
||||
@PostMapping("/checkBadgeAndAward")
|
||||
public ResponseEntity<Void> checkAndAwardBadges() {
|
||||
badgeService.checkAndAwardBadges();
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
package SuMoC.backend.gamification.badges;
|
||||
|
||||
import SuMoC.backend.gamification.Timeframe;
|
||||
import SuMoC.backend.gamification.badges.mapper.BadgeMapper;
|
||||
import SuMoC.backend.gamification.badges.mapper.UserBadgeMapper;
|
||||
import SuMoC.backend.gamification.badges.models.Badge;
|
||||
import SuMoC.backend.gamification.badges.models.BadgeDTO;
|
||||
import SuMoC.backend.gamification.badges.models.UserBadge;
|
||||
import SuMoC.backend.gamification.badges.models.UserBadgeDTO;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.service.CurrentUserService;
|
||||
import SuMoC.backend.user.service.PrivacyService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import jakarta.transaction.Transactional;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
@@ -19,6 +22,7 @@ import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class BadgeService {
|
||||
|
||||
private final CurrentUserService currentUser;
|
||||
@@ -35,16 +39,19 @@ public class BadgeService {
|
||||
this.privacyService = privacyService;
|
||||
}
|
||||
|
||||
public Badge createBadge(Badge badge) {
|
||||
badgeRepository.findByName(badge.getName())
|
||||
public BadgeDTO createBadge(BadgeDTO badgeDTO) {
|
||||
badgeRepository.findByName(badgeDTO.getName())
|
||||
.ifPresent(b -> {
|
||||
throw new ResponseStatusException(HttpStatus.CONFLICT, "Badge existiert bereits");
|
||||
});
|
||||
return badgeRepository.save(badge);
|
||||
|
||||
Badge badge = BadgeMapper.toEntity(badgeDTO);
|
||||
Badge savedBadge = badgeRepository.save(badge);
|
||||
return BadgeMapper.toDTO(savedBadge);
|
||||
}
|
||||
|
||||
|
||||
public void checkAndAwardBadges(User user) {
|
||||
public void checkAndAwardBadges() {
|
||||
User user = currentUser.get();
|
||||
List<Badge> badges = badgeRepository.findAll();
|
||||
|
||||
for (Badge badge : badges) {
|
||||
@@ -70,20 +77,19 @@ public class BadgeService {
|
||||
user.getBadges().add(userBadge);
|
||||
|
||||
// TODO: Remove in production
|
||||
System.out.println("Badge " + badge.getName() + " vergeben an " + user.getPrivateName() + ". Mit Condition: " + badge.getCriteria().toString());
|
||||
System.out.println("Badge " + badge.getName() + " vergeben an " + user.getPrivateName() +
|
||||
". Mit Condition: " + badge.getCriteria().toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Badge modifyBadge(Badge modifiedBadge) {
|
||||
Badge badge = badgeRepository.findById(modifiedBadge.getId())
|
||||
public BadgeDTO modifyBadge(BadgeDTO badgeDTO) {
|
||||
Badge badge = badgeRepository.findById(badgeDTO.getId())
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Badge nicht gefunden"));
|
||||
|
||||
badge.setName(modifiedBadge.getName());
|
||||
badge.setDescription(modifiedBadge.getDescription());
|
||||
badge.setCriteria(modifiedBadge.getCriteria());
|
||||
|
||||
return badgeRepository.save(badge);
|
||||
BadgeMapper.updateEntityFromDTO(badge, badgeDTO);
|
||||
Badge savedBadge = badgeRepository.save(badge);
|
||||
return BadgeMapper.toDTO(savedBadge);
|
||||
}
|
||||
|
||||
public void deleteBadge(Long id) {
|
||||
@@ -92,14 +98,17 @@ public class BadgeService {
|
||||
badgeRepository.delete(badge);
|
||||
}
|
||||
|
||||
public Badge getBadgeById(Long badgeId) {
|
||||
return badgeRepository.findById(badgeId)
|
||||
public BadgeDTO getBadgeById(Long badgeId) {
|
||||
Badge badge = badgeRepository.findById(badgeId)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Badge nicht gefunden"));
|
||||
return BadgeMapper.toDTO(badge);
|
||||
}
|
||||
|
||||
|
||||
public List<Badge> getAllBadges() {
|
||||
return badgeRepository.findAll();
|
||||
public List<BadgeDTO> getAllBadges() {
|
||||
List<Badge> badges = badgeRepository.findAll();
|
||||
return badges.stream()
|
||||
.map(BadgeMapper::toDTO)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public List<UserBadgeDTO> getUserBadges(Long id) {
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
package SuMoC.backend.gamification.badges;
|
||||
|
||||
import SuMoC.backend.gamification.badges.mapper.BadgeMapper;
|
||||
import SuMoC.backend.gamification.badges.models.Badge;
|
||||
import SuMoC.backend.gamification.badges.models.BadgeCategory;
|
||||
import SuMoC.backend.gamification.badges.models.BadgeDTO;
|
||||
import jakarta.transaction.Transactional;
|
||||
import kotlin.collections.ArrayDeque;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
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(3)
|
||||
public class DevBadgeSeeder implements CommandLineRunner {
|
||||
|
||||
private final BadgeService badgeService;
|
||||
private final BadgeRepository badgeRepository;
|
||||
|
||||
@Autowired
|
||||
public DevBadgeSeeder(BadgeService badgeService, BadgeRepository badgeRepository) {
|
||||
this.badgeService = badgeService;
|
||||
this.badgeRepository = badgeRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void run(String... args) {
|
||||
List<Seed> seeds = generateSeeds();
|
||||
|
||||
|
||||
for (Seed seed : seeds) {
|
||||
badgeRepository.findByName(seed.name())
|
||||
.map(BadgeMapper::toDTO)
|
||||
.ifPresentOrElse(
|
||||
existing -> {
|
||||
boolean changed =
|
||||
!Objects.equals(existing.getDescription(), seed.description()) ||
|
||||
!Objects.equals(existing.getCriteria(), seed.criteria());
|
||||
|
||||
if (changed) {
|
||||
existing.setDescription(seed.description());
|
||||
existing.setCriteria(new HashMap<>(seed.criteria()));
|
||||
badgeService.modifyBadge(existing);
|
||||
}
|
||||
},
|
||||
() -> badgeService.createBadge(
|
||||
new BadgeDTO(
|
||||
seed.name(),
|
||||
seed.description(),
|
||||
seed.category(),
|
||||
new HashMap<>(seed.criteria())
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private static Seed seed(String name, String desc, BadgeCategory category, Map<String, Integer> criteria) {
|
||||
return new Seed(name, desc, category, criteria);
|
||||
}
|
||||
|
||||
private record Seed(String name, String description, BadgeCategory category, Map<String, Integer> criteria) {}
|
||||
|
||||
private ArrayList<Seed> generateSeeds() {
|
||||
ArrayList<Seed> seeds = new ArrayList<>();
|
||||
seeds.add(seed("Eröffnung", "Ein kleiner Schritt für einen Menschen, aber ein großer für die Umwelt", BadgeCategory.MOBILITY_SCORE, Map.of()));
|
||||
//---------------- Mobility Score ----------------
|
||||
seeds.add(seed("Mobility Score I", "Sammle 100 Mobility-Score-Punkte", BadgeCategory.MOBILITY_SCORE, Map.of("MOBILITY_SCORE", 100)));
|
||||
seeds.add(seed("Mobility Score II", "Sammle 250 Mobility-Score-Punkte", BadgeCategory.MOBILITY_SCORE, Map.of("MOBILITY_SCORE", 250)));
|
||||
seeds.add(seed("Mobility Score III", "Sammle 500 Mobility-Score-Punkte", BadgeCategory.MOBILITY_SCORE, Map.of("MOBILITY_SCORE", 500)));
|
||||
seeds.add(seed("Mobility Score IV", "Sammle 750 Mobility-Score-Punkte", BadgeCategory.MOBILITY_SCORE, Map.of("MOBILITY_SCORE", 750)));
|
||||
seeds.add(seed("Mobility Score V", "Sammle 1.000 Mobility-Score-Punkte", BadgeCategory.MOBILITY_SCORE, Map.of("MOBILITY_SCORE", 1000)));
|
||||
seeds.add(seed("Mobility Score VI", "Sammle 1.500 Mobility-Score-Punkte", BadgeCategory.MOBILITY_SCORE, Map.of("MOBILITY_SCORE", 1500)));
|
||||
seeds.add(seed("Mobility Score VII", "Sammle 2.000 Mobility-Score-Punkte", BadgeCategory.MOBILITY_SCORE, Map.of("MOBILITY_SCORE", 2000)));
|
||||
seeds.add(seed("Mobility Score VIII","Sammle 3.000 Mobility-Score-Punkte", BadgeCategory.MOBILITY_SCORE, Map.of("MOBILITY_SCORE", 3000)));
|
||||
seeds.add(seed("Mobility Score IX", "Sammle 4.000 Mobility-Score-Punkte", BadgeCategory.MOBILITY_SCORE, Map.of("MOBILITY_SCORE", 4000)));
|
||||
seeds.add(seed("Mobility Score X", "Sammle 5.000 Mobility-Score-Punkte", BadgeCategory.MOBILITY_SCORE, Map.of("MOBILITY_SCORE", 5000)));
|
||||
seeds.add(seed("Mobility Score XI", "Sammle 6.500 Mobility-Score-Punkte", BadgeCategory.MOBILITY_SCORE, Map.of("MOBILITY_SCORE", 6500)));
|
||||
seeds.add(seed("Mobility Score XII", "Sammle 8.000 Mobility-Score-Punkte", BadgeCategory.MOBILITY_SCORE, Map.of("MOBILITY_SCORE", 8000)));
|
||||
seeds.add(seed("Over 9000! Mobility Score", "Erreiche 9000 Mobility Score-Punkte", BadgeCategory.MOBILITY_SCORE, Map.of("MOBILITY_SCORE", 9000)));
|
||||
seeds.add(seed("Mobilitätspunkte XIII","Sammle 10.000 Mobility-Score-Punkte", BadgeCategory.MOBILITY_SCORE, Map.of("MOBILITY_SCORE", 10000)));
|
||||
// ---------------- Public Transport ----------------
|
||||
seeds.add(seed("ÖPNV-Fan I", "Fahre 20 km mit ÖPNV", BadgeCategory.OPNV, Map.of("KM_PUBLIC_TRANSPORT", 20)));
|
||||
seeds.add(seed("ÖPNV-Fan II", "Fahre 50 km mit ÖPNV", BadgeCategory.OPNV, Map.of("KM_PUBLIC_TRANSPORT", 50)));
|
||||
seeds.add(seed("ÖPNV-Fan III", "Fahre 100 km mit ÖPNV", BadgeCategory.OPNV, Map.of("KM_PUBLIC_TRANSPORT", 100)));
|
||||
seeds.add(seed("ÖPNV-Fan IV", "Fahre 150 km mit ÖPNV", BadgeCategory.OPNV, Map.of("KM_PUBLIC_TRANSPORT", 150)));
|
||||
seeds.add(seed("ÖPNV-Fan V", "Fahre 200 km mit ÖPNV", BadgeCategory.OPNV, Map.of("KM_PUBLIC_TRANSPORT", 200)));
|
||||
seeds.add(seed("ÖPNV-Fan VI", "Fahre 300 km mit ÖPNV", BadgeCategory.OPNV, Map.of("KM_PUBLIC_TRANSPORT", 300)));
|
||||
seeds.add(seed("ÖPNV-Fan VII", "Fahre 400 km mit ÖPNV", BadgeCategory.OPNV, Map.of("KM_PUBLIC_TRANSPORT", 400)));
|
||||
seeds.add(seed("ÖPNV-Fan VIII","Fahre 500 km mit ÖPNV", BadgeCategory.OPNV, Map.of("KM_PUBLIC_TRANSPORT", 500)));
|
||||
seeds.add(seed("ÖPNV-Fan IX", "Fahre 750 km mit ÖPNV", BadgeCategory.OPNV, Map.of("KM_PUBLIC_TRANSPORT", 750)));
|
||||
seeds.add(seed("ÖPNV-Fan X", "Fahre 1.000 km mit ÖPNV", BadgeCategory.OPNV, Map.of("KM_PUBLIC_TRANSPORT", 1_000)));
|
||||
// ---------------- Walking ----------------
|
||||
seeds.add(seed("Walker I", "Gehe 5 km zu Fuß", BadgeCategory.WALKING, Map.of("KM_WALKED", 5)));
|
||||
seeds.add(seed("Walker II", "Gehe 10 km zu Fuß", BadgeCategory.WALKING, Map.of("KM_WALKED", 10)));
|
||||
seeds.add(seed("Walker III", "Gehe 20 km zu Fuß", BadgeCategory.WALKING, Map.of("KM_WALKED", 20)));
|
||||
seeds.add(seed("Walker IV", "Gehe 30 km zu Fuß", BadgeCategory.WALKING, Map.of("KM_WALKED", 30)));
|
||||
seeds.add(seed("Walker V", "Gehe 50 km zu Fuß", BadgeCategory.WALKING, Map.of("KM_WALKED", 50)));
|
||||
seeds.add(seed("Walker VI", "Gehe 75 km zu Fuß", BadgeCategory.WALKING, Map.of("KM_WALKED", 75)));
|
||||
seeds.add(seed("Walker VII", "Gehe 100 km zu Fuß", BadgeCategory.WALKING, Map.of("KM_WALKED", 100)));
|
||||
seeds.add(seed("Walker VIII","Gehe 150 km zu Fuß", BadgeCategory.WALKING, Map.of("KM_WALKED", 150)));
|
||||
seeds.add(seed("Walker IX", "Gehe 200 km zu Fuß", BadgeCategory.WALKING, Map.of("KM_WALKED", 200)));
|
||||
seeds.add(seed("Walker X", "Gehe 300 km zu Fuß", BadgeCategory.WALKING, Map.of("KM_WALKED", 300)));
|
||||
//---------------- Cycling ----------------
|
||||
seeds.add(seed("Bike Commuter I", "Fahre 10 km mit dem Rad", BadgeCategory.BICYCLE, Map.of("KM_CYCLED", 10)));
|
||||
seeds.add(seed("Bike Commuter II", "Fahre 25 km mit dem Rad", BadgeCategory.BICYCLE, Map.of("KM_CYCLED", 25)));
|
||||
seeds.add(seed("Bike Commuter III", "Fahre 50 km mit dem Rad", BadgeCategory.BICYCLE, Map.of("KM_CYCLED", 50)));
|
||||
seeds.add(seed("Bike Commuter IV", "Fahre 75 km mit dem Rad", BadgeCategory.BICYCLE, Map.of("KM_CYCLED", 75)));
|
||||
seeds.add(seed("Bike Commuter V", "Fahre 100 km mit dem Rad", BadgeCategory.BICYCLE, Map.of("KM_CYCLED", 100)));
|
||||
seeds.add(seed("Bike Commuter VI", "Fahre 150 km mit dem Rad", BadgeCategory.BICYCLE, Map.of("KM_CYCLED", 150)));
|
||||
seeds.add(seed("Bike Commuter VII", "Fahre 200 km mit dem Rad", BadgeCategory.BICYCLE, Map.of("KM_CYCLED", 200)));
|
||||
seeds.add(seed("Bike Commuter VIII","Fahre 300 km mit dem Rad", BadgeCategory.BICYCLE, Map.of("KM_CYCLED", 300)));
|
||||
seeds.add(seed("Bike Commuter IX", "Fahre 400 km mit dem Rad", BadgeCategory.BICYCLE, Map.of("KM_CYCLED", 400)));
|
||||
seeds.add(seed("Bike Commuter X", "Fahre 500 km mit dem Rad", BadgeCategory.BICYCLE, Map.of("KM_CYCLED", 500)));
|
||||
//---------------- XP ----------------
|
||||
seeds.add(seed("Silber-Pendler", "Erreiche 500 XP", BadgeCategory.XP, Map.of("XP", 500)));
|
||||
seeds.add(seed("Gold-Pendler", "Erreiche 1.000 XP", BadgeCategory.XP, Map.of("XP", 1_000)));
|
||||
seeds.add(seed("Platin-Pendler", "Erreiche 2.000 XP", BadgeCategory.XP, Map.of("XP", 2_000)));
|
||||
seeds.add(seed("Diamant-Pendler", "Erreiche 3.000 XP", BadgeCategory.XP, Map.of("XP", 3_000)));
|
||||
seeds.add(seed("XP-Jäger I", "Erreiche 5.000 XP", BadgeCategory.XP, Map.of("XP", 5_000)));
|
||||
seeds.add(seed("XP-Jäger II", "Erreiche 7.500 XP", BadgeCategory.XP, Map.of("XP", 7_500)));
|
||||
seeds.add(seed("XP-Jäger III", "Erreiche 10.000 XP", BadgeCategory.XP, Map.of("XP", 10_000)));
|
||||
seeds.add(seed("XP-Meister I", "Erreiche 12.500 XP", BadgeCategory.XP, Map.of("XP", 12_500)));
|
||||
seeds.add(seed("XP-Meister II", "Erreiche 15.000 XP", BadgeCategory.XP, Map.of("XP", 15_000)));
|
||||
seeds.add(seed("XP-Meister III", "Erreiche 20.000 XP", BadgeCategory.XP, Map.of("XP", 20_000)));
|
||||
seeds.add(seed("XP-Champion I", "Erreiche 25.000 XP", BadgeCategory.XP, Map.of("XP", 25_000)));
|
||||
seeds.add(seed("XP-Champion II", "Erreiche 30.000 XP", BadgeCategory.XP, Map.of("XP", 30_000)));
|
||||
seeds.add(seed("XP-Champion III", "Erreiche 40.000 XP", BadgeCategory.XP, Map.of("XP", 40_000)));
|
||||
seeds.add(seed("XP-Legende I", "Erreiche 50.000 XP", BadgeCategory.XP, Map.of("XP", 50_000)));
|
||||
seeds.add(seed("XP-Legende II", "Erreiche 75.000 XP", BadgeCategory.XP, Map.of("XP", 75_000)));
|
||||
seeds.add(seed("XP-Legende III", "Erreiche 100.000 XP", BadgeCategory.XP, Map.of("XP", 100_000)));
|
||||
return seeds;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package SuMoC.backend.gamification.badges.mapper;
|
||||
|
||||
import SuMoC.backend.gamification.badges.models.Badge;
|
||||
import SuMoC.backend.gamification.badges.models.BadgeDTO;
|
||||
import SuMoC.backend.gamification.badges.models.BadgeImageEntity;
|
||||
import SuMoC.backend.images.ImageBase64Util;
|
||||
import org.mapstruct.Mapper;
|
||||
|
||||
import java.util.Base64;
|
||||
|
||||
@Mapper
|
||||
public interface BadgeMapper {
|
||||
|
||||
static BadgeDTO toDTO(Badge badge) {
|
||||
BadgeDTO dto = new BadgeDTO();
|
||||
dto.setId(badge.getId());
|
||||
dto.setName(badge.getName());
|
||||
dto.setDescription(badge.getDescription());
|
||||
dto.setCategory(badge.getCategory());
|
||||
dto.setCriteria(badge.getCriteria());
|
||||
dto.setImageBase64(ImageBase64Util.encode(badge.getImage().getImageData()));
|
||||
|
||||
return dto;
|
||||
}
|
||||
|
||||
static Badge toEntity(BadgeDTO dto) {
|
||||
Badge badge = new Badge();
|
||||
badge.setId(dto.getId());
|
||||
badge.setName(dto.getName());
|
||||
badge.setDescription(dto.getDescription());
|
||||
badge.setCategory(dto.getCategory());
|
||||
badge.setCriteria(dto.getCriteria());
|
||||
badge.setImage(new BadgeImageEntity(badge, ImageBase64Util.decode(dto.getImageBase64())));
|
||||
|
||||
return badge;
|
||||
}
|
||||
|
||||
static void updateEntityFromDTO(Badge badge, BadgeDTO dto) {
|
||||
badge.setName(dto.getName());
|
||||
badge.setDescription(dto.getDescription());
|
||||
badge.setCategory(dto.getCategory());
|
||||
badge.setCriteria(dto.getCriteria());
|
||||
|
||||
// Bild aktualisieren
|
||||
if (dto.getImageBase64() != null && !dto.getImageBase64().isEmpty()) {
|
||||
byte[] imageData = Base64.getDecoder().decode(dto.getImageBase64());
|
||||
if (badge.getImage() == null) {
|
||||
badge.setImage(new BadgeImageEntity(badge, imageData));
|
||||
} else {
|
||||
badge.getImage().setImageData(imageData);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
-1
@@ -1,4 +1,4 @@
|
||||
package SuMoC.backend.gamification.badges;
|
||||
package SuMoC.backend.gamification.badges.mapper;
|
||||
|
||||
import SuMoC.backend.gamification.badges.models.Badge;
|
||||
import SuMoC.backend.gamification.badges.models.UserBadge;
|
||||
@@ -6,6 +6,7 @@ import SuMoC.backend.gamification.badges.models.UserBadgeDTO;
|
||||
import org.mapstruct.Mapper;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
@@ -19,9 +20,15 @@ public class UserBadgeMapper {
|
||||
dto.setBadgeId(badge.getId());
|
||||
dto.setName(badge.getName());
|
||||
dto.setDescription(badge.getDescription());
|
||||
dto.setCategory(badge.getCategory());
|
||||
dto.setCriteria(badge.getCriteria());
|
||||
dto.setAwardedAt(userBadge.getAwardedAt());
|
||||
|
||||
if (badge.getImage() != null && badge.getImage().getImageData() != null) {
|
||||
String base64Image = Base64.getEncoder().encodeToString(badge.getImage().getImageData());
|
||||
dto.setImageBase64(base64Image);
|
||||
}
|
||||
|
||||
return dto;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package SuMoC.backend.gamification.badges.models;
|
||||
|
||||
import SuMoC.backend.images.ImageEntity;
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
@@ -13,6 +14,10 @@ public class Badge {
|
||||
|
||||
private String name;
|
||||
private String description;
|
||||
private BadgeCategory category;
|
||||
|
||||
@OneToOne(mappedBy = "badge", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||
private BadgeImageEntity image;
|
||||
|
||||
@ElementCollection
|
||||
@CollectionTable(name = "badge_criteria", joinColumns = @JoinColumn(name = "badge_id"))
|
||||
@@ -20,34 +25,33 @@ public class Badge {
|
||||
@Column(name = "criteria_value")
|
||||
private Map<String, Integer> criteria = new HashMap<>();
|
||||
|
||||
// Constructor
|
||||
|
||||
/**
|
||||
* Badge without criteria - if the Badge shouldn't be reachable by now
|
||||
* @param name name of the badge
|
||||
* @param description a short description
|
||||
*/
|
||||
public Badge(String name, String description) {
|
||||
// Constructors
|
||||
public Badge(String name, String description, BadgeCategory category) {
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.category = category;
|
||||
this.image = new BadgeImageEntity(this, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Badge with criteria
|
||||
* @param name name of the badge
|
||||
* @param description a short description
|
||||
* @param criteria criteria Mapping StatField-Long
|
||||
*/
|
||||
public Badge(String name, String description, Map<String, Integer> criteria) {
|
||||
public Badge(String name, String description, BadgeCategory category, Map<String, Integer> criteria) {
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.category = category;
|
||||
this.criteria = criteria;
|
||||
}
|
||||
|
||||
public Badge(String name, String description, BadgeCategory category, Map<String, Integer> criteria, BadgeImageEntity image) {
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.category = category;
|
||||
this.criteria = criteria;
|
||||
this.image = image;
|
||||
|
||||
}
|
||||
|
||||
public Badge() {}
|
||||
|
||||
// Getter & Setter
|
||||
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
|
||||
@@ -57,6 +61,17 @@ public class Badge {
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String description) { this.description = description; }
|
||||
|
||||
public BadgeCategory getCategory() { return category; }
|
||||
public void setCategory(BadgeCategory category) { this.category = category; }
|
||||
|
||||
public BadgeImageEntity getImage() { return image; }
|
||||
public void setImage(BadgeImageEntity image) {
|
||||
this.image = image;
|
||||
if (image != null) {
|
||||
image.setBadge(this);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Integer> getCriteria() { return criteria; }
|
||||
public void setCriteria(Map<String, Integer> criteria) { this.criteria = criteria; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package SuMoC.backend.gamification.badges.models;
|
||||
|
||||
public enum BadgeCategory {
|
||||
XP,
|
||||
MOBILITY_SCORE,
|
||||
CO2,
|
||||
|
||||
IDLE,
|
||||
WALKING,
|
||||
BICYCLE,
|
||||
ESCOOTER,
|
||||
BUS,
|
||||
TRAM,
|
||||
TRAIN,
|
||||
CAR,
|
||||
|
||||
OPNV,
|
||||
|
||||
MONTHLY, // Get 10000 XP in January; Travel over 100 KM by train in May
|
||||
HIDDEN
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package SuMoC.backend.gamification.badges.models;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class BadgeDTO {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String description;
|
||||
private BadgeCategory category;
|
||||
private Map<String, Integer> criteria;
|
||||
private String imageBase64;
|
||||
|
||||
// Constructors
|
||||
public BadgeDTO() {}
|
||||
|
||||
public BadgeDTO(String name, String description, BadgeCategory category) {
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.category = category;
|
||||
}
|
||||
|
||||
public BadgeDTO(Long id, String name, String description, BadgeCategory category) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.category = category;
|
||||
}
|
||||
|
||||
public BadgeDTO(String name, String description, BadgeCategory category, Map<String, Integer> criteria) {
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.category = category;
|
||||
this.criteria = criteria;
|
||||
}
|
||||
|
||||
public BadgeDTO(Long id, String name, String description, BadgeCategory category, Map<String, Integer> criteria) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.category = category;
|
||||
this.criteria = criteria;
|
||||
}
|
||||
|
||||
public BadgeDTO(String name, String description, BadgeCategory category, Map<String, Integer> criteria, String imageBase64) {
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.category = category;
|
||||
this.criteria = criteria;
|
||||
this.imageBase64 = imageBase64;
|
||||
}
|
||||
|
||||
public BadgeDTO(Long id, String name, String description, BadgeCategory category, Map<String, Integer> criteria, String imageBase64) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.category = category;
|
||||
this.criteria = criteria;
|
||||
this.imageBase64 = imageBase64;
|
||||
}
|
||||
|
||||
// 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 BadgeCategory getCategory() { return category; }
|
||||
public void setCategory(BadgeCategory category) { this.category = category; }
|
||||
|
||||
public Map<String, Integer> getCriteria() { return criteria; }
|
||||
public void setCriteria(Map<String, Integer> criteria) { this.criteria = criteria; }
|
||||
|
||||
public String getImageBase64() { return imageBase64; }
|
||||
public void setImageBase64(String imageBase64) { this.imageBase64 = imageBase64; }
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package SuMoC.backend.gamification.badges.models;
|
||||
|
||||
import SuMoC.backend.images.ImageEntity;
|
||||
import jakarta.persistence.DiscriminatorValue;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.OneToOne;
|
||||
|
||||
@Entity
|
||||
@DiscriminatorValue("BADGE")
|
||||
public class BadgeImageEntity extends ImageEntity {
|
||||
|
||||
@OneToOne
|
||||
@JoinColumn(name = "badge_id")
|
||||
private Badge badge;
|
||||
|
||||
public BadgeImageEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
public BadgeImageEntity(Badge badge, byte[] imageData) {
|
||||
super(imageData);
|
||||
this.badge = badge;
|
||||
}
|
||||
|
||||
public Badge getBadge() {
|
||||
return badge;
|
||||
}
|
||||
|
||||
public void setBadge(Badge badge) {
|
||||
this.badge = badge;
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,11 @@ public class UserBadgeDTO {
|
||||
private Long badgeId;
|
||||
private String name;
|
||||
private String description;
|
||||
private BadgeCategory category;
|
||||
private Map<String, Integer> criteria;
|
||||
private LocalDateTime awardedAt;
|
||||
private String imageBase64;
|
||||
|
||||
|
||||
// Getter & Setter
|
||||
|
||||
@@ -38,6 +41,14 @@ public class UserBadgeDTO {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public BadgeCategory getCategory() {
|
||||
return this.category;
|
||||
}
|
||||
|
||||
public void setCategory(BadgeCategory category) {
|
||||
this.category = category;
|
||||
}
|
||||
|
||||
public Map<String, Integer> getCriteria() {
|
||||
return criteria;
|
||||
}
|
||||
@@ -53,4 +64,7 @@ public class UserBadgeDTO {
|
||||
public void setAwardedAt(LocalDateTime awardedAt) {
|
||||
this.awardedAt = awardedAt;
|
||||
}
|
||||
|
||||
public String getImageBase64() { return imageBase64; }
|
||||
public void setImageBase64(String imageBase64) { this.imageBase64 = imageBase64; }
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
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().isBlank()) {
|
||||
byte[] bytes = ImageBase64Util.decode(dto.getBase64image());
|
||||
ChallengeImageEntity img = new ChallengeImageEntity();
|
||||
img.setImageData(bytes);
|
||||
challenge.setImage(img);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
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
|
||||
@Transactional
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
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, fetch = FetchType.LAZY)
|
||||
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;
|
||||
if (image != null) {
|
||||
image.setChallenge(this);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -2,22 +2,24 @@ package SuMoC.backend.gamification.scoretable;
|
||||
|
||||
import SuMoC.backend.gamification.scoretable.models.Leaderboard;
|
||||
import SuMoC.backend.gamification.Timeframe;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
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 org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/leaderboard")
|
||||
class LeaderboardController {
|
||||
public class LeaderboardController {
|
||||
private LeaderboardService leaderboardService;
|
||||
|
||||
@Autowired
|
||||
@@ -27,28 +29,34 @@ class LeaderboardController {
|
||||
|
||||
@Operation(summary = "Get the global score table")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Successfully retrieved global score table"),
|
||||
@ApiResponse(responseCode = "200", description = "Successfully retrieved global score table",
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = Leaderboard.class))),
|
||||
@ApiResponse(responseCode = "304", description = "Not modified"),
|
||||
@ApiResponse(responseCode = "400", description = "Bad request")
|
||||
|
||||
})
|
||||
@GetMapping("/getLeaderboard")
|
||||
public ResponseEntity<Leaderboard> getLeaderboard(@AuthenticationPrincipal User user,
|
||||
@RequestParam Timeframe timeframe,
|
||||
public ResponseEntity<Leaderboard> getLeaderboard(@RequestParam Timeframe timeframe,
|
||||
@RequestParam String field) {
|
||||
Leaderboard leaderboard = this.leaderboardService.getLeaderboard(user, timeframe, field);
|
||||
return ResponseEntity.status(HttpStatus.OK).body(leaderboard);
|
||||
Leaderboard leaderboard = this.leaderboardService.getLeaderboard( timeframe, field);
|
||||
return ResponseEntity.ok()
|
||||
.cacheControl(CacheControl.maxAge(24, TimeUnit.HOURS))
|
||||
.body(leaderboard);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get the friend score table")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Successfully retrieved friend score table"),
|
||||
@ApiResponse(responseCode = "200", description = "Successfully retrieved friend score table",
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = Leaderboard.class))),
|
||||
@ApiResponse(responseCode = "304", description = "Not modified"),
|
||||
@ApiResponse(responseCode = "400", description = "Bad request")
|
||||
})
|
||||
@GetMapping("/getFriendLeaderboard")
|
||||
public ResponseEntity<Leaderboard> getFriendLeaderboard(@AuthenticationPrincipal User user,
|
||||
@RequestParam Timeframe timeframe,
|
||||
public ResponseEntity<Leaderboard> getFriendLeaderboard(@RequestParam Timeframe timeframe,
|
||||
@RequestParam String field) {
|
||||
Leaderboard leaderboard = this.leaderboardService.getFriendLeaderboard(user, timeframe, field);
|
||||
return ResponseEntity.status(HttpStatus.OK).body(leaderboard);
|
||||
Leaderboard leaderboard = this.leaderboardService.getFriendLeaderboard(timeframe, field);
|
||||
return ResponseEntity.ok()
|
||||
.cacheControl(CacheControl.maxAge(24, TimeUnit.HOURS))
|
||||
.body(leaderboard);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,9 +3,13 @@ package SuMoC.backend.gamification.scoretable;
|
||||
import SuMoC.backend.gamification.scoretable.models.Leaderboard;
|
||||
import SuMoC.backend.gamification.Timeframe;
|
||||
import SuMoC.backend.gamification.scoretable.models.LeaderboardEntry;
|
||||
import SuMoC.backend.images.ImageBase64Util;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.service.CurrentUserService;
|
||||
import SuMoC.backend.user.service.FriendshipService;
|
||||
import SuMoC.backend.user.service.PrivacyService;
|
||||
import SuMoC.backend.user.stats.*;
|
||||
import jakarta.transaction.Transactional;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -14,69 +18,64 @@ import org.springframework.stereotype.Service;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class LeaderboardService {
|
||||
private final FriendshipService friendshipService;
|
||||
private final StatsListRepository statsListRepository;
|
||||
private final CurrentUserService currentUser;
|
||||
private final PrivacyService privacyService;
|
||||
|
||||
public LeaderboardService(
|
||||
FriendshipService friendshipService,
|
||||
StatsListRepository statsListRepository
|
||||
) {
|
||||
StatsListRepository statsListRepository,
|
||||
CurrentUserService currentUser,
|
||||
PrivacyService privacyService) {
|
||||
|
||||
this.friendshipService = friendshipService;
|
||||
this.statsListRepository = statsListRepository;
|
||||
this.currentUser = currentUser;
|
||||
this.privacyService = privacyService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Method Overload to get the score table with a default limit of 30.
|
||||
* @param user
|
||||
* @param timeframe
|
||||
* @param field
|
||||
* @return
|
||||
*/
|
||||
public Leaderboard getLeaderboard(User user, Timeframe timeframe, String field) {
|
||||
return getLeaderboard(user, timeframe, field, 30);
|
||||
public Leaderboard getLeaderboard(Timeframe timeframe, String field) {
|
||||
return getLeaderboard( timeframe, field, 30);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the global score table for a given user, timeframe, score type, and limit.
|
||||
* @param user
|
||||
* @param timeframe
|
||||
* @param field
|
||||
* @param limit
|
||||
* @return
|
||||
*/
|
||||
public Leaderboard getLeaderboard(User user, Timeframe timeframe, String field, int limit) {
|
||||
public Leaderboard getLeaderboard(Timeframe timeframe, String field, int limit) {
|
||||
User user = currentUser.get();
|
||||
List<StatsList> topStats = getTopStats(timeframe, field, limit);
|
||||
|
||||
List<Long> topUserIds = topStats.stream()
|
||||
.map(stats -> stats.getUser().getId())
|
||||
.toList();
|
||||
|
||||
Map<Long, FriendshipService.NameWithFriendship> nameMap =
|
||||
friendshipService.getPrivateNameIfFriendshipAccepted(user, topUserIds)
|
||||
.stream()
|
||||
.collect(Collectors.toMap(FriendshipService.NameWithFriendship::id, n -> n));
|
||||
|
||||
Leaderboard leaderboard = new Leaderboard();
|
||||
leaderboard.setEntries(new ArrayList<>());
|
||||
|
||||
List<User> friendships = friendshipService.getAcceptedFriends(user);
|
||||
for (StatsList statsList : topStats) {
|
||||
User topUser = statsList.getUser();
|
||||
FriendshipService.NameWithFriendship nwf = nameMap.get(topUser.getId());
|
||||
|
||||
String displayName = (nwf != null) ? nwf.name() : topUser.getPublicName();
|
||||
boolean friendship = (nwf != null) && nwf.friendship();
|
||||
boolean ps = privacyService.checkVisibility(user, topUser.getId());
|
||||
|
||||
LeaderboardEntry entry = new LeaderboardEntry(
|
||||
topUser.getId(),
|
||||
displayName,
|
||||
friendship,
|
||||
statsList.getStatValue(timeframe, field)
|
||||
ps ? topUser.getPrivateName() : topUser.getPublicName(),
|
||||
friendships
|
||||
.stream()
|
||||
.anyMatch(o -> o.getId().equals(topUser.getId())),
|
||||
statsList.getStatValue(timeframe, field),
|
||||
ps ? ImageBase64Util.encode(topUser.getProfileImage().getImageData()) : null
|
||||
);
|
||||
|
||||
leaderboard.getEntries().add(entry);
|
||||
@@ -86,8 +85,9 @@ public class LeaderboardService {
|
||||
LeaderboardEntry userEntry = new LeaderboardEntry(
|
||||
user.getId(),
|
||||
user.getPrivateName(),
|
||||
true,
|
||||
user.getStats().getStatValue(timeframe, field)
|
||||
false,
|
||||
user.getStats().getStatValue(timeframe, field),
|
||||
ImageBase64Util.encode(user.getProfileImage().getImageData())
|
||||
);
|
||||
leaderboard.getEntries().add(userEntry);
|
||||
}
|
||||
@@ -103,52 +103,53 @@ public class LeaderboardService {
|
||||
|
||||
/**
|
||||
* Method Overload to get the friend score table with a default limit of 30.
|
||||
* @param user
|
||||
* @param timeframe
|
||||
* @param field
|
||||
* @return
|
||||
*/
|
||||
public Leaderboard getFriendLeaderboard(User user, Timeframe timeframe, String field) {
|
||||
return getFriendLeaderboard(user, timeframe, field, 30);
|
||||
public Leaderboard getFriendLeaderboard(Timeframe timeframe, String field) {
|
||||
return getFriendLeaderboard(timeframe, field, 30);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get the friend score table for a given user, timeframe, score type, and limit.
|
||||
* @param user
|
||||
* @param timeframe
|
||||
* @param field
|
||||
* @param limit
|
||||
* @return
|
||||
*/
|
||||
public Leaderboard getFriendLeaderboard(User user, Timeframe timeframe, String field, int limit) {
|
||||
public Leaderboard getFriendLeaderboard(Timeframe timeframe, String field, int limit) {
|
||||
User user = currentUser.get();
|
||||
List<User> friends = friendshipService.getAcceptedFriends(user);
|
||||
|
||||
Leaderboard leaderboard = new Leaderboard();
|
||||
leaderboard.setEntries(new ArrayList<>()); // Initialize list
|
||||
leaderboard.setEntries(new ArrayList<>());
|
||||
|
||||
for (User friend : friends) {
|
||||
StatsList statsList = friend.getStats();
|
||||
if (statsList != null) {
|
||||
Long statValue = statsList.getStatValue(timeframe, field);
|
||||
if (statValue != null) {
|
||||
LeaderboardEntry entry = new LeaderboardEntry(
|
||||
friend.getId(),
|
||||
friend.getPrivateName(),
|
||||
true,
|
||||
statValue
|
||||
);
|
||||
leaderboard.getEntries().add(entry);
|
||||
}
|
||||
}
|
||||
boolean ps = privacyService.checkVisibility(user, friend.getId());
|
||||
Long statValue = statsList.getStatValue(timeframe, field);
|
||||
|
||||
LeaderboardEntry entry = new LeaderboardEntry(
|
||||
friend.getId(),
|
||||
ps ? friend.getPrivateName() : friend.getPublicName(),
|
||||
true,
|
||||
statValue,
|
||||
ps ? ImageBase64Util.encode(friend.getProfileImage().getImageData()): null
|
||||
|
||||
);
|
||||
leaderboard.getEntries().add(entry);
|
||||
}
|
||||
|
||||
if (leaderboard.getEntries().stream().noneMatch(e -> e.getUserId().equals(user.getId()))) {
|
||||
leaderboard.getEntries().add(new LeaderboardEntry(
|
||||
user.getId(),
|
||||
user.getPrivateName(),
|
||||
true,
|
||||
user.getStats().getStatValue(timeframe, field)
|
||||
false,
|
||||
user.getStats().getStatValue(timeframe, field),
|
||||
ImageBase64Util.encode(user.getProfileImage().getImageData())
|
||||
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
@@ -5,12 +5,15 @@ public class LeaderboardEntry {
|
||||
private String username;
|
||||
private Boolean isFriend;
|
||||
private Long score;
|
||||
private String base64ProfilePicture;
|
||||
|
||||
public LeaderboardEntry(Long userId, String username, Boolean isFriend, Long score) {
|
||||
public LeaderboardEntry(Long userId, String username, Boolean isFriend, Long score, String base64ProfilePicture) {
|
||||
this.userId = userId;
|
||||
this.username = username;
|
||||
this.isFriend = isFriend;
|
||||
this.score = score;
|
||||
this.base64ProfilePicture = base64ProfilePicture;
|
||||
|
||||
}
|
||||
|
||||
public LeaderboardEntry() {}
|
||||
@@ -27,4 +30,12 @@ public class LeaderboardEntry {
|
||||
|
||||
public Long getScore() { return score; }
|
||||
public void setScore(Long score) { this.score = score; }
|
||||
|
||||
public String getBase64ProfilePicture() {
|
||||
return base64ProfilePicture;
|
||||
}
|
||||
|
||||
public void setBase64ProfilePicture(String base64ProfilePicture) {
|
||||
this.base64ProfilePicture = base64ProfilePicture;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class CartaLocationClient implements GeocodingClient {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CartaLocationClient.class);
|
||||
|
||||
private final WebClient cartaLocationClient;
|
||||
|
||||
public CartaLocationClient(WebClient cartaLocationClient) {
|
||||
this.cartaLocationClient = cartaLocationClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<GeocodingResponse> reverse(double lat, double lon) {
|
||||
String query = lat + "," + lon;
|
||||
logger.debug("Calling Carta location API with query: {}, type: BUILDING, limit: 3", query);
|
||||
|
||||
return cartaLocationClient.get()
|
||||
.uri(uriBuilder -> {
|
||||
var uri = uriBuilder.path("/location/search")
|
||||
.queryParam("q", query)
|
||||
.queryParam("type", "BUILDING")
|
||||
.queryParam("limit", 3)
|
||||
.build();
|
||||
logger.debug("Full Carta location API URL: {}", uri);
|
||||
return uri;
|
||||
})
|
||||
.retrieve()
|
||||
.bodyToMono(CartaLocationResponse[].class)
|
||||
.doOnNext(responses -> logger.debug("Received {} results from Carta location API",
|
||||
responses != null ? responses.length : 0))
|
||||
.map(responses -> {
|
||||
if (responses == null || responses.length == 0) {
|
||||
logger.error("Carta location API returned empty response for coordinates: lat={}, lon={}", lat, lon);
|
||||
return new GeocodingResponse(null);
|
||||
}
|
||||
logger.debug("Using first result: {}", responses[0]);
|
||||
return mapToGeocodingResponse(responses[0]);
|
||||
})
|
||||
.onErrorResume(error -> {
|
||||
logger.error("Error calling Carta location API for coordinates: lat={}, lon={}", lat, lon, error);
|
||||
return Mono.just(new GeocodingResponse(null));
|
||||
});
|
||||
}
|
||||
|
||||
private GeocodingResponse mapToGeocodingResponse(CartaLocationResponse response) {
|
||||
Map<String, String> addressMap = new HashMap<>();
|
||||
|
||||
// Map Carta fields to Nominatim-style address format
|
||||
if (response.building() != null) {
|
||||
addressMap.put("house_number", response.building());
|
||||
}
|
||||
if (response.street() != null) {
|
||||
addressMap.put("road", response.street());
|
||||
}
|
||||
if (response.suburb() != null) {
|
||||
addressMap.put("suburb", response.suburb());
|
||||
}
|
||||
if (response.city() != null) {
|
||||
addressMap.put("city", response.city());
|
||||
}
|
||||
if (response.state() != null) {
|
||||
addressMap.put("state", response.state());
|
||||
}
|
||||
if (response.postcode() != null) {
|
||||
addressMap.put("postcode", response.postcode());
|
||||
}
|
||||
if (response.country() != null) {
|
||||
addressMap.put("country", response.country());
|
||||
}
|
||||
|
||||
return new GeocodingResponse(addressMap);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record CartaLocationResponse(
|
||||
Double longitude,
|
||||
Double latitude,
|
||||
String country,
|
||||
String state,
|
||||
String county,
|
||||
String city,
|
||||
String suburb,
|
||||
String neighborhood,
|
||||
String locality,
|
||||
String street,
|
||||
String building,
|
||||
String postcode,
|
||||
String name
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -1,26 +1,27 @@
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import SuMoC.backend.nominatim.NominatimClient;
|
||||
import SuMoC.backend.nominatim.ReverseResponse;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Service
|
||||
public class GeoCodingService {
|
||||
|
||||
private final NominatimClient nominatimClient;
|
||||
private final GeocodingClient geocodingClient;
|
||||
|
||||
public GeoCodingService(NominatimClient nominatimClient) {
|
||||
this.nominatimClient = nominatimClient;
|
||||
public GeoCodingService(GeocodingClient geocodingClient) {
|
||||
this.geocodingClient = geocodingClient;
|
||||
}
|
||||
|
||||
public Mono<AddressDTO> getAddress(double lat, double lon) {
|
||||
return nominatimClient.reverse(lat, lon)
|
||||
return geocodingClient.reverse(lat, lon)
|
||||
.map(this::mapToAddressDTO);
|
||||
}
|
||||
|
||||
private AddressDTO mapToAddressDTO(ReverseResponse response) {
|
||||
private AddressDTO mapToAddressDTO(GeocodingResponse response) {
|
||||
var addressMap = response.address();
|
||||
if (addressMap == null) {
|
||||
return new AddressDTO(null, null, null, null, null, null, null, null, null, null);
|
||||
}
|
||||
return new AddressDTO(
|
||||
addressMap.get("house_number"),
|
||||
addressMap.get("road"),
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public interface GeocodingClient {
|
||||
Mono<GeocodingResponse> reverse(double lat, double lon);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
|
||||
@Configuration
|
||||
@EnableConfigurationProperties(GeocodingProperties.class)
|
||||
public class GeocodingConfig {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnProperty(name = "geocoding.provider", havingValue = "docker", matchIfMissing = true)
|
||||
public WebClient nominatimWebClient(GeocodingProperties properties) {
|
||||
return WebClient.builder()
|
||||
.baseUrl(properties.nominatim().baseUrl())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean(name = "geocodingClient")
|
||||
@ConditionalOnProperty(name = "geocoding.provider", havingValue = "docker", matchIfMissing = true)
|
||||
public GeocodingClient nominatimClient(WebClient nominatimWebClient) {
|
||||
return new NominatimClient(nominatimWebClient);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnProperty(name = "geocoding.provider", havingValue = "carta")
|
||||
public WebClient cartaLocationWebClient(GeocodingProperties properties) {
|
||||
return WebClient.builder()
|
||||
.baseUrl(properties.carta().baseUrl())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean(name = "geocodingClient")
|
||||
@ConditionalOnProperty(name = "geocoding.provider", havingValue = "carta")
|
||||
public GeocodingClient cartaLocationClient(WebClient cartaLocationWebClient) {
|
||||
return new CartaLocationClient(cartaLocationWebClient);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@ConfigurationProperties(prefix = "geocoding")
|
||||
public record GeocodingProperties(
|
||||
String provider,
|
||||
NominatimConfig nominatim,
|
||||
CartaConfig carta
|
||||
) {
|
||||
public record NominatimConfig(
|
||||
String baseUrl
|
||||
) {
|
||||
}
|
||||
|
||||
public record CartaConfig(
|
||||
String baseUrl
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public record GeocodingResponse(
|
||||
Map<String, String> address
|
||||
) {
|
||||
}
|
||||
|
||||
+8
-8
@@ -1,20 +1,18 @@
|
||||
package SuMoC.backend.nominatim;
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Service
|
||||
public class NominatimClient {
|
||||
public class NominatimClient implements GeocodingClient {
|
||||
|
||||
private final WebClient nominatimClient;
|
||||
|
||||
public NominatimClient(@Qualifier("nominatimWebClient") WebClient nominatimClient) {
|
||||
public NominatimClient(WebClient nominatimClient) {
|
||||
this.nominatimClient = nominatimClient;
|
||||
}
|
||||
|
||||
public Mono<ReverseResponse> reverse(double lat, double lon) {
|
||||
@Override
|
||||
public Mono<GeocodingResponse> reverse(double lat, double lon) {
|
||||
return nominatimClient.get()
|
||||
.uri(uriBuilder -> uriBuilder.path("/reverse")
|
||||
.queryParam("lat", lat)
|
||||
@@ -22,6 +20,8 @@ public class NominatimClient {
|
||||
.queryParam("format", "jsonv2")
|
||||
.build())
|
||||
.retrieve()
|
||||
.bodyToMono(ReverseResponse.class);
|
||||
.bodyToMono(ReverseResponse.class)
|
||||
.map(response -> new GeocodingResponse(response.address()));
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,4 +1,4 @@
|
||||
package SuMoC.backend.nominatim;
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
@@ -15,3 +15,4 @@ public record ReverseResponse(
|
||||
@JsonProperty("address") Map<String, String> address
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package SuMoC.backend.images;
|
||||
|
||||
import java.util.Base64;
|
||||
|
||||
public final class ImageBase64Util {
|
||||
|
||||
private ImageBase64Util() {
|
||||
}
|
||||
|
||||
public static String encode(byte[] imageData) {
|
||||
if (imageData == null || imageData.length == 0) {
|
||||
return null;
|
||||
}
|
||||
return Base64.getEncoder().encodeToString(imageData);
|
||||
}
|
||||
|
||||
public static byte[] decode(String base64Image) {
|
||||
if (base64Image == null || base64Image.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return Base64.getDecoder().decode(base64Image);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package SuMoC.backend.images;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
@Entity
|
||||
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
|
||||
@DiscriminatorColumn(name = "dtype")
|
||||
public class ImageEntity {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private int id;
|
||||
|
||||
@Lob
|
||||
//@Column(columnDefinition = "BYTEA")
|
||||
//@Column(columnDefinition = "BLOB")
|
||||
private byte[] imageData;
|
||||
|
||||
public ImageEntity() {
|
||||
}
|
||||
|
||||
public ImageEntity(byte[] imageData) {
|
||||
this.imageData = imageData;
|
||||
}
|
||||
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public byte[] getImageData() {
|
||||
return imageData;
|
||||
}
|
||||
|
||||
public void setImageData(byte[] imageData) {
|
||||
this.imageData = imageData;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package SuMoC.backend.images;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface ImageEntityRepository extends JpaRepository<ImageEntity, Long> {
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package SuMoC.backend.logger;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
@Controller
|
||||
public class LogPageController {
|
||||
|
||||
@GetMapping("/logs")
|
||||
public String logs(Model model) throws IOException {
|
||||
String content = Files.readString(Path.of("logs/app.log"));
|
||||
model.addAttribute("logs", content);
|
||||
return "logs";
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package SuMoC.backend.nominatim;
|
||||
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
|
||||
@Configuration
|
||||
@EnableConfigurationProperties(NominatimProperties.class)
|
||||
public class NominatimClientConfig {
|
||||
|
||||
@Bean
|
||||
public WebClient nominatimWebClient(NominatimProperties properties) {
|
||||
return WebClient.builder()
|
||||
.baseUrl(properties.baseUrl())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package SuMoC.backend.nominatim;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@ConfigurationProperties(prefix = "nominatim")
|
||||
public record NominatimProperties(
|
||||
String baseUrl
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package SuMoC.backend.notification;
|
||||
|
||||
import SuMoC.backend.notification.enums.NotificationProvider;
|
||||
import SuMoC.backend.notification.services.NotificationTokenService;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/notifications")
|
||||
@RequiredArgsConstructor
|
||||
public class NotificationController {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
private final NotificationTokenService notificationTokenService;
|
||||
|
||||
// TODO extend security context with user id to avoid unnecessary db query
|
||||
private User getAuthenticatedUser() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
return userRepository.findByEmail(authentication.getName()).orElseThrow(() -> new RuntimeException("User not found"));
|
||||
}
|
||||
|
||||
@PutMapping("/register-device-token")
|
||||
@Operation(summary = "Registers a device token for push notifications for the authenticated user.")
|
||||
public ResponseEntity<Void> registerDeviceToken(@RequestBody RegisterDeviceTokenRequest request) {
|
||||
User user = getAuthenticatedUser();
|
||||
notificationTokenService.registerDeviceToken(user, request.provider(), request.token());
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@PutMapping("/unregister-device-token")
|
||||
@Operation(description = "Unregisters the device token for push notifications for the authenticated user.")
|
||||
public ResponseEntity<Void> unregisterDeviceToken() {
|
||||
User user = getAuthenticatedUser();
|
||||
notificationTokenService.unregisterDeviceToken(user);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
// Simple record for request body
|
||||
public record RegisterDeviceTokenRequest(String token, NotificationProvider provider) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
# Notification System Overview
|
||||
|
||||
This document provides an overview of the notification system for client developers integrating with the backend. It
|
||||
explains notification types, expected payloads, and device token registration.
|
||||
|
||||
## Notification Types
|
||||
|
||||
Notifications sent to clients are categorized by `NotificationType`:
|
||||
|
||||
- **TREND**: Informs users about changes in their mobility trends (e.g., reduced car usage). See
|
||||
`TrendNotificationService`.
|
||||
- **ADHOC_ALTERNATIVE**: Suggests a more sustainable alternative after a recent trip upload. See
|
||||
`AdHocSuggestionService`.
|
||||
- **REGULAR_TRIP_ALTERNATIVE**: Suggests an alternative for a detected regular trip (e.g., weekly commute). See
|
||||
`RegularTripSuggestionService`.
|
||||
- **FRIENDSHIP_REQUEST_RECEIVED**: Notifies about a new pending friendship request.
|
||||
|
||||
See `NotificationType.java` for the full enum.
|
||||
|
||||
## Notification Payloads
|
||||
|
||||
Each notification type includes a data payload. The main DTOs in the notification body are:
|
||||
|
||||
- **TREND**: Contains a list of `TrendDetectionDTO` objects, each describing a detected trend for the user. The
|
||||
structure includes fields such as `userId`, `timespan`, `type`, `attribute`, `deltaType`, `changeValue`, and
|
||||
`trendConnotation`. See `TrendDetectionDTO.java` for details.
|
||||
- **ADHOC_ALTERNATIVE**: Contains a list of `RouteDTO` objects representing the best alternative(s) for a recent trip (
|
||||
see `AdHocSuggestionService`).
|
||||
- **REGULAR_TRIP_ALTERNATIVE**: Contains a list of 1 or 2 `RouteDTO` objects for the best alternative(s) to a detected
|
||||
regular trip, depending on user preferences (e.g., if `preferPhysicalActivity` is set, two alternatives may be
|
||||
included). See `RegularTripSuggestionService` and `RegularTripDetectionService` for details.
|
||||
- **FRIENDSHIP_REQUEST_RECEIVED**: Contains a `friendshipDTO` where `friend` is the user who sent the request. See
|
||||
`FriendshipDTO.java`.
|
||||
|
||||
## Device Token Registration
|
||||
|
||||
To receive push notifications, clients must register their device token. Token registration is handled in the
|
||||
`NotificationController`. The backend stores or updates the token for the authenticated user.
|
||||
|
||||
### Unregistering Device Token
|
||||
|
||||
When a user logs out, the client should call the device token unregistration endpoint to remove the device token from
|
||||
the backend. This ensures the user will no longer receive push notifications on that device after logout.
|
||||
|
||||
- **Endpoint:** `PUT /notifications/unregister-device-token`
|
||||
|
||||
---
|
||||
|
||||
## For Backend Developers
|
||||
|
||||
To queue notifications for users, use the `NotificationSchedulerService` as the main entry point. This service provides
|
||||
methods to schedule notifications with the appropriate type and payload. See `NotificationSchedulerService.java` for
|
||||
usage details.
|
||||
|
||||
---
|
||||
For further details, refer to the respective service and DTO classes in the codebase.
|
||||
@@ -0,0 +1,29 @@
|
||||
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")
|
||||
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
|
||||
));
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package SuMoC.backend.notification.enums;
|
||||
|
||||
public enum NotificationProvider {
|
||||
FIREBASE,
|
||||
}
|
||||
@@ -1,7 +1,16 @@
|
||||
package SuMoC.backend.notification.enums;
|
||||
|
||||
public enum NotificationStatus {
|
||||
/**
|
||||
* Has never been sent successfully. Will be retried.
|
||||
*/
|
||||
PENDING,
|
||||
/**
|
||||
* Has been sent successfully.
|
||||
*/
|
||||
SENT,
|
||||
/**
|
||||
* Has failed to send and will not be retried.
|
||||
*/
|
||||
FAILED
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package SuMoC.backend.notification.enums;
|
||||
|
||||
/**
|
||||
* Notification type that will be included in the data sent to the mobile devices.
|
||||
*/
|
||||
public enum NotificationType {
|
||||
/**
|
||||
* Informing about a change in mobility trends, e.g. driving less car.
|
||||
*/
|
||||
TREND,
|
||||
/**
|
||||
* An alternative suggestion following the upload of a recent trip.
|
||||
*/
|
||||
ADHOC_ALTERNATIVE,
|
||||
/**
|
||||
* An alternative suggestion that refers to a detected regular trip.
|
||||
* E.g. user drives by car every monday at 8 am and there is a sustainable alternative.
|
||||
*/
|
||||
REGULAR_TRIP_ALTERNATIVE,
|
||||
/**
|
||||
* A notification informing the user about a new pending friendship request.
|
||||
*/
|
||||
FRIENDSHIP_REQUEST_RECEIVED,
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package SuMoC.backend.notification.factories;
|
||||
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
import SuMoC.backend.trend.TrendDetection;
|
||||
import SuMoC.backend.trend.services.TrendMessageGenerator;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class TrendNotificationFactory {
|
||||
|
||||
private final TrendMessageGenerator trendMessageGenerator;
|
||||
|
||||
public Notification createNotification(TrendDetection trend) {
|
||||
return Notification.builder()
|
||||
.user(trend.getUser())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
package SuMoC.backend.notification.interfaces;
|
||||
|
||||
public interface NotificationPublisher {
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
package SuMoC.backend.notification.interfaces;
|
||||
|
||||
public interface NotificationSender {
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package SuMoC.backend.notification.interfaces;
|
||||
|
||||
public interface Notifieable {
|
||||
Long getUserId();
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package SuMoC.backend.notification.interfaces;
|
||||
|
||||
import java.time.LocalTime;
|
||||
|
||||
public interface NotifieableWithTime {
|
||||
Long getUserId();
|
||||
|
||||
LocalTime getEarliestTimeOfDayToSend();
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
package SuMoC.backend.notification.models;
|
||||
|
||||
import SuMoC.backend.notification.enums.NotificationStatus;
|
||||
import SuMoC.backend.notification.enums.NotificationType;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalTime;
|
||||
|
||||
@Entity
|
||||
@@ -25,7 +26,11 @@ public class Notification {
|
||||
private User user;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String message;
|
||||
@Enumerated(EnumType.STRING)
|
||||
private NotificationType type;
|
||||
|
||||
@Column(columnDefinition = "TEXT")
|
||||
private String data; // Store serialized DTO as JSON
|
||||
|
||||
/**
|
||||
* Time of day from which on a notification might be sent.
|
||||
@@ -36,11 +41,25 @@ public class Notification {
|
||||
private LocalTime earliestTimeOfDayToSend;
|
||||
|
||||
@Column(nullable = false)
|
||||
private NotificationStatus status;
|
||||
@Enumerated(EnumType.STRING)
|
||||
private NotificationStatus status = NotificationStatus.PENDING;
|
||||
|
||||
/**
|
||||
* Number of retry attempts made to send this notification.
|
||||
*/
|
||||
@Column(nullable = false)
|
||||
private int failedSendAttempts = 0;
|
||||
|
||||
@Column
|
||||
private String lastFailureReason;
|
||||
|
||||
@Column(nullable = false)
|
||||
private int retryCount;
|
||||
private Instant createdAt;
|
||||
|
||||
@Column(nullable = false)
|
||||
private LocalDateTime createdAt;
|
||||
@Column(nullable = true)
|
||||
private Instant sentAt = null;
|
||||
|
||||
public void incrementFailedSendAttempts() {
|
||||
this.failedSendAttempts++;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package SuMoC.backend.notification.models;
|
||||
|
||||
import SuMoC.backend.notification.enums.NotificationProvider;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
@Entity
|
||||
public class NotificationToken {
|
||||
|
||||
@Id
|
||||
@Column(name = "user_id", nullable = false, unique = true)
|
||||
private Long userId;
|
||||
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private NotificationProvider provider;
|
||||
|
||||
@Column(nullable = false, length = 512)
|
||||
private String token;
|
||||
}
|
||||
@@ -1,7 +1,42 @@
|
||||
package SuMoC.backend.notification.repositories;
|
||||
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
import SuMoC.backend.user.models.User;
|
||||
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.LocalTime;
|
||||
import java.util.List;
|
||||
|
||||
public interface NotificationRepository extends JpaRepository<Notification, Long> {
|
||||
@Query("""
|
||||
SELECT n
|
||||
FROM Notification n
|
||||
LEFT JOIN FETCH n.user u
|
||||
LEFT JOIN FETCH u.notificationToken
|
||||
WHERE n.status = 'PENDING'
|
||||
AND n.earliestTimeOfDayToSend <= :currentTime
|
||||
""")
|
||||
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 deleteAllByUser(User user);
|
||||
}
|
||||
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package SuMoC.backend.notification.repositories;
|
||||
|
||||
import SuMoC.backend.notification.models.NotificationToken;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface NotificationTokenRepository extends JpaRepository<NotificationToken, Long> {
|
||||
Optional<NotificationToken> findByUserId(Long userId);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package SuMoC.backend.notification.services;
|
||||
|
||||
import SuMoC.backend.security.dtos.PasswordResetDTO;
|
||||
import SuMoC.backend.security.models.PasswordResetToken;
|
||||
import SuMoC.backend.security.services.AuthenticationService;
|
||||
import jdk.dynalink.linker.support.SimpleLinkRequest;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.mail.MailException;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class EmailService {
|
||||
|
||||
@Autowired
|
||||
private JavaMailSender mailSender;
|
||||
|
||||
@Async
|
||||
public void sendPasswordResetEmail(String email, String otp_code) throws MailException {
|
||||
SimpleMailMessage message = new SimpleMailMessage();
|
||||
|
||||
message.setFrom("SuMoC@outlook.de");
|
||||
message.setTo(email);
|
||||
message.setSubject("Dein Passwort-Reset Code");
|
||||
message.setText("Hallo!\n\nDein OTP Code lautet: " + otp_code +
|
||||
"\nDieser Code ist für " + String.valueOf(PasswordResetToken.EXPIRY_TIME_MINUTES) + " Minuten gültig.");
|
||||
|
||||
mailSender.send(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
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;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* This service is the main entry point to schedule notifications to be sent to a users' mobile device.
|
||||
* It creates Notification entities in the database with status PENDING which are then later processed by the notification worker.
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class NotificationSchedulerService {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
private final NotificationRepository notificationRepository;
|
||||
|
||||
private final EntityManager entityManager;
|
||||
|
||||
/**
|
||||
* Can be used to schedule multiple notifications at once. Notifieable interface allows sending to multiple users.
|
||||
* dataBodies need to be serializable to JSON.
|
||||
*
|
||||
* @param dataBodies
|
||||
* @param notificationType
|
||||
* @param earliestTimeOfDayToSend
|
||||
*/
|
||||
public void scheduleAll(List<Notifieable> dataBodies,
|
||||
NotificationType notificationType,
|
||||
LocalTime earliestTimeOfDayToSend
|
||||
) {
|
||||
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(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())
|
||||
.failedSendAttempts(0)
|
||||
.build();
|
||||
}).toList();
|
||||
|
||||
notificationRepository.saveAll(notifications);
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules a notification to be sent to the specified user.
|
||||
* Data body needs to be serializable to JSON.
|
||||
*
|
||||
* @param userId
|
||||
* @param dataBody
|
||||
* @param notificationType
|
||||
* @param earliestTimeOfDayToSend TOD from which on the notification can be sent. If null, send as soon as possible.
|
||||
*/
|
||||
public void schedule(
|
||||
Long userId,
|
||||
Object dataBody,
|
||||
NotificationType notificationType,
|
||||
LocalTime earliestTimeOfDayToSend
|
||||
) {
|
||||
String dataBodyJson;
|
||||
try {
|
||||
dataBodyJson = objectMapper.writeValueAsString(dataBody);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to serialize notification data body", e);
|
||||
}
|
||||
|
||||
if (earliestTimeOfDayToSend == null) {
|
||||
earliestTimeOfDayToSend = LocalTime.now();
|
||||
}
|
||||
|
||||
User userProxy = entityManager.getReference(User.class, userId);
|
||||
|
||||
Notification notification = Notification.builder()
|
||||
.user(userProxy)
|
||||
.type(notificationType)
|
||||
.data(dataBodyJson)
|
||||
.earliestTimeOfDayToSend(earliestTimeOfDayToSend)
|
||||
.status(NotificationStatus.PENDING)
|
||||
.createdAt(Instant.now())
|
||||
.failedSendAttempts(0)
|
||||
.build();
|
||||
|
||||
notificationRepository.save(notification);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package SuMoC.backend.notification.services;
|
||||
|
||||
import SuMoC.backend.firebase.FirebaseMessageBuilder;
|
||||
import SuMoC.backend.notification.config.NotificationProperties;
|
||||
import SuMoC.backend.notification.enums.NotificationStatus;
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
import SuMoC.backend.notification.models.NotificationToken;
|
||||
import SuMoC.backend.notification.repositories.NotificationRepository;
|
||||
import SuMoC.backend.notification.repositories.NotificationTokenRepository;
|
||||
import com.google.api.core.ApiFuture;
|
||||
import com.google.api.core.ApiFutureCallback;
|
||||
import com.google.api.core.ApiFutures;
|
||||
import com.google.common.util.concurrent.MoreExecutors;
|
||||
import com.google.firebase.messaging.FirebaseMessaging;
|
||||
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
|
||||
public class NotificationSender {
|
||||
|
||||
private final FirebaseMessageBuilder firebaseMessageBuilder;
|
||||
private final Logger logger = Logger.getLogger(NotificationSender.class.getName());
|
||||
private final FirebaseMessaging firebaseMessaging;
|
||||
private final NotificationRepository notificationRepository;
|
||||
private final NotificationProperties notificationProperties;
|
||||
|
||||
public NotificationSender(
|
||||
NotificationTokenRepository notificationTokenRepository,
|
||||
FirebaseMessageBuilder firebaseMessageBuilder,
|
||||
@Autowired(required = false) FirebaseMessaging firebaseMessaging,
|
||||
NotificationRepository notificationRepository, NotificationProperties notificationProperties
|
||||
) {
|
||||
this.firebaseMessageBuilder = firebaseMessageBuilder;
|
||||
this.firebaseMessaging = firebaseMessaging;
|
||||
this.notificationRepository = notificationRepository;
|
||||
this.notificationProperties = notificationProperties;
|
||||
}
|
||||
|
||||
public void sendNotification(Notification notification) {
|
||||
NotificationToken token = notification.getUser().getNotificationToken();
|
||||
|
||||
if (token == null) {
|
||||
logger.warning("No notification token found notification id: " + notification.getId());
|
||||
notification.incrementFailedSendAttempts();
|
||||
notification.setLastFailureReason("No notification token found for user");
|
||||
setFailedIfLimitExceeded(notification);
|
||||
notificationRepository.save(notification);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (token.getProvider()) {
|
||||
case FIREBASE -> sendViaFirebase(token, notification);
|
||||
}
|
||||
}
|
||||
|
||||
private void sendViaFirebase(NotificationToken token, Notification notification) {
|
||||
if (firebaseMessaging == null) {
|
||||
logger.warning("FirebaseMessaging not configured");
|
||||
return;
|
||||
}
|
||||
|
||||
Message message = firebaseMessageBuilder.generateMessage(notification, token.getToken());
|
||||
|
||||
ApiFuture<String> future = firebaseMessaging.sendAsync(message);
|
||||
ApiFutures.addCallback(future, new ApiFutureCallback<String>() {
|
||||
@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());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Throwable t) {
|
||||
notification.incrementFailedSendAttempts();
|
||||
notification.setLastFailureReason(t.getMessage());
|
||||
setFailedIfLimitExceeded(notification);
|
||||
notificationRepository.save(notification);
|
||||
logger.severe("Failed to send notification with id:" + notification.getId() + " " + t.getMessage());
|
||||
}
|
||||
}, MoreExecutors.directExecutor());
|
||||
|
||||
}
|
||||
|
||||
private void setFailedIfLimitExceeded(Notification notification) {
|
||||
if (notification.getFailedSendAttempts() >= notificationProperties.getMaxFailedSendAttempts()) {
|
||||
notification.setStatus(NotificationStatus.FAILED);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package SuMoC.backend.notification.services;
|
||||
|
||||
import SuMoC.backend.notification.enums.NotificationProvider;
|
||||
import SuMoC.backend.notification.models.NotificationToken;
|
||||
import SuMoC.backend.notification.repositories.NotificationTokenRepository;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class NotificationTokenService {
|
||||
|
||||
private final NotificationTokenRepository notificationTokenRepository;
|
||||
|
||||
public void registerDeviceToken(User user, NotificationProvider provider, String token) {
|
||||
var existingToken = notificationTokenRepository.findByUserId(user.getId());
|
||||
if (existingToken.isPresent()) {
|
||||
var notificationToken = existingToken.get();
|
||||
notificationToken.setToken(token);
|
||||
notificationTokenRepository.save(notificationToken);
|
||||
} else {
|
||||
var newToken = new NotificationToken();
|
||||
newToken.setUserId(user.getId());
|
||||
newToken.setProvider(provider);
|
||||
newToken.setToken(token);
|
||||
notificationTokenRepository.save(newToken);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void unregisterDeviceToken(User user) {
|
||||
var existingToken = notificationTokenRepository.findByUserId(user.getId());
|
||||
existingToken.ifPresent(token -> {
|
||||
user.setNotificationToken(null);
|
||||
notificationTokenRepository.delete(token);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package SuMoC.backend.notification.services;
|
||||
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
import SuMoC.backend.notification.repositories.NotificationRepository;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
@RequiredArgsConstructor
|
||||
public class NotificationWorker {
|
||||
|
||||
private final NotificationRepository notificationRepository;
|
||||
|
||||
private final NotificationSender notificationSender;
|
||||
|
||||
private final NotificationLimiter notificationLimiter;
|
||||
|
||||
/**
|
||||
* Process all pending notifications.
|
||||
*/
|
||||
public void run() {
|
||||
List<Notification> pendingNotifications =
|
||||
notificationRepository.findPendingNotificationsToSend(LocalTime.now());
|
||||
|
||||
var notificationSafeToSend = notificationLimiter.enforceHourlyLimits(pendingNotifications);
|
||||
|
||||
for (Notification notification : notificationSafeToSend) {
|
||||
notificationSender.sendNotification(notification);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up old notifications.
|
||||
*/
|
||||
public void cleanUpOldNotifications() {
|
||||
// Delete notifications older than 30 days
|
||||
notificationRepository.deleteNotificationsOlder(Instant.now().minus(Duration.ofDays(30)));
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package SuMoC.backend.notification.services;
|
||||
|
||||
import SuMoC.backend.notification.factories.TrendNotificationFactory;
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
import SuMoC.backend.notification.repositories.NotificationRepository;
|
||||
import SuMoC.backend.trend.TrendDetection;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class TrendNotificationService {
|
||||
|
||||
private final NotificationRepository notificationRepository;
|
||||
|
||||
private final TrendNotificationFactory trendNotificationFactory;
|
||||
|
||||
public List<Notification> generateTrendNotifications(List<TrendDetection> trendList) {
|
||||
List<Notification> notificationList = trendList.stream().map(trendNotificationFactory::createNotification).toList();
|
||||
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ public class DetectorConfiguration {
|
||||
havingValue = "iterative",
|
||||
matchIfMissing = true
|
||||
)
|
||||
public Detector iterativeClusterer(RegularTripDetectionProperties properties) {
|
||||
public IterativeClusterer iterativeClusterer(RegularTripDetectionProperties properties) {
|
||||
return new IterativeClusterer(properties);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ public class RegularTripDetectionProperties {
|
||||
/**
|
||||
* Time window in days to look back for detecting regular trips.
|
||||
*/
|
||||
private Integer detectionTimeWindowDays = 30;
|
||||
private Integer detectionTimeWindowDays = 40;
|
||||
|
||||
/**
|
||||
* Maximum time difference in minutes between trips to be considered the same regular trip.
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
package SuMoC.backend.regulartrip.dtos;
|
||||
|
||||
import SuMoC.backend.h3.H3Service;
|
||||
import SuMoC.backend.trip.Modality;
|
||||
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
|
||||
import lombok.*;
|
||||
|
||||
import java.time.LocalTime;
|
||||
import java.time.*;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@@ -18,7 +19,7 @@ import java.util.List;
|
||||
public class DetectedRegularTripDTO {
|
||||
private long userId;
|
||||
private Modality modality;
|
||||
private int dayOfWeek;
|
||||
private DayOfWeek dayOfWeek;
|
||||
private LocalTime departureWindowStart;
|
||||
private LocalTime departureWindowEnd;
|
||||
private LocalTime arrivalWindowStart;
|
||||
@@ -28,4 +29,56 @@ public class DetectedRegularTripDTO {
|
||||
private List<String> startH3neighbours;
|
||||
private List<String> endH3Neighbours;
|
||||
private List<RegularTripDetectionDTO> supportingTrips;
|
||||
|
||||
/**
|
||||
* Mock dto that should trigger available alternative.
|
||||
*/
|
||||
public static DetectedRegularTripDTO getTriggeringMock(H3Service h3Service, Long userId) {
|
||||
String h3_schutzenbahn = "8a1fa535568ffff"; // Essen Schuetzenbahn
|
||||
String h3_essen_hbf = "8a1fa535020ffff"; // Essen Hbf
|
||||
|
||||
return DetectedRegularTripDTO.builder()
|
||||
.userId(userId)
|
||||
.modality(Modality.CAR)
|
||||
.dayOfWeek(LocalDateTime.now().getDayOfWeek())
|
||||
.departureWindowStart(LocalTime.now().plusMinutes(20))
|
||||
.departureWindowEnd(LocalTime.now().plusMinutes(30))
|
||||
.arrivalWindowStart(LocalTime.now().plusMinutes(60))
|
||||
.arrivalWindowEnd(LocalTime.now().plusMinutes(70))
|
||||
.startH3Center(h3_schutzenbahn) // Essen Schuetzenbahn
|
||||
.endH3Center(h3_essen_hbf) // Essen Hbf
|
||||
.startH3neighbours(h3Service.getRoutePatternNeighbors(h3_schutzenbahn))
|
||||
.endH3Neighbours(h3Service.getRoutePatternNeighbors(h3_essen_hbf))
|
||||
.supportingTrips(List.of(
|
||||
RegularTripDetectionDTO.builder()
|
||||
.tripId(userId)
|
||||
.userId(userId)
|
||||
.startH3Cell(h3_schutzenbahn)
|
||||
.endH3Cell(h3_essen_hbf)
|
||||
.startTime(LocalTime.now().plusMinutes(20).atDate(LocalDateTime.now().toLocalDate()).toInstant(ZoneOffset.UTC))
|
||||
.endTime(LocalTime.now().plusMinutes(60).atDate(LocalDateTime.now().toLocalDate()).toInstant(ZoneOffset.UTC))
|
||||
.mainModality(Modality.CAR)
|
||||
.startH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(h3_schutzenbahn))
|
||||
.endH3CellKRingNeighboors(h3Service.getRoutePatternNeighbors(h3_essen_hbf))
|
||||
.build()
|
||||
))
|
||||
.build();
|
||||
}
|
||||
|
||||
public Instant getAverageArrivalTime() {
|
||||
long totalSeconds = 0;
|
||||
for (RegularTripDetectionDTO trip : supportingTrips) {
|
||||
totalSeconds += trip.getEndTime().getEpochSecond();
|
||||
}
|
||||
long averageSeconds = totalSeconds / supportingTrips.size();
|
||||
return Instant.ofEpochSecond(averageSeconds);
|
||||
}
|
||||
|
||||
public int getAverageDurationMinutes() {
|
||||
int totalDuration = 0;
|
||||
for (RegularTripDetectionDTO trip : supportingTrips) {
|
||||
totalDuration += trip.getDurationMinutes();
|
||||
}
|
||||
return totalDuration / supportingTrips.size();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
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;
|
||||
@Schema(description = "Backend trip ids of the trips that support this detected regular trip.")
|
||||
private List<Long> supportingTripIds;
|
||||
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();
|
||||
minimalDTO.supportingTripIds = regularTrip.getSupportingTrips().stream()
|
||||
.map(RegularTripDetectionDTO::getTripId)
|
||||
.toList();
|
||||
return minimalDTO;
|
||||
}
|
||||
|
||||
private static LocalTime getEarliestArrival(List<RegularTripDetectionDTO> supportingTrips) {
|
||||
var earliest = supportingTrips.stream()
|
||||
.map(RegularTripDetectionDTO::getEndTime)
|
||||
.min(Comparator.naturalOrder())
|
||||
.orElseThrow();
|
||||
return LocalTime.ofInstant(earliest, ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
private static LocalTime getLatestArrival(List<RegularTripDetectionDTO> supportingTrips) {
|
||||
var latest = supportingTrips.stream()
|
||||
.map(RegularTripDetectionDTO::getEndTime)
|
||||
.max(Comparator.naturalOrder())
|
||||
.orElseThrow();
|
||||
return LocalTime.ofInstant(latest, ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
private static LocalTime getEarliestDeparture(List<RegularTripDetectionDTO> supportingTrips) {
|
||||
var earliest = supportingTrips.stream()
|
||||
.map(RegularTripDetectionDTO::getStartTime)
|
||||
.min(Comparator.naturalOrder())
|
||||
.orElseThrow();
|
||||
return LocalTime.ofInstant(earliest, ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
private static LocalTime getLatestDeparture(List<RegularTripDetectionDTO> supportingTrips) {
|
||||
var latest = supportingTrips.stream()
|
||||
.map(RegularTripDetectionDTO::getStartTime)
|
||||
.max(Comparator.naturalOrder())
|
||||
.orElseThrow();
|
||||
return LocalTime.ofInstant(latest, ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -7,33 +7,35 @@ import SuMoC.backend.trip.Modality;
|
||||
import SuMoC.backend.trip.TripMapper;
|
||||
import SuMoC.backend.trip.TripRepository;
|
||||
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class RegularTripDetectionService {
|
||||
|
||||
RegularTripDetectionProperties properties;
|
||||
private final RegularTripDetectionProperties properties;
|
||||
|
||||
TripRepository tripRepository;
|
||||
private final TripRepository tripRepository;
|
||||
|
||||
TripMapper tripMapper;
|
||||
private final TripMapper tripMapper;
|
||||
|
||||
Detector tripDetector;
|
||||
private final Detector tripDetector;
|
||||
|
||||
/**
|
||||
* Detects regular trips for all users based on saved trip data and RegularTripDetectionProperties.
|
||||
* Detects regular trips for the current day of the week for all users based on saved trip data and RegularTripDetectionProperties.
|
||||
* This is the main method that orchestrates the detection process and should be used to detect trips
|
||||
* we want to suggest alternatives for.
|
||||
*/
|
||||
public HashMap<Long, List<DetectedRegularTripDTO>> detectRegularCarTrips() {
|
||||
var tripsByUser = getTripsByUser(Modality.CAR);
|
||||
public HashMap<Long, List<DetectedRegularTripDTO>> detectRegularCarTripsByUserForDayOfWeek(DayOfWeek dayOfWeek) {
|
||||
var tripsByUser = getTripsByUser(Modality.CAR, dayOfWeek);
|
||||
|
||||
// TODO this could be parallelized in the future
|
||||
HashMap<Long, List<DetectedRegularTripDTO>> results = new HashMap<>();
|
||||
for (Long userId : tripsByUser.keySet()) {
|
||||
results.put(userId, tripDetector.detectRegularTrips(tripsByUser.get(userId)));
|
||||
@@ -42,9 +44,9 @@ public class RegularTripDetectionService {
|
||||
return results;
|
||||
}
|
||||
|
||||
private HashMap<Long, List<RegularTripDetectionDTO>> getTripsByUser(Modality modality) {
|
||||
private HashMap<Long, List<RegularTripDetectionDTO>> getTripsByUser(Modality modality, DayOfWeek dayOfWeek) {
|
||||
Instant fromDate = Instant.now().minusSeconds(properties.getDetectionTimeWindowDays() * 24 * 60 * 60);
|
||||
List<RegularTripDetectionDTO> dtoList = tripMapper.toRegularTripDetectionDTOS(tripRepository.findAllValidFromDateWithMainModality(fromDate, modality));
|
||||
List<RegularTripDetectionDTO> dtoList = tripMapper.toRegularTripDetectionDTOS(tripRepository.findAllValidFromDateWithMainModalityOnCertainWeekday(fromDate, modality, dayOfWeek));
|
||||
|
||||
HashMap<Long, List<RegularTripDetectionDTO>> tripsByUser = new HashMap<>();
|
||||
for (RegularTripDetectionDTO dto : dtoList) {
|
||||
|
||||
@@ -16,8 +16,8 @@ public class AdHocRoutingProperties extends RoutingProperties {
|
||||
|
||||
public AdHocRoutingProperties() {
|
||||
super();
|
||||
setAcceptableAdditionalMultiplierRegular(1.30);
|
||||
setAcceptableAdditionalMultiplierPrefersPhysical(1.6);
|
||||
setAcceptableAdditionalMultiplierRegular(2.0);
|
||||
setAcceptableAdditionalMultiplierPrefersPhysical(2.0);
|
||||
setMinimumAcceptedAdditionalSecondsRegular(5 * 60);
|
||||
setMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity(5 * 60);
|
||||
}
|
||||
|
||||
+17
-16
@@ -1,12 +1,13 @@
|
||||
package SuMoC.backend.routing;
|
||||
package SuMoC.backend.routing.controller;
|
||||
|
||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
|
||||
import SuMoC.backend.routing.dtos.RoutingPreferencesDTO;
|
||||
import SuMoC.backend.routing.services.RoutingService;
|
||||
import SuMoC.backend.routing.services.AlternativeRoutingService;
|
||||
import SuMoC.backend.routing.services.RoutingPreferencesService;
|
||||
import SuMoC.backend.user.service.CurrentUserService;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
@@ -20,28 +21,28 @@ import java.util.logging.Logger;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/routing/alternative")
|
||||
public class RoutingController {
|
||||
@RequiredArgsConstructor
|
||||
class RoutingAlternativeController {
|
||||
|
||||
private final Logger logger = Logger.getLogger(RoutingController.class.getName());
|
||||
private final Logger logger = Logger.getLogger(RoutingAlternativeController.class.getName());
|
||||
|
||||
private final RoutingService routingService;
|
||||
private final AlternativeRoutingService alternativeRoutingService;
|
||||
|
||||
@Autowired
|
||||
public RoutingController(RoutingService routingService) {
|
||||
this.routingService = routingService;
|
||||
}
|
||||
private final RoutingPreferencesService routingPreferencesService;
|
||||
|
||||
private final CurrentUserService currentUserService;
|
||||
|
||||
@PostMapping("/request")
|
||||
@Schema(description = "Calculates alternative, sustainable routes for the request. The delta of departure and arrival in the requestdto is used as baseline to determine if alternatives are acceptable.")
|
||||
public ResponseEntity<List<RouteDTO>> requestAlternativeRoutes(@Valid @RequestBody RoutingAlternativeRequestDTO routingAlternativeRequestDTO) {
|
||||
try {
|
||||
if (routingAlternativeRequestDTO.getRoutingPreferencesDTO() == null) { // Use default preferences if none are provided
|
||||
// TODO we might want to also save users preferences in the future
|
||||
var preferences = new RoutingPreferencesDTO(); // use default preferences
|
||||
routingAlternativeRequestDTO.setRoutingPreferencesDTO(preferences);
|
||||
|
||||
if (routingAlternativeRequestDTO.getRoutingPreferencesDTO() == null) {
|
||||
// This automatically uses default preferences for unauthenticated users
|
||||
routingAlternativeRequestDTO.setRoutingPreferencesDTO(routingPreferencesService.getRoutingPreferencesForCurrentUser());
|
||||
}
|
||||
|
||||
var routeDTOs = routingService.determineAlternativeRoutesOnUserRequest(routingAlternativeRequestDTO);
|
||||
var routeDTOs = alternativeRoutingService.determineAlternativeRoutesOnUserRequest(routingAlternativeRequestDTO);
|
||||
return ResponseEntity.ok(routeDTOs);
|
||||
} catch (WebClientRequestException e) {
|
||||
// nominatim container is not up yet, we return mock
|
||||
@@ -0,0 +1,54 @@
|
||||
package SuMoC.backend.routing.controller;
|
||||
|
||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||
import SuMoC.backend.routing.dtos.RoutingDirectionsRequestDTO;
|
||||
import SuMoC.backend.routing.services.DirectionsRoutingService;
|
||||
import SuMoC.backend.routing.services.RoutingPreferencesService;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/routing/directions")
|
||||
@RequiredArgsConstructor
|
||||
class RoutingDirectionsController {
|
||||
|
||||
private final DirectionsRoutingService directionsRoutingService;
|
||||
|
||||
private final RoutingPreferencesService routingPreferencesService;
|
||||
|
||||
@PostMapping("/request")
|
||||
@Schema(description = "Endpoint to request routes from point A to B, also see RoutingDirectionsRequestDTO.")
|
||||
public ResponseEntity<List<RouteDTO>> requestDirections(@Valid @RequestBody RoutingDirectionsRequestDTO directionsRequestDTO) {
|
||||
validateRequestDTO(directionsRequestDTO);
|
||||
|
||||
// if routing preferences are not provided, get stored preferences or default
|
||||
if (directionsRequestDTO.getRoutingPreferencesDTO() == null) {
|
||||
directionsRequestDTO.setRoutingPreferencesDTO(routingPreferencesService.getRoutingPreferencesForCurrentUser());
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(directionsRoutingService.getDirections(directionsRequestDTO));
|
||||
}
|
||||
|
||||
private void validateRequestDTO(RoutingDirectionsRequestDTO requestDTO) {
|
||||
if (requestDTO.getArrivalTime() == null && requestDTO.getDepartureTime() == null) {
|
||||
throw new IllegalArgumentException("Either arrivalTime or departureTime must be provided.");
|
||||
}
|
||||
if (requestDTO.getArrivalTime() != null && requestDTO.getDepartureTime() != null) {
|
||||
throw new IllegalArgumentException("Only one of arrivalTime or departureTime should be provided.");
|
||||
}
|
||||
if (requestDTO.getOriginAddress() == null && (requestDTO.getOriginLat() == 0.0 || requestDTO.getOriginLon() == 0.0)) {
|
||||
throw new IllegalArgumentException("Origin must be specified either by address or coordinates.");
|
||||
}
|
||||
if (requestDTO.getDestinationAddress() == null && (requestDTO.getDestinationLat() == 0.0 || requestDTO.getDestinationLon() == 0.0)) {
|
||||
throw new IllegalArgumentException("Destination must be specified either by address or coordinates.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package SuMoC.backend.routing.controller;
|
||||
|
||||
import SuMoC.backend.routing.dtos.RoutingPreferencesDTO;
|
||||
import SuMoC.backend.routing.services.RoutingPreferencesService;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.service.CurrentUserService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/routing/preferences")
|
||||
@RequiredArgsConstructor
|
||||
public class RoutingPreferencesController {
|
||||
|
||||
private final RoutingPreferencesService routingPreferencesService;
|
||||
|
||||
private final CurrentUserService currentUserService;
|
||||
|
||||
@Operation(summary = "Get the routing preferences of the current user", description = "Retrieves the routing preferences set by the authenticated user.")
|
||||
@GetMapping("/get")
|
||||
public ResponseEntity<RoutingPreferencesDTO> getRoutingPreferences() {
|
||||
User user = currentUserService.get();
|
||||
RoutingPreferencesDTO preferences = routingPreferencesService.getUserRoutingPreferences(user.getId());
|
||||
return ResponseEntity.ok(preferences);
|
||||
}
|
||||
|
||||
@Operation(summary = "Update the routing preferences of the current user", description = "Updates the routing preferences for the authenticated user with the provided settings.")
|
||||
@PutMapping("/update")
|
||||
public ResponseEntity<Void> updateRoutingPreferences(@RequestBody RoutingPreferencesDTO newPreferencesDTO) {
|
||||
User user = currentUserService.get();
|
||||
routingPreferencesService.updateUserRoutingPreferences(user.getId(), newPreferencesDTO);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ 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;
|
||||
@@ -17,6 +18,7 @@ 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;
|
||||
@@ -46,10 +48,25 @@ public class RouteDTO {
|
||||
private double co2Savings;
|
||||
@Schema(description = "CO2e emission of this route.")
|
||||
private double co2Emissions;
|
||||
@Schema(description = "The temporal difference in minutes compared to the original route the user requested alternatives for.")
|
||||
@Schema(description = "The temporal difference in minutes compared to the original route (in case alternative was requested) / the car route (when simply directions requested) .")
|
||||
private double timeDifferenceSeconds;
|
||||
|
||||
public RouteDTO(AddressDTO startAddress, @Nullable String firstStopName, double startLat, double startLon, AddressDTO endAddress, @Nullable String lastStopName, double endLat, double endLon, Instant startDateTime, Instant endDateTime, List<StepDTO> steps, double co2Savings, double timeDifferenceSeconds, double co2Emissions) {
|
||||
public RouteDTO(
|
||||
AddressDTO startAddress,
|
||||
@Nullable String firstStopName,
|
||||
double startLat,
|
||||
double startLon,
|
||||
AddressDTO endAddress,
|
||||
@Nullable String lastStopName,
|
||||
double endLat,
|
||||
double endLon,
|
||||
Instant startDateTime,
|
||||
Instant endDateTime,
|
||||
List<StepDTO> steps,
|
||||
double co2Savings,
|
||||
double timeDifferenceSeconds,
|
||||
double co2Emissions
|
||||
) {
|
||||
this.startAddress = startAddress;
|
||||
this.firstStopName = firstStopName;
|
||||
this.startLat = startLat;
|
||||
@@ -114,17 +131,18 @@ public class RouteDTO {
|
||||
);
|
||||
dto.steps.add(new StepDTO(
|
||||
Modality.WALKING,
|
||||
null,
|
||||
400f
|
||||
));
|
||||
dto.steps.add(new StepDTO(
|
||||
dto.steps.add(new TransitStepDTO(
|
||||
Modality.TRAM,
|
||||
5000f,
|
||||
"106",
|
||||
5000f
|
||||
"Ich bin eine Testlinie",
|
||||
"Ich bin ein Teststartbahnhof",
|
||||
"Ich bin ein Testendbahnhof"
|
||||
));
|
||||
dto.steps.add(new StepDTO(
|
||||
Modality.WALKING,
|
||||
null,
|
||||
300f
|
||||
));
|
||||
return dto;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user