Compare commits
166
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53cfce5359 | ||
|
|
fb94421247 | ||
|
|
4567ca16f0 | ||
|
|
88fcbfb728 | ||
|
|
400c31cc34 | ||
|
|
522393bdd7 | ||
|
|
768acc1841 | ||
|
|
850410ec46 | ||
|
|
85ca90fa7c | ||
|
|
46a8ca67a0 | ||
|
|
c6fe80145b | ||
|
|
5b6cc1c679 | ||
|
|
43e91670b3 | ||
|
|
e2e1cc48a0 | ||
|
|
fb0989ef95 | ||
|
|
607ce804da | ||
|
|
72efa472fa | ||
|
|
9b475a37e1 | ||
|
|
fb49fa2130 | ||
|
|
edabef4fb3 | ||
|
|
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 | ||
|
|
d92b71179a | ||
|
|
95e496ab85 | ||
|
|
140945dbc2 | ||
|
|
0752a59fd9 | ||
|
|
106bdbe220 | ||
|
|
1cca645696 | ||
|
|
7098fbe8cc | ||
|
|
9f854ce3ab | ||
|
|
1369f4f25d | ||
|
|
4e11dd2d78 | ||
|
|
f8c661ccb6 | ||
|
|
d099909aab | ||
|
|
b08d9dd22d | ||
|
|
8bace01238 | ||
|
|
29a7811c97 | ||
|
|
56e594b625 | ||
|
|
8ee6992f88 | ||
|
|
ddbf925caf | ||
|
|
41f04620ba | ||
|
|
ce665d143f | ||
|
|
51c742b746 | ||
|
|
813390286f | ||
|
|
11ce10a8d8 | ||
|
|
521a4ba957 | ||
|
|
bc3dd9b59b | ||
|
|
06aa0ce3cc | ||
|
|
bef418d77d | ||
|
|
ba642d10a5 | ||
|
|
fd5bdd6083 | ||
|
|
f1a214b5db | ||
|
|
dd86b857d4 | ||
|
|
c8f667bba7 | ||
|
|
008313d651 | ||
|
|
7e8edab77a | ||
|
|
23da358686 | ||
|
|
474813b2b9 | ||
|
|
160b883bfc | ||
|
|
1b74f6125c | ||
|
|
6bb438f786 | ||
|
|
4d112a599f | ||
|
|
a643db3133 | ||
|
|
4fb5d9c5f8 | ||
|
|
1f439338da | ||
|
|
ea3c941b84 | ||
|
|
8e3cb83d27 | ||
|
|
4c9b69a0d0 | ||
|
|
ea2494db49 | ||
|
|
86073411b0 | ||
|
|
671dabad3b | ||
|
|
b2718efa4c | ||
|
|
0630bdd2a5 | ||
|
|
a9bb7cfa33 | ||
|
|
caff26d7ca | ||
|
|
0f54353263 | ||
|
|
41bda73041 | ||
|
|
4410c0b3bc | ||
|
|
ca41233397 | ||
|
|
e88d651c71 | ||
|
|
137923d9a6 | ||
|
|
6e458edd5c | ||
|
|
ec0615f6df | ||
|
|
c010f34479 | ||
|
|
17636f0b65 | ||
|
|
266d9ff3bb | ||
|
|
bff1659186 | ||
|
|
8c5fff5a3b | ||
|
|
bda244a2e8 | ||
|
|
dfa5ee9559 | ||
|
|
ce7494a95f | ||
|
|
5c45937fba | ||
|
|
80ba8b1c19 | ||
|
|
5e63753bf7 | ||
|
|
a716986d91 | ||
|
|
e93bdde124 | ||
|
|
45cf83aa78 | ||
|
|
6c589a22ac | ||
|
|
1daa400a90 | ||
|
|
3ae5b85cc0 | ||
|
|
5f5365d5bc | ||
|
|
12aed5ef26 | ||
|
|
0437117d9e | ||
|
|
52788a9c83 | ||
|
|
c6dabb9cd9 | ||
|
|
6eb36f5b58 | ||
|
|
6bd78c597f | ||
|
|
54c28ff83a | ||
|
|
980e026fe3 | ||
|
|
938a618bf2 | ||
|
|
3ea13530bc | ||
|
|
0a78c302d4 | ||
|
|
44c2fc0832 | ||
|
|
3f6260edf3 | ||
|
|
afec6af878 |
@@ -1,3 +1,5 @@
|
||||
# This file overrides default envs set in application.properties when run in full docker setup
|
||||
SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/sumoc
|
||||
SPRING_DATASOURCE_USERNAME=postgres
|
||||
SPRING_DATASOURCE_PASSWORD=admin
|
||||
SPRING_DATASOURCE_PASSWORD=admin
|
||||
nominatim.base-url=http://nominatim:8080/
|
||||
+12
@@ -33,3 +33,15 @@ build/
|
||||
.vscode/
|
||||
/generated/
|
||||
/.mvn/
|
||||
/app/
|
||||
|
||||
|
||||
/docker_images/*.tar
|
||||
|
||||
### 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."
|
||||
|
||||
+17
-1
@@ -1,4 +1,6 @@
|
||||
version: '3.8'
|
||||
volumes:
|
||||
nominatim-data:
|
||||
postgres_data:
|
||||
|
||||
services:
|
||||
db:
|
||||
@@ -8,6 +10,20 @@ services:
|
||||
- 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"
|
||||
|
||||
@@ -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"
|
||||
+38
-8
@@ -1,3 +1,7 @@
|
||||
volumes:
|
||||
postgres_data:
|
||||
jwt_keys:
|
||||
# nominatim-data:
|
||||
|
||||
services:
|
||||
backend:
|
||||
@@ -8,22 +12,48 @@ 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
|
||||
|
||||
db:
|
||||
image: postgres:15
|
||||
container_name: sumoc-postgres
|
||||
image: postgres:16.2-alpine
|
||||
container_name: sumoc_db
|
||||
environment:
|
||||
POSTGRES_DB: sumoc
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: admin
|
||||
- TZ=Europe/Berlin
|
||||
- POSTGRES_USER=postgres
|
||||
- POSTGRES_PASSWORD=admin
|
||||
- POSTGRES_DB=sumoc
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
ports:
|
||||
- "5432:5432"
|
||||
restart: unless-stopped
|
||||
restart: always
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
# 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
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/bin/bash
|
||||
|
||||
# 1. Spring Boot starten
|
||||
echo "Starte Spring Boot..."
|
||||
./mvnw spring-boot:run &
|
||||
|
||||
# Prozess-ID speichern, um später ggf. zu stoppen
|
||||
SPRING_PID=$!
|
||||
|
||||
# Warten, bis der Server verfügbar ist
|
||||
echo "Warte auf Serverstart..."
|
||||
until curl -s http://localhost:8080/v3/api-docs.yaml -o /dev/null; do
|
||||
sleep 2
|
||||
done
|
||||
|
||||
# 2. OpenAPI-Spezifikation herunterladen
|
||||
echo "Lade OpenAPI-Spezifikation herunter..."
|
||||
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 --additional-properties=useClasses=true
|
||||
|
||||
# 4. Kotlin-Client generieren
|
||||
echo "Generiere Kotlin-Client..."
|
||||
openapi-generator-cli generate -i openapi.yaml -g kotlin -o app/android-api
|
||||
|
||||
# Optional: Spring Boot stoppen
|
||||
echo "Stoppe Spring Boot..."
|
||||
kill $SPRING_PID
|
||||
|
||||
echo "Fertig!"
|
||||
+1811
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"$schema": "./node_modules/@openapitools/openapi-generator-cli/config.schema.json",
|
||||
"spaces": 2,
|
||||
"generator-cli": {
|
||||
"version": "7.14.0"
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
@@ -87,8 +91,31 @@
|
||||
<artifactId>spring-security-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- OpenAPI okhttp client -->
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
<version>4.12.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- JSON serialization used by the generated client -->
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>2.11.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Usually needed by openapi-generator's gson setup -->
|
||||
<dependency>
|
||||
<groupId>io.gsonfire</groupId>
|
||||
<artifactId>gson-fire</artifactId>
|
||||
<version>1.9.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>logging-interceptor</artifactId>
|
||||
<version>4.12.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mapstruct</groupId>
|
||||
<artifactId>mapstruct</artifactId>
|
||||
@@ -103,7 +130,25 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.projectreactor</groupId>
|
||||
<artifactId>reactor-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.firebase</groupId>
|
||||
<artifactId>firebase-admin</artifactId>
|
||||
<version>9.7.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.uber</groupId>
|
||||
<artifactId>h3</artifactId>
|
||||
<version>4.4.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -112,8 +157,6 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
|
||||
|
||||
<!-- MapStruct Annotation Processor einbinden -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
@@ -123,27 +166,67 @@
|
||||
<source>21</source>
|
||||
<target>21</target>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.18.32</version>
|
||||
</path>
|
||||
<path>
|
||||
<groupId>org.mapstruct</groupId>
|
||||
<artifactId>mapstruct-processor</artifactId>
|
||||
<version>1.5.5.Final</version>
|
||||
<version>1.6.3</version>
|
||||
</path>
|
||||
<path>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.18.30</version>
|
||||
<artifactId>lombok-mapstruct-binding</artifactId>
|
||||
<version>0.2.0</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
<!--<compilerArgs>- -enable-preview</compilerArgs> -->
|
||||
<!--<compilerArgs>- -enable-preview</compilerArgs> -->
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
|
||||
<plugin>
|
||||
<groupId>org.openapitools</groupId>
|
||||
<artifactId>openapi-generator-maven-plugin</artifactId>
|
||||
<version>7.8.0</version>
|
||||
<version>7.18.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>generate-carta-client</id>
|
||||
<goals>
|
||||
<goal>generate</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<inputSpec>${project.basedir}/src/main/resources/carta_fixed_by_hand.json</inputSpec>
|
||||
|
||||
<generatorName>java</generatorName>
|
||||
<library>resttemplate</library>
|
||||
|
||||
<!-- cleaner, distinguishable output location -->
|
||||
<output>${project.build.directory}/generated-sources/openapi/carta-client</output>
|
||||
<addCompileSourceRoot>true</addCompileSourceRoot>
|
||||
|
||||
<!-- distinguish packages -->
|
||||
<apiPackage>sumoc.backend.carta.client.api</apiPackage>
|
||||
<modelPackage>sumoc.backend.carta.client.model</modelPackage>
|
||||
<invokerPackage>sumoc.backend.carta.client.invoker</invokerPackage>
|
||||
|
||||
<configOptions>
|
||||
<!-- inside the output dir -->
|
||||
<sourceFolder>src/main/java</sourceFolder>
|
||||
<dateLibrary>java21</dateLibrary>
|
||||
|
||||
<!-- for Spring Boot 3 -->
|
||||
<useJakartaEe>true</useJakartaEe>
|
||||
<openApiNullable>false</openApiNullable>
|
||||
<legacyDiscriminatorBehavior>false</legacyDiscriminatorBehavior>
|
||||
<!-- <disallowAdditionalPropertiesIfNotPresent>false-->
|
||||
<!-- </disallowAdditionalPropertiesIfNotPresent>-->
|
||||
</configOptions>
|
||||
<!-- <skipValidateSpec>true</skipValidateSpec>-->
|
||||
<generateApiTests>false</generateApiTests>
|
||||
<generateModelTests>false</generateModelTests>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>generate-android-client</id>
|
||||
<phase>none</phase>
|
||||
@@ -156,7 +239,6 @@
|
||||
<output>${project.basedir}/generated/android</output>
|
||||
</configuration>
|
||||
</execution>
|
||||
|
||||
<execution>
|
||||
<id>generate-ios-client</id>
|
||||
<phase>none</phase>
|
||||
@@ -182,6 +264,28 @@
|
||||
</activation>
|
||||
<build>
|
||||
<plugins>
|
||||
<!-- SpringDoc plugin to generate OpenAPI spec without running server -->
|
||||
<plugin>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-maven-plugin</artifactId>
|
||||
<version>1.4</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>generate-openapi-spec</id>
|
||||
<phase>initialize</phase>
|
||||
<goals>
|
||||
<goal>generate</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<apiDocsUrl>http://localhost:8080/v3/api-docs.yaml</apiDocsUrl>
|
||||
<outputFileName>openapi.yaml</outputFileName>
|
||||
<outputDir>${project.basedir}</outputDir>
|
||||
<skip>false</skip>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.openapitools</groupId>
|
||||
<artifactId>openapi-generator-maven-plugin</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.
@@ -2,8 +2,10 @@ package SuMoC.backend;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableScheduling
|
||||
public class BackendApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package SuMoC.backend.carta;
|
||||
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Service;
|
||||
import sumoc.backend.carta.client.api.CartaApi;
|
||||
import sumoc.backend.carta.client.api.MapApi;
|
||||
import sumoc.backend.carta.client.model.Direction;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@Service
|
||||
public class CartaClient {
|
||||
|
||||
private final MapApi mapApi;
|
||||
private final CartaApi cartaApi;
|
||||
|
||||
public CartaClient(MapApi mapApi, CartaApi cartaApi) {
|
||||
this.cartaApi = cartaApi;
|
||||
this.mapApi = mapApi;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param origin
|
||||
* @param destination
|
||||
* @param mode
|
||||
* @param arrivalTime
|
||||
* @param departureTime
|
||||
* @param alternatives Number of alternatives
|
||||
* @param walkingSpeed
|
||||
* @param transferTime
|
||||
* @param type 0=tram, 1=subway, 2=rail, 3=bus, 4=ferry, 5=cablecar, 6=gondola, 7=funicular, 8=trolleybus, 9=monorail - after inspecting innamoruhr 10 = add bikes?
|
||||
* @param range
|
||||
* @param location Context for name resolution
|
||||
* @return
|
||||
*/
|
||||
@Async
|
||||
public CompletableFuture<Direction> asyncGetRoute(
|
||||
String origin,
|
||||
String destination,
|
||||
String mode,
|
||||
Instant arrivalTime,
|
||||
Instant departureTime,
|
||||
Integer alternatives,
|
||||
Double walkingSpeed,
|
||||
Integer transferTime,
|
||||
String type,
|
||||
Integer range,
|
||||
String location
|
||||
) {
|
||||
try {
|
||||
return CompletableFuture.completedFuture(cartaApi.getDirection(
|
||||
origin,
|
||||
destination,
|
||||
mode.toLowerCase(), // possible values: walking, driving, cycling
|
||||
arrivalTime.getEpochSecond(),
|
||||
departureTime != null ? departureTime.getEpochSecond() : null,
|
||||
alternatives,
|
||||
walkingSpeed,
|
||||
transferTime,
|
||||
false,
|
||||
false,
|
||||
type,
|
||||
range,
|
||||
location,
|
||||
null
|
||||
));
|
||||
|
||||
// } catch (InterruptedException e) {
|
||||
// return CompletableFuture.failedFuture(e);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package SuMoC.backend.carta;
|
||||
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import sumoc.backend.carta.client.api.CartaApi;
|
||||
import sumoc.backend.carta.client.api.MapApi;
|
||||
import sumoc.backend.carta.client.invoker.ApiClient;
|
||||
|
||||
@Configuration
|
||||
@EnableConfigurationProperties(CartaProperties.class)
|
||||
public class CartaClientConfig {
|
||||
|
||||
@Bean
|
||||
public ApiClient cartaApiClient(CartaProperties cartaProperties) {
|
||||
ApiClient apiClient = new ApiClient();
|
||||
apiClient.setBasePath(cartaProperties.baseUrl());
|
||||
// TODO Timeouts?
|
||||
return apiClient;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MapApi mapApi(ApiClient cartaApiClient) {
|
||||
return new MapApi(cartaApiClient);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CartaApi cartaApi(ApiClient cartaApiClient) {
|
||||
return new CartaApi(cartaApiClient);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package SuMoC.backend.carta;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@ConfigurationProperties(prefix = "carta")
|
||||
public record CartaProperties(
|
||||
String baseUrl
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package SuMoC.backend.common.converter;
|
||||
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
import java.time.DayOfWeek;
|
||||
|
||||
/**
|
||||
* This converter handles the conversion between Java's DayOfWeek enum and the SQL DAY_OF_WEEK integer representation.
|
||||
* In Java, DayOfWeek uses 1 (Monday) to 7 (Sunday), while SQL's DAY_OF_WEEK function returns 1 (Sunday) to 7 (Saturday).
|
||||
*/
|
||||
@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) to SQL format (1=Sunday)
|
||||
return (attribute.getValue() % 7) + 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DayOfWeek convertToEntityAttribute(Integer dbData) {
|
||||
if (dbData == null) {
|
||||
return null;
|
||||
}
|
||||
// Convert SQL format (1=Sunday) back to Java DayOfWeek (1=Monday)
|
||||
// Example: SQL 1 (Sunday) -> Java 7
|
||||
// SQL 7 (Saturday) -> Java 6
|
||||
// SQL 2 (Monday) -> Java 1
|
||||
return DayOfWeek.of(((dbData + 5) % 7) + 1);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
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.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.*;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/dev")
|
||||
@Profile("dev")
|
||||
public class DevController {
|
||||
|
||||
private final ScheduledTasks scheduledTasks;
|
||||
private final StatTableUpdateService statTableUpdateService;
|
||||
private final FirebaseMessaging firebaseMessaging;
|
||||
private final MeteoClient meteoClient;
|
||||
private final ForecastService forecastService;
|
||||
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,
|
||||
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")
|
||||
public void triggerTrendCalculation() {
|
||||
LocalDate dayOfLastWeek = LocalDate.now().minusDays(7);
|
||||
LocalDate day2WeeksAgo = LocalDate.now().minusDays(14);
|
||||
LocalDate day3WeeksAgo = LocalDate.now().minusDays(21);
|
||||
statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(dayOfLastWeek);
|
||||
statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(day2WeeksAgo);
|
||||
statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(day3WeeksAgo);
|
||||
}
|
||||
|
||||
@GetMapping("/test-firebase-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(
|
||||
mockTrendMessage
|
||||
).get();
|
||||
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/test-firebase-adhoc-route-notification/{fcm_token}")
|
||||
@Operation(description = "Immediately sends a test notification of type ADHOC_ALTERNATIVE to the provided FCM token.")
|
||||
public ResponseEntity<String> SendTestAdhocRouteNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
|
||||
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-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(LocalDateTime.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(LocalDateTime.now().minusDays(60))
|
||||
.status(NotificationStatus.SENT)
|
||||
.build();
|
||||
|
||||
notificationRepository.save(notification);
|
||||
|
||||
Thread.sleep(5000);
|
||||
|
||||
scheduledTasks.scheduleCleanUpOldNotifications();
|
||||
}
|
||||
|
||||
@GetMapping("/test-meteo")
|
||||
public void testMeteoClient() {
|
||||
try {
|
||||
// Test with Zurich coordinates
|
||||
double lat = 51.44378662109375;
|
||||
double lon = 7.007565975189209;
|
||||
|
||||
var forecast = forecastService.getTodayYesterdayForecast(
|
||||
lat,
|
||||
lon);
|
||||
} catch (Exception e) {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,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 = "";
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package SuMoC.backend.firebase;
|
||||
|
||||
import com.google.auth.oauth2.GoogleCredentials;
|
||||
import com.google.firebase.FirebaseApp;
|
||||
import com.google.firebase.FirebaseOptions;
|
||||
import com.google.firebase.messaging.FirebaseMessaging;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
@Configuration
|
||||
@EnableConfigurationProperties(FirebaseProperties.class)
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnProperty(prefix = "firebase.config", name = "enabled", havingValue = "true", matchIfMissing = false)
|
||||
public class FirebaseConfiguration {
|
||||
|
||||
private final FirebaseProperties firebaseProperties;
|
||||
|
||||
@Bean
|
||||
FirebaseMessaging firebaseMessaging(FirebaseApp firebaseApp) {
|
||||
return FirebaseMessaging.getInstance(firebaseApp);
|
||||
}
|
||||
|
||||
@Bean
|
||||
FirebaseApp firebaseApp(GoogleCredentials credentials) {
|
||||
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) {
|
||||
try (InputStream is = firebaseProperties.serviceAccount().getInputStream()) {
|
||||
return GoogleCredentials.fromStream(is);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
} else {
|
||||
// Use standard credentials chain. Useful when running inside GKE
|
||||
return GoogleCredentials.getApplicationDefault();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package SuMoC.backend.firebase;
|
||||
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
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());
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package SuMoC.backend.firebase;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.core.io.Resource;
|
||||
|
||||
@ConfigurationProperties(prefix = "firebase.config")
|
||||
public record FirebaseProperties(
|
||||
Boolean enabled,
|
||||
Resource serviceAccount
|
||||
) {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package SuMoC.backend.gamification;
|
||||
|
||||
public enum Timeframe {
|
||||
TOTAL("totalStats"),
|
||||
MONTHLY("monthlyStats"),
|
||||
WEEKLY("weeklyStats");
|
||||
|
||||
private final String statsField;
|
||||
|
||||
Timeframe(String statsField) {
|
||||
this.statsField = statsField;
|
||||
}
|
||||
|
||||
public String getStatsField() {
|
||||
return statsField;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
package SuMoC.backend.gamification.badges;
|
||||
|
||||
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.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")
|
||||
public class BadgeController {
|
||||
private BadgeService badgeService;
|
||||
|
||||
@Autowired
|
||||
public BadgeController(BadgeService badgeService) {
|
||||
this.badgeService = badgeService;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Operation(summary = "Create a new badge")
|
||||
@ApiResponses(value = {
|
||||
@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<BadgeDTO> createBadge(@RequestBody @Valid BadgeDTO badge) {
|
||||
BadgeDTO createdBadge = badgeService.createBadge(badge);
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(createdBadge);
|
||||
}
|
||||
|
||||
|
||||
@Operation(summary = "Delete a badge by ID")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Badge deleted successfully"),
|
||||
@ApiResponse(responseCode = "404", description = "Badge not found")
|
||||
})
|
||||
@DeleteMapping("/deleteBadge/{badgeId}")
|
||||
public ResponseEntity<Void> deleteBadgeById(@PathVariable Long badgeId) {
|
||||
badgeService.deleteBadge(badgeId);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Operation(summary = "Modify a badge by ID")
|
||||
@ApiResponses(value = {
|
||||
@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<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",
|
||||
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<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",
|
||||
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<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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package SuMoC.backend.gamification.badges;
|
||||
|
||||
import SuMoC.backend.gamification.badges.models.Badge;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface BadgeRepository extends JpaRepository<Badge, Long> {
|
||||
Optional<Badge> findByName(String name);
|
||||
|
||||
List<Badge> getBadgeById(Long id);
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
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.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
@Service
|
||||
public class BadgeService {
|
||||
|
||||
private final CurrentUserService currentUser;
|
||||
|
||||
private final BadgeRepository badgeRepository;
|
||||
|
||||
private final UserBadgeRepository userBadgeRepository;
|
||||
private final PrivacyService privacyService;
|
||||
|
||||
public BadgeService(CurrentUserService currentUser, BadgeRepository badgeRepository, UserBadgeRepository userBadgeRepository, PrivacyService privacyService) {
|
||||
this.currentUser = currentUser;
|
||||
this.badgeRepository = badgeRepository;
|
||||
this.userBadgeRepository = userBadgeRepository;
|
||||
this.privacyService = privacyService;
|
||||
}
|
||||
|
||||
public BadgeDTO createBadge(BadgeDTO badgeDTO) {
|
||||
badgeRepository.findByName(badgeDTO.getName())
|
||||
.ifPresent(b -> {
|
||||
throw new ResponseStatusException(HttpStatus.CONFLICT, "Badge existiert bereits");
|
||||
});
|
||||
|
||||
Badge badge = BadgeMapper.toEntity(badgeDTO);
|
||||
Badge savedBadge = badgeRepository.save(badge);
|
||||
return BadgeMapper.toDTO(savedBadge);
|
||||
}
|
||||
|
||||
public void checkAndAwardBadges() {
|
||||
User user = currentUser.get();
|
||||
List<Badge> badges = badgeRepository.findAll();
|
||||
|
||||
for (Badge badge : badges) {
|
||||
// Prüfe, ob Nutzer schon den Badge hat
|
||||
boolean alreadyHas = user.getBadges().stream()
|
||||
.anyMatch(ub -> ub.getBadge().equals(badge));
|
||||
if (alreadyHas) continue;
|
||||
|
||||
// Nur prüfen, wenn es überhaupt Kriterien gibt
|
||||
Map<String, Integer> criteria = badge.getCriteria();
|
||||
boolean qualifies = criteria != null && !criteria.isEmpty() &&
|
||||
criteria.entrySet().stream()
|
||||
.allMatch(entry ->
|
||||
user.getStats().getStatValue(Timeframe.TOTAL, entry.getKey()) >= entry.getValue()
|
||||
);
|
||||
|
||||
if (qualifies) {
|
||||
UserBadge userBadge = new UserBadge();
|
||||
userBadge.setUser(user);
|
||||
userBadge.setBadge(badge);
|
||||
userBadge.setAwardedAt(LocalDateTime.now());
|
||||
userBadgeRepository.save(userBadge);
|
||||
user.getBadges().add(userBadge);
|
||||
|
||||
// TODO: Remove in production
|
||||
System.out.println("Badge " + badge.getName() + " vergeben an " + user.getPrivateName() +
|
||||
". Mit Condition: " + badge.getCriteria().toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public BadgeDTO modifyBadge(BadgeDTO badgeDTO) {
|
||||
Badge badge = badgeRepository.findById(badgeDTO.getId())
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Badge nicht gefunden"));
|
||||
|
||||
BadgeMapper.updateEntityFromDTO(badge, badgeDTO);
|
||||
Badge savedBadge = badgeRepository.save(badge);
|
||||
return BadgeMapper.toDTO(savedBadge);
|
||||
}
|
||||
|
||||
public void deleteBadge(Long id) {
|
||||
Badge badge = badgeRepository.findById(id)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Badge nicht gefunden"));
|
||||
badgeRepository.delete(badge);
|
||||
}
|
||||
|
||||
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<BadgeDTO> getAllBadges() {
|
||||
List<Badge> badges = badgeRepository.findAll();
|
||||
return badges.stream()
|
||||
.map(BadgeMapper::toDTO)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public List<UserBadgeDTO> getUserBadges(Long id) {
|
||||
User sender = currentUser.get();
|
||||
List<UserBadge> badges = new ArrayList<>();
|
||||
if(Objects.equals(id, sender.getId())) {
|
||||
badges = userBadgeRepository.findByUserId(sender.getId());
|
||||
} else {
|
||||
if(privacyService.checkVisibility(sender, id)) {
|
||||
badges = userBadgeRepository.findByUserId(id);
|
||||
}
|
||||
}
|
||||
|
||||
return badges.stream()
|
||||
.map(UserBadgeMapper::toDTO)
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,12 @@
|
||||
package SuMoC.backend.gamification.badges;
|
||||
|
||||
import SuMoC.backend.gamification.badges.models.UserBadge;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
public interface UserBadgeRepository extends JpaRepository<UserBadge, Long> {
|
||||
List<UserBadge> findByUserId(Long userId);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package SuMoC.backend.gamification.badges.mapper;
|
||||
|
||||
import SuMoC.backend.gamification.badges.models.Badge;
|
||||
import SuMoC.backend.gamification.badges.models.UserBadge;
|
||||
import SuMoC.backend.gamification.badges.models.UserBadgeDTO;
|
||||
import org.mapstruct.Mapper;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public class UserBadgeMapper {
|
||||
|
||||
public static UserBadgeDTO toDTO(UserBadge userBadge) {
|
||||
UserBadgeDTO dto = new UserBadgeDTO();
|
||||
|
||||
Badge badge = userBadge.getBadge();
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public static List<UserBadgeDTO> toDTO(List<UserBadge> userBadges) {
|
||||
List<UserBadgeDTO> dtos = new ArrayList<>();
|
||||
for(UserBadge badge : userBadges ) {
|
||||
dtos.add(UserBadgeMapper.toDTO(badge));
|
||||
}
|
||||
return dtos;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package SuMoC.backend.gamification.badges.models;
|
||||
|
||||
import SuMoC.backend.images.ImageEntity;
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Entity
|
||||
public class Badge {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
private String description;
|
||||
private BadgeCategory category;
|
||||
|
||||
@OneToOne(mappedBy = "badge", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
private BadgeImageEntity image;
|
||||
|
||||
@ElementCollection
|
||||
@CollectionTable(name = "badge_criteria", joinColumns = @JoinColumn(name = "badge_id"))
|
||||
@MapKeyColumn(name = "criteria_name")
|
||||
@Column(name = "criteria_value")
|
||||
private Map<String, Integer> criteria = new HashMap<>();
|
||||
|
||||
// Constructors
|
||||
public Badge(String name, String description, BadgeCategory category) {
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.category = category;
|
||||
this.image = new BadgeImageEntity(this, null);
|
||||
}
|
||||
|
||||
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; }
|
||||
|
||||
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 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package SuMoC.backend.gamification.badges.models;
|
||||
|
||||
import SuMoC.backend.user.models.User;
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
public class UserBadge {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
// TODO: Discuss if this Duplex Joint really makes sense
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
private User user;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "badge_id", nullable = false)
|
||||
private Badge badge;
|
||||
|
||||
private LocalDateTime awardedAt;
|
||||
|
||||
|
||||
// Getter & Setter
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
|
||||
public User getUser() { return user; }
|
||||
public void setUser(User user) { this.user = user; }
|
||||
|
||||
public Badge getBadge() { return badge; }
|
||||
public void setBadge(Badge badge) { this.badge = badge; }
|
||||
|
||||
public LocalDateTime getAwardedAt() { return awardedAt; }
|
||||
public void setAwardedAt(LocalDateTime awardedAt) { this.awardedAt = awardedAt; }
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package SuMoC.backend.gamification.badges.models;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
|
||||
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
|
||||
|
||||
|
||||
public Long getBadgeId() {
|
||||
return badgeId;
|
||||
}
|
||||
|
||||
public void setBadgeId(Long badgeId) {
|
||||
this.badgeId = badgeId;
|
||||
}
|
||||
|
||||
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 this.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 LocalDateTime getAwardedAt() {
|
||||
return awardedAt;
|
||||
}
|
||||
|
||||
public void setAwardedAt(LocalDateTime awardedAt) {
|
||||
this.awardedAt = awardedAt;
|
||||
}
|
||||
|
||||
public String getImageBase64() { return imageBase64; }
|
||||
public void setImageBase64(String imageBase64) { this.imageBase64 = imageBase64; }
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package SuMoC.backend.gamification.scoretable;
|
||||
|
||||
import SuMoC.backend.gamification.scoretable.models.Leaderboard;
|
||||
import SuMoC.backend.gamification.Timeframe;
|
||||
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.CacheControl;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
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")
|
||||
public class LeaderboardController {
|
||||
private LeaderboardService leaderboardService;
|
||||
|
||||
@Autowired
|
||||
public LeaderboardController(LeaderboardService leaderboardService) {
|
||||
this.leaderboardService = leaderboardService;
|
||||
}
|
||||
|
||||
@Operation(summary = "Get the global score table")
|
||||
@ApiResponses(value = {
|
||||
@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(@RequestParam Timeframe timeframe,
|
||||
@RequestParam String field) {
|
||||
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",
|
||||
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(@RequestParam Timeframe timeframe,
|
||||
@RequestParam String field) {
|
||||
Leaderboard leaderboard = this.leaderboardService.getFriendLeaderboard(timeframe, field);
|
||||
return ResponseEntity.ok()
|
||||
.cacheControl(CacheControl.maxAge(24, TimeUnit.HOURS))
|
||||
.body(leaderboard);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
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 org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@Service
|
||||
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,
|
||||
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 timeframe
|
||||
* @param field
|
||||
* @return
|
||||
*/
|
||||
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 timeframe
|
||||
* @param field
|
||||
* @param limit
|
||||
* @return
|
||||
*/
|
||||
public Leaderboard getLeaderboard(Timeframe timeframe, String field, int limit) {
|
||||
User user = currentUser.get();
|
||||
List<StatsList> topStats = getTopStats(timeframe, field, limit);
|
||||
|
||||
Leaderboard leaderboard = new Leaderboard();
|
||||
leaderboard.setEntries(new ArrayList<>());
|
||||
List<User> friendships = friendshipService.getAcceptedFriends(user);
|
||||
for (StatsList statsList : topStats) {
|
||||
User topUser = statsList.getUser();
|
||||
boolean ps = privacyService.checkVisibility(user, topUser.getId());
|
||||
|
||||
LeaderboardEntry entry = new LeaderboardEntry(
|
||||
topUser.getId(),
|
||||
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);
|
||||
}
|
||||
|
||||
if (leaderboard.getEntries().stream().noneMatch(e -> e.getUserId().equals(user.getId()))) {
|
||||
LeaderboardEntry userEntry = new LeaderboardEntry(
|
||||
user.getId(),
|
||||
user.getPrivateName(),
|
||||
false,
|
||||
user.getStats().getStatValue(timeframe, field),
|
||||
ImageBase64Util.encode(user.getProfileImage().getImageData())
|
||||
);
|
||||
leaderboard.getEntries().add(userEntry);
|
||||
}
|
||||
|
||||
leaderboard.getEntries().sort(
|
||||
Comparator.comparingLong(LeaderboardEntry::getScore).reversed()
|
||||
);
|
||||
|
||||
return leaderboard;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Method Overload to get the friend score table with a default limit of 30.
|
||||
* @param timeframe
|
||||
* @param field
|
||||
* @return
|
||||
*/
|
||||
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 timeframe
|
||||
* @param field
|
||||
* @param limit
|
||||
* @return
|
||||
*/
|
||||
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<>());
|
||||
|
||||
for (User friend : friends) {
|
||||
StatsList statsList = friend.getStats();
|
||||
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(),
|
||||
false,
|
||||
user.getStats().getStatValue(timeframe, field),
|
||||
ImageBase64Util.encode(user.getProfileImage().getImageData())
|
||||
|
||||
));
|
||||
}
|
||||
|
||||
leaderboard.getEntries().sort(
|
||||
Comparator.comparingLong(LeaderboardEntry::getScore).reversed()
|
||||
);
|
||||
return leaderboard;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get the top stats for a given timeframe and stat field.
|
||||
* @param timeframe
|
||||
* @param statField
|
||||
* @param limit
|
||||
* @return
|
||||
*/
|
||||
public List<StatsList> getTopStats(
|
||||
Timeframe timeframe,
|
||||
String statField,
|
||||
int limit
|
||||
) {
|
||||
Pageable pageable = PageRequest.of(0, limit);
|
||||
|
||||
return statsListRepository
|
||||
.findAll(
|
||||
StatsListSpecifications.orderByStat(timeframe, statField),
|
||||
pageable
|
||||
)
|
||||
.getContent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the rank of a specific value for a given timeframe and stat field.
|
||||
* @param timeframe
|
||||
* @param statField
|
||||
* @param value
|
||||
* @return
|
||||
*/
|
||||
public long getRank(
|
||||
Timeframe timeframe,
|
||||
String statField,
|
||||
long value
|
||||
) {
|
||||
return statsListRepository.count(
|
||||
StatsListSpecifications
|
||||
.higherThan(timeframe, statField, value)
|
||||
) + 1;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package SuMoC.backend.gamification.scoretable.models;
|
||||
|
||||
import SuMoC.backend.gamification.Timeframe;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Leaderboard {
|
||||
|
||||
private Timeframe timeframe;
|
||||
|
||||
private LeaderboardType leaderboardType;
|
||||
|
||||
private List<LeaderboardEntry> entries;
|
||||
|
||||
|
||||
// Constructor
|
||||
|
||||
public Leaderboard(Timeframe timeframe, LeaderboardType leaderboardType, List<LeaderboardEntry> entries) {
|
||||
this.timeframe = timeframe;
|
||||
this.leaderboardType = leaderboardType;
|
||||
this.entries = entries;
|
||||
}
|
||||
|
||||
public Leaderboard() {}
|
||||
|
||||
|
||||
// Getter & Setter
|
||||
|
||||
public Timeframe getTimeframe() { return timeframe; }
|
||||
public void setTimeframe(Timeframe timeframe) { this.timeframe = timeframe; }
|
||||
|
||||
public LeaderboardType getScoreType() { return leaderboardType; }
|
||||
public void setScoreType(LeaderboardType leaderboardType) { this.leaderboardType = leaderboardType; }
|
||||
|
||||
public List<LeaderboardEntry> getEntries() { return entries; }
|
||||
public void setEntries(List<LeaderboardEntry> entries) { this.entries = entries; }
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package SuMoC.backend.gamification.scoretable.models;
|
||||
|
||||
public class LeaderboardEntry {
|
||||
private Long userId;
|
||||
private String username;
|
||||
private Boolean isFriend;
|
||||
private Long score;
|
||||
private String base64ProfilePicture;
|
||||
|
||||
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() {}
|
||||
|
||||
// Getter & Setter
|
||||
public Long getUserId() { return userId; }
|
||||
public void setUserId(Long userId) { this.userId = userId; }
|
||||
|
||||
public String getUsername() { return username; }
|
||||
public void setUsername(String username) { this.username = username; }
|
||||
|
||||
public Boolean getIsFriend() { return isFriend; }
|
||||
public void setIsFriend(Boolean isFriend) { this.isFriend = isFriend; }
|
||||
|
||||
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,7 @@
|
||||
package SuMoC.backend.gamification.scoretable.models;
|
||||
|
||||
public enum LeaderboardType {
|
||||
XP,
|
||||
CO2,
|
||||
KM
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
public class AddressDTO {
|
||||
// Getters and setters
|
||||
private String houseNumber;
|
||||
private String road;
|
||||
private String suburb;
|
||||
private String cityDistrict;
|
||||
private String city;
|
||||
private String state;
|
||||
private String iso3166_2_lvl4;
|
||||
private String postcode;
|
||||
private String country;
|
||||
private String countryCode;
|
||||
|
||||
// Constructor with fields
|
||||
public AddressDTO(String houseNumber, String road, String suburb, String cityDistrict, String city, String state, String iso3166_2_lvl4, String postcode, String country, String countryCode) {
|
||||
this.houseNumber = houseNumber;
|
||||
this.road = road;
|
||||
this.suburb = suburb;
|
||||
this.cityDistrict = cityDistrict;
|
||||
this.city = city;
|
||||
this.state = state;
|
||||
this.iso3166_2_lvl4 = iso3166_2_lvl4;
|
||||
this.postcode = postcode;
|
||||
this.country = country;
|
||||
this.countryCode = countryCode;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Service
|
||||
public class GeoCodingService {
|
||||
|
||||
private final GeocodingClient geocodingClient;
|
||||
|
||||
public GeoCodingService(GeocodingClient geocodingClient) {
|
||||
this.geocodingClient = geocodingClient;
|
||||
}
|
||||
|
||||
public Mono<AddressDTO> getAddress(double lat, double lon) {
|
||||
return geocodingClient.reverse(lat, lon)
|
||||
.map(this::mapToAddressDTO);
|
||||
}
|
||||
|
||||
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"),
|
||||
addressMap.get("suburb"),
|
||||
addressMap.get("city_district"),
|
||||
addressMap.get("city"),
|
||||
addressMap.get("state"),
|
||||
addressMap.get("ISO3166-2-lvl4"),
|
||||
addressMap.get("postcode"),
|
||||
addressMap.get("country"),
|
||||
addressMap.get("country_code")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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,25 @@
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/geocoding")
|
||||
public class GeocodingController {
|
||||
|
||||
private final GeoCodingService geoCodingService;
|
||||
|
||||
public GeocodingController(GeoCodingService geoCodingService) {
|
||||
this.geoCodingService = geoCodingService;
|
||||
}
|
||||
|
||||
@GetMapping("/reverse")
|
||||
@Operation(description = "Returns the address at the given lat / lon.")
|
||||
public Mono<AddressDTO> reverse(@RequestParam double lat, @RequestParam double lon) {
|
||||
return geoCodingService.getAddress(lat, lon);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public class NominatimClient implements GeocodingClient {
|
||||
|
||||
private final WebClient nominatimClient;
|
||||
|
||||
public NominatimClient(WebClient nominatimClient) {
|
||||
this.nominatimClient = nominatimClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<GeocodingResponse> reverse(double lat, double lon) {
|
||||
return nominatimClient.get()
|
||||
.uri(uriBuilder -> uriBuilder.path("/reverse")
|
||||
.queryParam("lat", lat)
|
||||
.queryParam("lon", lon)
|
||||
.queryParam("format", "jsonv2")
|
||||
.build())
|
||||
.retrieve()
|
||||
.bodyToMono(ReverseResponse.class)
|
||||
.map(response -> new GeocodingResponse(response.address()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package SuMoC.backend.geocoding;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public record ReverseResponse(
|
||||
@JsonProperty("place_id") long placeId,
|
||||
String licence,
|
||||
@JsonProperty("osm_type") String osmType,
|
||||
@JsonProperty("osm_id") long osmId,
|
||||
String lat,
|
||||
String lon,
|
||||
@JsonProperty("display_name") String displayName,
|
||||
@JsonProperty("address") Map<String, String> address
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package SuMoC.backend.h3;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "h3")
|
||||
@Getter
|
||||
@Setter
|
||||
public class H3Configuration {
|
||||
|
||||
/**
|
||||
* H3 resolution for route pattern detection.
|
||||
* Typically slightly lower resolution for broader matching.
|
||||
*/
|
||||
private int routePatternResolution = 10;
|
||||
|
||||
/**
|
||||
* Number of hexagonal rings to include when matching route patterns.
|
||||
* K-ring depth where k=1 includes immediate neighbors (6 hexagons),
|
||||
* k=2 includes two rings (18 hexagons), etc.
|
||||
* Higher values allow fuzzier location matching but may incorrectly
|
||||
* group distinct locations.
|
||||
* Consider resolution when setting.
|
||||
* Default: 1 (immediate neighbors only)
|
||||
*/
|
||||
private int routePatternNeighborRings = 1;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package SuMoC.backend.h3;
|
||||
|
||||
import com.uber.h3core.H3Core;
|
||||
import com.uber.h3core.util.LatLng;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Service for H3 spatial indexing operations.
|
||||
* H3 is a hierarchical hexagonal geospatial indexing system.
|
||||
*/
|
||||
@Service
|
||||
public class H3Service {
|
||||
|
||||
private final H3Core h3;
|
||||
private final H3Configuration config;
|
||||
|
||||
public H3Service(H3Configuration config) {
|
||||
this.config = config;
|
||||
try {
|
||||
this.h3 = H3Core.newInstance();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to initialize H3Core", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert latitude/longitude to H3 cell ID with specific resolution.
|
||||
*
|
||||
* @param latitude Latitude in degrees
|
||||
* @param longitude Longitude in degrees
|
||||
* @param resolution H3 resolution (0-15, higher = more precise)
|
||||
* @return H3 cell ID as hex string
|
||||
*/
|
||||
public String latLngToCell(double latitude, double longitude, int resolution) {
|
||||
return h3.latLngToCellAddress(latitude, longitude, resolution);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert latitude/longitude to H3 cell ID using route pattern resolution.
|
||||
* This is typically used for detecting regular trip patterns.
|
||||
*
|
||||
* @param latitude Latitude in degrees
|
||||
* @param longitude Longitude in degrees
|
||||
* @return H3 cell ID as hex string
|
||||
*/
|
||||
public String latLngToCellForRoute(double latitude, double longitude) {
|
||||
return latLngToCell(latitude, longitude, config.getRoutePatternResolution());
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert H3 cell ID to center latitude/longitude.
|
||||
*
|
||||
* @param cellId H3 cell ID as hex string
|
||||
* @return LatLng of cell center
|
||||
*/
|
||||
public LatLng cellToLatLng(String cellId) {
|
||||
return h3.cellToLatLng(cellId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all cells within k distance of the given cell (excluding the cell it self).
|
||||
* K-ring distance means cells reachable in k steps on the hexagonal grid.
|
||||
*
|
||||
* @param cellId H3 cell ID as hex string
|
||||
* @param k Distance (number of rings, 0 = only the cell itself)
|
||||
* @return List of H3 cell IDs including the origin cell
|
||||
*/
|
||||
public List<String> getKRingNeighbors(String cellId, int k) {
|
||||
return h3.gridRing(cellId, k);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get K-ring neighbors using the configured route pattern resolution distance.
|
||||
* Ring means the center cell is not included.
|
||||
* Useful for finding nearby locations when matching trip patterns.
|
||||
*
|
||||
* @param cellId H3 cell ID as hex string
|
||||
* @return List of H3 cell IDs within configured neighbor distance
|
||||
*/
|
||||
public List<String> getRoutePatternNeighbors(String cellId) {
|
||||
return getKRingNeighbors(cellId, config.getRoutePatternNeighborRings());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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,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";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package SuMoC.backend.meteo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public record ForecastResponse(
|
||||
double latitude,
|
||||
double longitude,
|
||||
@JsonProperty("generationtime_ms") double generationtimeMs,
|
||||
@JsonProperty("utc_offset_seconds") int utcOffsetSeconds,
|
||||
String timezone,
|
||||
@JsonProperty("timezone_abbreviation") String timezoneAbbreviation,
|
||||
double elevation,
|
||||
@JsonProperty("hourly_units") HourlyUnits hourlyUnits,
|
||||
Hourly hourly
|
||||
) {
|
||||
private static int findIndex(ForecastResponse forecast, LocalDateTime target) {
|
||||
int index = -1;
|
||||
for (int i = 0; i < forecast.hourly().time().size(); i++) {
|
||||
LocalDateTime entry = forecast.hourly().time().get(i);
|
||||
if (entry.toLocalDate().equals(target.toLocalDate()) && entry.getHour() == target.getHour()) {
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (index == -1) throw new RuntimeException("Start or end not found in list received from meteo.");
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the weather code for a specific point in time.
|
||||
*
|
||||
* @param dateTime the target date and time
|
||||
* @return the weather code if found, empty otherwise
|
||||
*/
|
||||
public Optional<Integer> getWeatherCodeAt(LocalDateTime dateTime) {
|
||||
if (hourly == null || hourly.time == null || hourly.weatherCode == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
for (int i = 0; i < hourly.time.size(); i++) {
|
||||
if (hourly.time.get(i).equals(dateTime)) {
|
||||
return Optional.of(hourly.weatherCode.get(i));
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public List<WeatherCondition> getWeatherConditionsBetween(
|
||||
Instant start,
|
||||
Instant end
|
||||
) throws Exception {
|
||||
LocalDateTime startDateTime = start.atZone(ZoneId.systemDefault()).toLocalDateTime();
|
||||
LocalDateTime endDateTime = end.atZone(ZoneId.systemDefault()).toLocalDateTime();
|
||||
if (start.isAfter(end)) {
|
||||
throw new IllegalArgumentException("Start must be before end");
|
||||
}
|
||||
|
||||
int startIndex = findIndex(this, startDateTime);
|
||||
int endIndex = findIndex(this, endDateTime);
|
||||
|
||||
var results = new ArrayList<WeatherCondition>();
|
||||
for (int i = startIndex; i <= endIndex; i++)
|
||||
results.add(WeatherCondition.from(this.hourly().weatherCode().get(i)));
|
||||
return results;
|
||||
|
||||
}
|
||||
|
||||
public record HourlyUnits(
|
||||
String time,
|
||||
@JsonProperty("weather_code") String weatherCode
|
||||
) {
|
||||
}
|
||||
|
||||
public record Hourly(
|
||||
List<LocalDateTime> time,
|
||||
@JsonProperty("weather_code") List<Integer> weatherCode
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package SuMoC.backend.meteo;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ForecastService {
|
||||
|
||||
private final MeteoClient meteoClient;
|
||||
|
||||
/**
|
||||
* Returns forecast for today and yesterday.
|
||||
*/
|
||||
public ForecastResponse getTodayYesterdayForecast(
|
||||
double latitude,
|
||||
double longitude) {
|
||||
return meteoClient.getForecastWeatherCodeTodayYesterday(latitude, longitude).block();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package SuMoC.backend.meteo;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Service
|
||||
public class MeteoClient {
|
||||
|
||||
private final WebClient meteoClient;
|
||||
|
||||
public MeteoClient(@Qualifier("meteoWebClient") WebClient meteoClient) {
|
||||
this.meteoClient = meteoClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple wrapper around meteo's forecast API.
|
||||
* https://open-meteo.com/en/docs
|
||||
*/
|
||||
public Mono<ForecastResponse> getForecastWeatherCodeTodayYesterday(
|
||||
double lat,
|
||||
double lon
|
||||
) {
|
||||
String today = LocalDate.now().toString(); // Uses ISO-8601 format: yyyy-MM-dd
|
||||
// We include yesterday for cases where routes cross midnight
|
||||
String yesterday = LocalDate.now().minusDays(1).toString();
|
||||
|
||||
return meteoClient.get()
|
||||
.uri(uriBuilder -> uriBuilder.path("/forecast")
|
||||
.queryParam("latitude", lat)
|
||||
.queryParam("longitude", lon)
|
||||
.queryParam("hourly", "weather_code")
|
||||
.queryParam("start_date", yesterday)
|
||||
.queryParam("end_date", today)
|
||||
.build())
|
||||
.retrieve()
|
||||
.bodyToMono(ForecastResponse.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package SuMoC.backend.meteo;
|
||||
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
|
||||
@Configuration
|
||||
@EnableConfigurationProperties(MeteoProperties.class)
|
||||
public class MeteoClientConfig {
|
||||
|
||||
@Bean
|
||||
public WebClient meteoWebClient(MeteoProperties properties) {
|
||||
return WebClient.builder()
|
||||
.baseUrl(properties.baseUrl())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package SuMoC.backend.meteo;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@ConfigurationProperties(prefix = "meteo")
|
||||
public record MeteoProperties(
|
||||
String baseUrl
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
Weather client based on the public API from https://open-meteo.com:
|
||||
|
||||
[Forecast](https://open-meteo.com/en/docs)
|
||||
|
||||
- to be used for future and
|
||||
|
||||
[Historical Weather](https://open-meteo.com/en/docs/historical-weather-api)
|
||||
@@ -0,0 +1,7 @@
|
||||
package SuMoC.backend.meteo;
|
||||
|
||||
public class UnknownWeatherCodeException extends RuntimeException {
|
||||
public UnknownWeatherCodeException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package SuMoC.backend.meteo;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Simplified WMO weather codes, taken from https://gist.github.com/stellasphere/9490c195ed2b53c707087c8c2db4ec0c
|
||||
*/
|
||||
public enum WeatherCondition {
|
||||
|
||||
CLEAR(Set.of(0, 1)),
|
||||
PARTLY_CLOUDY(Set.of(2)),
|
||||
CLOUDY(Set.of(3)),
|
||||
|
||||
FOG(Set.of(45, 48)),
|
||||
|
||||
DRIZZLE(Set.of(51, 53, 55, 56, 57)),
|
||||
RAIN(Set.of(61, 63, 65, 66, 67)),
|
||||
|
||||
SNOW(Set.of(71, 73, 75, 77, 85, 86)),
|
||||
|
||||
SHOWERS(Set.of(80, 81, 82)),
|
||||
|
||||
THUNDERSTORM(Set.of(95, 96, 99)),
|
||||
|
||||
UNKNOWN(Set.of());
|
||||
|
||||
private final Set<Integer> codes;
|
||||
|
||||
WeatherCondition(Set<Integer> codes) {
|
||||
this.codes = codes;
|
||||
}
|
||||
|
||||
public static WeatherCondition from(int code) throws Exception {
|
||||
for (WeatherCondition condition : values()) {
|
||||
if (condition.codes.contains(code)) {
|
||||
return condition;
|
||||
}
|
||||
}
|
||||
throw new UnknownWeatherCodeException("Encountered unknown weather code.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
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();
|
||||
}
|
||||
|
||||
// Simple record for request body
|
||||
public record RegisterDeviceTokenRequest(String token, NotificationProvider provider) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package SuMoC.backend.notification.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@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;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package SuMoC.backend.notification.enums;
|
||||
|
||||
public enum NotificationProvider {
|
||||
FIREBASE,
|
||||
}
|
||||
@@ -0,0 +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,20 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package SuMoC.backend.notification.interfaces;
|
||||
|
||||
public interface Notifieable {
|
||||
Long getUserId();
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
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.LocalTime;
|
||||
|
||||
@Entity
|
||||
@Table(name = "notifications")
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class Notification {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
private User user;
|
||||
|
||||
@Column(nullable = false)
|
||||
@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.
|
||||
* Useful since we might want to send messages about specific trips immediately but not inform about trend changes
|
||||
* etc. in the middle of night when calculating jobs might run.
|
||||
*/
|
||||
@Column(nullable = false)
|
||||
private LocalTime earliestTimeOfDayToSend;
|
||||
|
||||
@Column(nullable = false)
|
||||
@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 LocalDateTime createdAt;
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package SuMoC.backend.notification.repositories;
|
||||
|
||||
import SuMoC.backend.notification.models.Notification;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
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);
|
||||
|
||||
@Modifying
|
||||
@Query("""
|
||||
DELETE
|
||||
FROM Notification n
|
||||
WHERE n.createdAt < :cutOff
|
||||
""")
|
||||
void deleteNotificationsOlder(LocalDateTime cutOff);
|
||||
}
|
||||
+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,83 @@
|
||||
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.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.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class NotificationSchedulerService {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
private final NotificationRepository notificationRepository;
|
||||
|
||||
private final EntityManager entityManager;
|
||||
|
||||
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(LocalDateTime.now())
|
||||
.failedSendAttempts(0)
|
||||
.build();
|
||||
}).toList();
|
||||
|
||||
notificationRepository.saveAll(notifications);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
User userProxy = entityManager.getReference(User.class, userId);
|
||||
|
||||
Notification notification = Notification.builder()
|
||||
.user(userProxy)
|
||||
.type(notificationType)
|
||||
.data(dataBodyJson)
|
||||
.earliestTimeOfDayToSend(earliestTimeOfDayToSend)
|
||||
.status(NotificationStatus.PENDING)
|
||||
.createdAt(LocalDateTime.now())
|
||||
.failedSendAttempts(0)
|
||||
.build();
|
||||
|
||||
notificationRepository.save(notification);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
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.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();
|
||||
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);
|
||||
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());
|
||||
if (notification.getFailedSendAttempts() >= notificationProperties.getMaxFailedSendAttempts()) {
|
||||
notification.setStatus(NotificationStatus.FAILED);
|
||||
}
|
||||
notificationRepository.save(notification);
|
||||
logger.severe("Failed to send notification with id:" + notification.getId() + " " + t.getMessage());
|
||||
}
|
||||
}, MoreExecutors.directExecutor());
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
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.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
@RequiredArgsConstructor
|
||||
public class NotificationWorker {
|
||||
|
||||
private final NotificationRepository notificationRepository;
|
||||
|
||||
private final NotificationSender notificationSender;
|
||||
|
||||
/**
|
||||
* Process all pending notifications.
|
||||
*/
|
||||
public void run() {
|
||||
// Get all pending notifications where earliest send time has passed and status is pending
|
||||
List<Notification> pendingNotifications =
|
||||
notificationRepository.findPendingNotificationsToSend(LocalTime.now());
|
||||
// Send them
|
||||
for (Notification notification : pendingNotifications) {
|
||||
notificationSender.sendNotification(notification);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up old notifications.
|
||||
*/
|
||||
public void cleanUpOldNotifications() {
|
||||
// Delete notifications older than 30 days
|
||||
notificationRepository.deleteNotificationsOlder(LocalDateTime.now().minusDays(30));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package SuMoC.backend.regulartrip.config;
|
||||
|
||||
import SuMoC.backend.regulartrip.detectionapproaches.Detector;
|
||||
import SuMoC.backend.regulartrip.detectionapproaches.IterativeClusterer;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class DetectorConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnProperty(
|
||||
prefix = "regulartripdetection",
|
||||
name = "detection-algorithm",
|
||||
havingValue = "iterative",
|
||||
matchIfMissing = true
|
||||
)
|
||||
public IterativeClusterer iterativeClusterer(RegularTripDetectionProperties properties) {
|
||||
return new IterativeClusterer(properties);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package SuMoC.backend.regulartrip.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "regulartripdetection")
|
||||
public class RegularTripDetectionProperties {
|
||||
|
||||
// TODO at end check if this is really right place for these vals
|
||||
/**
|
||||
* Minimum number of trips a user must have made between the same start and end locations
|
||||
* for those trips to be considered regular.
|
||||
*/
|
||||
private Integer minTripsForRegularity = 2;
|
||||
|
||||
/**
|
||||
* Time window in days to look back for detecting regular trips.
|
||||
*/
|
||||
private Integer detectionTimeWindowDays = 40;
|
||||
|
||||
/**
|
||||
* Maximum time difference in minutes between trips to be considered the same regular trip.
|
||||
*/
|
||||
private Integer timeWindowSeconds = 90 * 60;
|
||||
|
||||
/**
|
||||
* Number of times the iterative algorithm is run on randomly shuffled trip lists to pick best results.
|
||||
*/
|
||||
private Integer iterativeShuffleAmounts = 5;
|
||||
|
||||
private String detectionAlgorithm = "iterative";
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package SuMoC.backend.regulartrip.detectionapproaches;
|
||||
|
||||
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
|
||||
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface Detector {
|
||||
|
||||
/**
|
||||
* Core function to analyze a list of one users trips for regular trips. Assumes all trips have the same modality and user.
|
||||
*/
|
||||
List<DetectedRegularTripDTO> detectRegularTrips(List<RegularTripDetectionDTO> trips);
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package SuMoC.backend.regulartrip.detectionapproaches;
|
||||
|
||||
import SuMoC.backend.regulartrip.config.RegularTripDetectionProperties;
|
||||
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
|
||||
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
|
||||
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This is the first approach of a regular trip detection algorithm.
|
||||
*/
|
||||
public class IterativeClusterer implements Detector {
|
||||
|
||||
private final RegularTripDetectionProperties properties;
|
||||
|
||||
public IterativeClusterer(RegularTripDetectionProperties properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DetectedRegularTripDTO> detectRegularTrips(List<RegularTripDetectionDTO> trips) {
|
||||
// Step 1: Init potential detected trip for all trips
|
||||
HashMap<Long, DetectedRegularTripDTO> baseDetectedTripsMap = initDetectedTripsMap(trips);
|
||||
// Step 2: Find trips supported by min number of supporters
|
||||
|
||||
List<List<DetectedRegularTripDTO>> iterationResults = new ArrayList<>();
|
||||
for (int i = 0; i < properties.getIterativeShuffleAmounts(); i++) {
|
||||
// Deep copy the map for each iteration
|
||||
HashMap<Long, DetectedRegularTripDTO> iterationMap = deepCopyDetectedTripsMap(baseDetectedTripsMap);
|
||||
Collections.shuffle(trips);
|
||||
iterationResults.add(aggregateToSupportedDetections(iterationMap, trips, properties.getMinTripsForRegularity()));
|
||||
}
|
||||
|
||||
List<DetectedRegularTripDTO> bestIteration = pickBestIteration(iterationResults);
|
||||
return deduplicateOverlappingDetections(bestIteration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks the best detection results by picking iteration with the highest total number of supporters.
|
||||
*/
|
||||
private List<DetectedRegularTripDTO> pickBestIteration(List<List<DetectedRegularTripDTO>> iterationResults) {
|
||||
return iterationResults.stream()
|
||||
.max(Comparator.comparingInt(iteration ->
|
||||
iteration.stream()
|
||||
// subtracting 1 to avoid inflation by self supporting -> less detections with more supporters are better
|
||||
.mapToInt(detection -> detection.getSupportingTrips().size() - 1)
|
||||
.sum()))
|
||||
.orElse(List.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes overlapping detections by greedily selecting the best non-overlapping set.
|
||||
* Detections with more supporters are prioritized.
|
||||
*/
|
||||
private List<DetectedRegularTripDTO> deduplicateOverlappingDetections(List<DetectedRegularTripDTO> detections) {
|
||||
// Sort by supporter count (descending)
|
||||
List<DetectedRegularTripDTO> sorted = new ArrayList<>(detections);
|
||||
sorted.sort(Comparator.comparingInt(d -> -d.getSupportingTrips().size()));
|
||||
|
||||
List<DetectedRegularTripDTO> result = new ArrayList<>();
|
||||
Set<Long> usedTripIds = new HashSet<>();
|
||||
|
||||
for (DetectedRegularTripDTO detection : sorted) {
|
||||
// Get all trip IDs involved in this detection
|
||||
Set<Long> detectionTripIds = new HashSet<>();
|
||||
for (RegularTripDetectionDTO trip : detection.getSupportingTrips()) {
|
||||
detectionTripIds.add(trip.getTripId());
|
||||
}
|
||||
|
||||
// Check if any trips are already used
|
||||
boolean hasOverlap = detectionTripIds.stream().anyMatch(usedTripIds::contains);
|
||||
|
||||
if (!hasOverlap) {
|
||||
result.add(detection);
|
||||
usedTripIds.addAll(detectionTripIds);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes a map with potential detected regular trips and checks against a list of trips which are supported
|
||||
* If a trip supports another detected regular trips, its own regular trip is removed.
|
||||
*/
|
||||
private List<DetectedRegularTripDTO> aggregateToSupportedDetections(
|
||||
HashMap<Long, DetectedRegularTripDTO> potentialDetectedRegularTrips,
|
||||
List<RegularTripDetectionDTO> trips,
|
||||
int necessarySupporters
|
||||
) {
|
||||
// We need to dupe deletions with this list since we cant modify other list entries while iterating over it
|
||||
Set<Long> deletedDetections = new HashSet<>();
|
||||
|
||||
for (Map.Entry<Long, DetectedRegularTripDTO> entry : potentialDetectedRegularTrips.entrySet()) {
|
||||
if (deletedDetections.contains(entry.getKey())) continue;
|
||||
|
||||
// Check for all other trips if they support this detected regular trip
|
||||
for (RegularTripDetectionDTO trip : trips) {
|
||||
// prevent checking against trip the detected regular trip stems from
|
||||
if (entry.getKey() == trip.getTripId()) continue;
|
||||
|
||||
if (supportsDetectedRegularTrip(entry.getValue(), trip)) {
|
||||
entry.getValue().getSupportingTrips().add(trip);
|
||||
// remove trip's own potential regular trip since its now a supporter
|
||||
deletedDetections.add(trip.getTripId());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// Generate final results
|
||||
List<DetectedRegularTripDTO> detectedTrips = new ArrayList<>();
|
||||
for (Map.Entry<Long, DetectedRegularTripDTO> entry : potentialDetectedRegularTrips.entrySet()) {
|
||||
if (deletedDetections.contains(entry.getKey())) continue;
|
||||
if (entry.getValue().getSupportingTrips().size() >= necessarySupporters) {
|
||||
detectedTrips.add(entry.getValue());
|
||||
}
|
||||
}
|
||||
return detectedTrips;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method holds the core logic to determine if a trip supports a detected regular trip.
|
||||
*/
|
||||
private boolean supportsDetectedRegularTrip(DetectedRegularTripDTO regularTrip, RegularTripDetectionDTO trip) {
|
||||
// Conditions:
|
||||
// 1. same day of week
|
||||
if (regularTrip.getDayOfWeek() == trip.getDayOfTheWeek()) {
|
||||
// 2. Departure and arrival within window
|
||||
if (isWithinTimeWindow(regularTrip, trip)) {
|
||||
// 3. Same start and end area
|
||||
if (sameStartAndEndCellArea(regularTrip, trip)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* We consider start and end to be the same place when cells match or are direct neighbours.
|
||||
*/
|
||||
private boolean sameStartAndEndCellArea(DetectedRegularTripDTO regularTripDTO, RegularTripDetectionDTO trip) {
|
||||
if (trip.getStartH3Cell().equals(regularTripDTO.getStartH3Center()) || regularTripDTO.getStartH3neighbours().contains(trip.getStartH3Cell())) {
|
||||
return trip.getEndH3Cell().equals(regularTripDTO.getEndH3Center()) || regularTripDTO.getEndH3Neighbours().contains(trip.getEndH3Cell());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean isWithinTimeWindow(DetectedRegularTripDTO regularTrip, RegularTripDetectionDTO trip) {
|
||||
LocalTime departure = LocalTime.ofInstant(trip.getStartTime(), ZoneId.systemDefault());
|
||||
LocalTime arrival = LocalTime.ofInstant(trip.getEndTime(), ZoneId.systemDefault());
|
||||
if (departure.isAfter(regularTrip.getDepartureWindowStart()) && departure.isBefore(regularTrip.getDepartureWindowEnd())) {
|
||||
return arrival.isAfter(regularTrip.getArrivalWindowStart()) && arrival.isBefore(regularTrip.getArrivalWindowEnd());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts all trips to a detected regular trip, using original tripId as map key
|
||||
*/
|
||||
private HashMap<Long, DetectedRegularTripDTO> initDetectedTripsMap(List<RegularTripDetectionDTO> trips) {
|
||||
HashMap<Long, DetectedRegularTripDTO> potentialDetectedTrips = new HashMap<>();
|
||||
|
||||
for (RegularTripDetectionDTO trip : trips) {
|
||||
LocalTime departure = LocalTime.ofInstant(trip.getStartTime(), ZoneId.systemDefault());
|
||||
LocalTime arrival = LocalTime.ofInstant(trip.getEndTime(), ZoneId.systemDefault());
|
||||
|
||||
potentialDetectedTrips.put(trip.getTripId(), DetectedRegularTripDTO.builder()
|
||||
.modality(trip.getMainModality())
|
||||
.userId(trip.getUserId())
|
||||
.dayOfWeek(trip.getDayOfTheWeek())
|
||||
.departureWindowStart(departure.minusSeconds(properties.getTimeWindowSeconds() / 2))
|
||||
.departureWindowEnd(departure.plusSeconds(properties.getTimeWindowSeconds() / 2))
|
||||
.arrivalWindowStart(arrival.minusSeconds(properties.getTimeWindowSeconds() / 2))
|
||||
.arrivalWindowEnd(arrival.plusSeconds(properties.getTimeWindowSeconds() / 2))
|
||||
.startH3Center(trip.getStartH3Cell())
|
||||
.endH3Center(trip.getEndH3Cell())
|
||||
.startH3neighbours(trip.getStartH3CellKRingNeighboors())
|
||||
.endH3Neighbours(trip.getEndH3CellKRingNeighboors())
|
||||
.supportingTrips(new ArrayList<RegularTripDetectionDTO>(List.of(trip)))
|
||||
.build());
|
||||
}
|
||||
return potentialDetectedTrips;
|
||||
}
|
||||
|
||||
private HashMap<Long, DetectedRegularTripDTO> deepCopyDetectedTripsMap(
|
||||
HashMap<Long, DetectedRegularTripDTO> original) {
|
||||
|
||||
HashMap<Long, DetectedRegularTripDTO> copy = new HashMap<>();
|
||||
|
||||
for (Map.Entry<Long, DetectedRegularTripDTO> entry : original.entrySet()) {
|
||||
DetectedRegularTripDTO originalDto = entry.getValue();
|
||||
|
||||
// Create new DTO with copied supporting trips list
|
||||
DetectedRegularTripDTO copiedDto = DetectedRegularTripDTO.builder()
|
||||
.modality(originalDto.getModality())
|
||||
.userId(originalDto.getUserId())
|
||||
.dayOfWeek(originalDto.getDayOfWeek())
|
||||
.departureWindowStart(originalDto.getDepartureWindowStart())
|
||||
.departureWindowEnd(originalDto.getDepartureWindowEnd())
|
||||
.arrivalWindowStart(originalDto.getArrivalWindowStart())
|
||||
.arrivalWindowEnd(originalDto.getArrivalWindowEnd())
|
||||
.startH3Center(originalDto.getStartH3Center())
|
||||
.endH3Center(originalDto.getEndH3Center())
|
||||
.startH3neighbours(originalDto.getStartH3neighbours())
|
||||
.endH3Neighbours(originalDto.getEndH3Neighbours())
|
||||
.supportingTrips(new ArrayList<>(originalDto.getSupportingTrips())) // New list
|
||||
.build();
|
||||
|
||||
copy.put(entry.getKey(), copiedDto);
|
||||
}
|
||||
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
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.DayOfWeek;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A DTO representing the details of a detected regular trip.
|
||||
*/
|
||||
@Builder
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class DetectedRegularTripDTO {
|
||||
private long userId;
|
||||
private Modality modality;
|
||||
private DayOfWeek dayOfWeek;
|
||||
private LocalTime departureWindowStart;
|
||||
private LocalTime departureWindowEnd;
|
||||
private LocalTime arrivalWindowStart;
|
||||
private LocalTime arrivalWindowEnd;
|
||||
private String startH3Center;
|
||||
private String endH3Center;
|
||||
private List<String> startH3neighbours;
|
||||
private List<String> endH3Neighbours;
|
||||
private List<RegularTripDetectionDTO> supportingTrips;
|
||||
|
||||
/**
|
||||
* 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 LocalTime getAverageArrivalTime() {
|
||||
int totalSeconds = 0;
|
||||
for (RegularTripDetectionDTO trip : supportingTrips) {
|
||||
totalSeconds += trip.getEndTime().atOffset(ZoneOffset.UTC).toLocalTime().toSecondOfDay();
|
||||
}
|
||||
int averageSeconds = totalSeconds / supportingTrips.size();
|
||||
return LocalTime.ofSecondOfDay(averageSeconds);
|
||||
}
|
||||
|
||||
public int getAverageDurationMinutes() {
|
||||
int totalDuration = 0;
|
||||
for (RegularTripDetectionDTO trip : supportingTrips) {
|
||||
totalDuration += trip.getDurationMinutes();
|
||||
}
|
||||
return totalDuration / supportingTrips.size();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package SuMoC.backend.regulartrip.services;
|
||||
|
||||
import SuMoC.backend.regulartrip.config.RegularTripDetectionProperties;
|
||||
import SuMoC.backend.regulartrip.detectionapproaches.Detector;
|
||||
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
|
||||
import SuMoC.backend.trip.Modality;
|
||||
import SuMoC.backend.trip.TripMapper;
|
||||
import SuMoC.backend.trip.TripRepository;
|
||||
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class RegularTripDetectionService {
|
||||
|
||||
RegularTripDetectionProperties properties;
|
||||
|
||||
TripRepository tripRepository;
|
||||
|
||||
TripMapper tripMapper;
|
||||
|
||||
Detector tripDetector;
|
||||
|
||||
/**
|
||||
* Detects regular trips for 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>> detectRegularCarTripsByUserForDayOfWeek(DayOfWeek dayOfWeek) {
|
||||
var tripsByUser = getTripsByUser(Modality.CAR, dayOfWeek);
|
||||
|
||||
HashMap<Long, List<DetectedRegularTripDTO>> results = new HashMap<>();
|
||||
for (Long userId : tripsByUser.keySet()) {
|
||||
results.put(userId, tripDetector.detectRegularTrips(tripsByUser.get(userId)));
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
private HashMap<Long, List<RegularTripDetectionDTO>> getTripsByUser(Modality modality, DayOfWeek dayOfWeek) {
|
||||
Instant fromDate = Instant.now().minusSeconds(properties.getDetectionTimeWindowDays() * 24 * 60 * 60);
|
||||
List<RegularTripDetectionDTO> dtoList = tripMapper.toRegularTripDetectionDTOS(tripRepository.findAllValidFromDateWithMainModalityOnCertainWeekday(fromDate, modality, dayOfWeek));
|
||||
|
||||
HashMap<Long, List<RegularTripDetectionDTO>> tripsByUser = new HashMap<>();
|
||||
for (RegularTripDetectionDTO dto : dtoList) {
|
||||
tripsByUser.computeIfAbsent(dto.getUserId(), k -> new ArrayList<>()).add(dto);
|
||||
}
|
||||
return tripsByUser;
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package SuMoC.backend.routing;
|
||||
|
||||
import SuMoC.backend.routing.dtos.RouteAlternativeDTO;
|
||||
import SuMoC.backend.routing.dtos.RouteAlternativeRequestDTO;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
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/alternative")
|
||||
public class RoutingAlternativeController {
|
||||
private final RoutingAlternativeService routingAlternativeService;
|
||||
|
||||
@Autowired
|
||||
public RoutingAlternativeController(RoutingAlternativeService routingAlternativeService) {
|
||||
this.routingAlternativeService = routingAlternativeService;
|
||||
}
|
||||
|
||||
// TODO operation description + how to handle preferences (optional, if not provided use saved users prefs or default
|
||||
@PostMapping("/request")
|
||||
public ResponseEntity<List<RouteAlternativeDTO>> requestAlternativeRoutes(@Valid @RequestBody RouteAlternativeRequestDTO routeAlternativeRequestDTO) {
|
||||
// Implementation goes here
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package SuMoC.backend.routing;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class RoutingAlternativeService {
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package SuMoC.backend.routing.config;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/**
|
||||
* These are the routing properties for alternatives that are calculated as a resonse to an uploaded trip.
|
||||
* We separate these from properties for OnCall (Explicitly Requested by user) routing properties since
|
||||
* the assumption is that "unasked for" alternatives have less tolerance for additional travel time etc.
|
||||
*/
|
||||
@ConfigurationProperties(prefix = "routing.adhoc")
|
||||
@Getter
|
||||
@Setter
|
||||
public class AdHocRoutingProperties extends RoutingProperties {
|
||||
|
||||
public AdHocRoutingProperties() {
|
||||
super();
|
||||
setAcceptableAdditionalMultiplierRegular(1.30);
|
||||
setAcceptableAdditionalMultiplierPrefersPhysical(1.6);
|
||||
setMinimumAcceptedAdditionalSecondsRegular(5 * 60);
|
||||
setMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity(5 * 60);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package SuMoC.backend.routing.config;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/**
|
||||
* These are the routing properties for alternatives explicitly requested by the user.
|
||||
*/
|
||||
@ConfigurationProperties(prefix = "routing.oncall")
|
||||
@Getter
|
||||
@Setter
|
||||
public class OnCallRoutingProperties extends RoutingProperties {
|
||||
|
||||
public OnCallRoutingProperties() {
|
||||
super();
|
||||
setAcceptableAdditionalMultiplierRegular(1.50);
|
||||
setAcceptableAdditionalMultiplierPrefersPhysical(1.80);
|
||||
setMinimumAcceptedAdditionalSecondsRegular(10 * 60);
|
||||
setMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity(15 * 60);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package SuMoC.backend.routing.config;
|
||||
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@EnableConfigurationProperties({
|
||||
OnCallRoutingProperties.class,
|
||||
AdHocRoutingProperties.class
|
||||
})
|
||||
public class RoutingConfig {
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package SuMoC.backend.routing.config;
|
||||
|
||||
import SuMoC.backend.meteo.WeatherCondition;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public abstract class RoutingProperties {
|
||||
/**
|
||||
* Multiplier of how much more travel time is tolerated for alternative routing.
|
||||
*/
|
||||
private double acceptableAdditionalMultiplierRegular;
|
||||
|
||||
/**
|
||||
* Multiplier of accepted additional travel time for users that wish more physical activity.
|
||||
*/
|
||||
private double acceptableAdditionalMultiplierPrefersPhysical;
|
||||
|
||||
/**
|
||||
* Minimum of accepted additional travel time for regular users which is always accepted.
|
||||
*/
|
||||
private Integer minimumAcceptedAdditionalSecondsRegular;
|
||||
|
||||
/**
|
||||
* Minimum of accepted additional travel time for users that wish more physical activity.
|
||||
*/
|
||||
private Integer minimumAcceptedAdditionalSecondsPrefersPhysicalActivity;
|
||||
|
||||
private List<WeatherCondition> acceptableWalkingConditions;
|
||||
|
||||
private List<WeatherCondition> acceptableCyclingConditions;
|
||||
|
||||
public RoutingProperties() {
|
||||
this.acceptableCyclingConditions = List.of(
|
||||
WeatherCondition.CLEAR,
|
||||
WeatherCondition.PARTLY_CLOUDY,
|
||||
WeatherCondition.CLOUDY
|
||||
);
|
||||
this.acceptableWalkingConditions = List.of(
|
||||
WeatherCondition.CLEAR,
|
||||
WeatherCondition.PARTLY_CLOUDY,
|
||||
WeatherCondition.CLOUDY,
|
||||
WeatherCondition.FOG
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package SuMoC.backend.routing.controller;
|
||||
|
||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
|
||||
import SuMoC.backend.routing.services.RoutingPreferencesService;
|
||||
import SuMoC.backend.routing.services.RoutingService;
|
||||
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 org.springframework.web.reactive.function.client.WebClientRequestException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/routing/alternative")
|
||||
@RequiredArgsConstructor
|
||||
public class RoutingController {
|
||||
|
||||
private final Logger logger = Logger.getLogger(RoutingController.class.getName());
|
||||
|
||||
private final RoutingService routingService;
|
||||
|
||||
private final RoutingPreferencesService routingPreferencesService;
|
||||
|
||||
@PostMapping("/request")
|
||||
@Schema(description = "Calculates alternative, sustainable routes for the request. The delta of departure and arrival in the requestdto is used as baseline to determine if alternatives are acceptable.")
|
||||
public ResponseEntity<List<RouteDTO>> requestAlternativeRoutes(@Valid @RequestBody RoutingAlternativeRequestDTO routingAlternativeRequestDTO) {
|
||||
try {
|
||||
if (routingAlternativeRequestDTO.getRoutingPreferencesDTO() == null) {
|
||||
// This automatically uses default preferences for unauthenticated users
|
||||
routingAlternativeRequestDTO.setRoutingPreferencesDTO(routingPreferencesService.getRoutingPreferencesForCurrentUser());
|
||||
}
|
||||
|
||||
var routeDTOs = routingService.determineAlternativeRoutesOnUserRequest(routingAlternativeRequestDTO);
|
||||
return ResponseEntity.ok(routeDTOs);
|
||||
} catch (WebClientRequestException e) {
|
||||
// nominatim container is not up yet, we return mock
|
||||
logger.warning("Nominatim service is not available. Returning mock route data. Error: " + e.getMessage());
|
||||
ArrayList<RouteDTO> mockDTOs = new ArrayList<>();
|
||||
mockDTOs.add(RouteDTO.getMockRouteDTO());
|
||||
mockDTOs.add(RouteDTO.getMockRouteDTO());
|
||||
mockDTOs.add(RouteDTO.getMockRouteDTO());
|
||||
return ResponseEntity.ok(mockDTOs);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
package SuMoC.backend.routing.dtos;
|
||||
|
||||
public class RouteAlternativeDTO {
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
package SuMoC.backend.routing.dtos;
|
||||
|
||||
public class RouteAlternativeRequestDTO {
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package SuMoC.backend.routing.dtos;
|
||||
|
||||
import SuMoC.backend.geocoding.AddressDTO;
|
||||
import SuMoC.backend.trip.Modality;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.annotation.Nullable;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Schema(description = "This DTO represents a suggested route as a response to a requested alternative route.")
|
||||
public class RouteDTO {
|
||||
@Schema(description = "The actual address of the start location.")
|
||||
private AddressDTO startAddress;
|
||||
@Schema(description = "The name of the first stop if the route uses public transport. E.g. \"Essen West\" if the route starts with a footpath to the first train leaving there.")
|
||||
@Nullable
|
||||
private String firstStopName;
|
||||
@Schema(description = "The latitude of the start address.")
|
||||
private double startLat;
|
||||
@Schema(description = "The longitude of the start address.")
|
||||
private double startLon;
|
||||
@Schema(description = "The actual address of the end location.")
|
||||
private AddressDTO endAddress;
|
||||
@Schema(description = "The name of the last stop if the route uses public transport. E.g. \"Essen Hbf\" if the route ends with a train arriving there (might still contain a footpath afterwards).")
|
||||
@Nullable
|
||||
private String lastStopName;
|
||||
@Schema(description = "The latitude of the end address.")
|
||||
private double endLat;
|
||||
@Schema(description = "The longitude of the end address.")
|
||||
private double endLon;
|
||||
@Schema(description = "The start date and time of the route.")
|
||||
private Instant startDateTime;
|
||||
@Schema(description = "The end date and time of the route.")
|
||||
private Instant endDateTime;
|
||||
@Schema(description = "The steps the route consists of.")
|
||||
private List<StepDTO> steps;
|
||||
@Schema(description = "Amount of CO2e savings in gramm compared to a car trip for the same route.")
|
||||
private double co2Savings;
|
||||
@Schema(description = "CO2e emission of this route.")
|
||||
private double co2Emissions;
|
||||
@Schema(description = "The temporal difference in minutes compared to the original route the user requested alternatives for.")
|
||||
private double timeDifferenceSeconds;
|
||||
|
||||
public RouteDTO(AddressDTO startAddress, @Nullable String firstStopName, double startLat, double startLon, AddressDTO endAddress, @Nullable String lastStopName, double endLat, double endLon, Instant startDateTime, Instant endDateTime, List<StepDTO> steps, double co2Savings, double timeDifferenceSeconds, double co2Emissions) {
|
||||
this.startAddress = startAddress;
|
||||
this.firstStopName = firstStopName;
|
||||
this.startLat = startLat;
|
||||
this.startLon = startLon;
|
||||
this.endAddress = endAddress;
|
||||
this.lastStopName = lastStopName;
|
||||
this.endLat = endLat;
|
||||
this.endLon = endLon;
|
||||
this.startDateTime = startDateTime;
|
||||
this.endDateTime = endDateTime;
|
||||
this.steps = steps;
|
||||
this.co2Savings = co2Savings;
|
||||
this.co2Emissions = co2Emissions;
|
||||
this.timeDifferenceSeconds = timeDifferenceSeconds;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mock method for testing purposes
|
||||
*
|
||||
* @return RouteDto with mock data
|
||||
*/
|
||||
public static RouteDTO getMockRouteDTO() {
|
||||
var startAddress = new AddressDTO(
|
||||
"28a",
|
||||
"Janssenstraße",
|
||||
"Holsterhausen",
|
||||
"Stadtbezirk III",
|
||||
"Essen",
|
||||
"Nordrhein-Westfalen",
|
||||
"DE-NW",
|
||||
"45147",
|
||||
"Deutschland",
|
||||
"de"
|
||||
);
|
||||
var endAddress = new AddressDTO(
|
||||
"70",
|
||||
"Schützenbahn",
|
||||
null,
|
||||
null,
|
||||
"Essen",
|
||||
"Nordrhein-Westfalen",
|
||||
"DE-NW",
|
||||
"45127",
|
||||
"Deutschland",
|
||||
"de"
|
||||
);
|
||||
var dto = new RouteDTO(
|
||||
startAddress,
|
||||
"Rubensstraße",
|
||||
51.440395,
|
||||
6.984785,
|
||||
endAddress,
|
||||
"Viehhofer Platz",
|
||||
51.459167,
|
||||
7.014928,
|
||||
Instant.now().minus(Duration.ofMinutes(30)),
|
||||
Instant.now(),
|
||||
new ArrayList<StepDTO>(),
|
||||
120.5f,
|
||||
+16.3f,
|
||||
20
|
||||
);
|
||||
dto.steps.add(new StepDTO(
|
||||
Modality.WALKING,
|
||||
null,
|
||||
400f
|
||||
));
|
||||
dto.steps.add(new StepDTO(
|
||||
Modality.TRAM,
|
||||
"106",
|
||||
5000f
|
||||
));
|
||||
dto.steps.add(new StepDTO(
|
||||
Modality.WALKING,
|
||||
null,
|
||||
300f
|
||||
));
|
||||
return dto;
|
||||
}
|
||||
|
||||
public long getDurationSeconds() {
|
||||
return endDateTime.getEpochSecond() - startDateTime.getEpochSecond();
|
||||
}
|
||||
|
||||
/**
|
||||
* We consider routes that only consist of walking and cycling steps as physical activity.
|
||||
*/
|
||||
public boolean isPhysicalActivity() {
|
||||
return steps.stream().allMatch(step -> step.getModality() == Modality.WALKING || step.getModality() == Modality.BICYCLE);
|
||||
}
|
||||
|
||||
public boolean isCyclingRoute() {
|
||||
return steps.stream().allMatch(step -> step.getModality() == Modality.BICYCLE);
|
||||
}
|
||||
|
||||
public boolean isWalkingRoute() {
|
||||
return steps.stream().allMatch(step -> step.getModality() == Modality.WALKING);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user