Compare commits
75
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bd860ee6d8 | ||
|
|
d92b71179a | ||
|
|
0752a59fd9 | ||
|
|
1cca645696 | ||
|
|
1369f4f25d | ||
|
|
4e11dd2d78 | ||
|
|
f8c661ccb6 | ||
|
|
8bace01238 | ||
|
|
29a7811c97 | ||
|
|
813390286f | ||
|
|
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_URL=jdbc:postgresql://db:5432/sumoc
|
||||||
SPRING_DATASOURCE_USERNAME=postgres
|
SPRING_DATASOURCE_USERNAME=postgres
|
||||||
SPRING_DATASOURCE_PASSWORD=admin
|
SPRING_DATASOURCE_PASSWORD=admin
|
||||||
|
nominatim.base-url=http://nominatim:8080/
|
||||||
@@ -33,3 +33,11 @@ build/
|
|||||||
.vscode/
|
.vscode/
|
||||||
/generated/
|
/generated/
|
||||||
/.mvn/
|
/.mvn/
|
||||||
|
/app/
|
||||||
|
|
||||||
|
|
||||||
|
/docker_images/*.tar
|
||||||
|
|
||||||
|
### Secrets ###
|
||||||
|
src/main/resources/firebase-private-key.json
|
||||||
|
src/main/resources/firebase-private-key_disable.json
|
||||||
|
|||||||
Vendored
+16
@@ -32,5 +32,21 @@ node('built-in') {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// generate Swift/Kotlin API clients and provide artifact for download
|
||||||
|
stage('Generate API Clients') {
|
||||||
|
if (env.BRANCH_NAME == "deploy") {
|
||||||
|
sh 'mkdir -p app'
|
||||||
|
|
||||||
|
sh '''
|
||||||
|
chmod +x generateStuds.sh
|
||||||
|
./generateStuds.sh
|
||||||
|
'''
|
||||||
|
|
||||||
|
archiveArtifacts artifacts: 'app/**', allowEmptyArchive: false
|
||||||
|
} else {
|
||||||
|
echo "Skipping API client generation for non-deploy branch."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+17
-1
@@ -1,4 +1,6 @@
|
|||||||
version: '3.8'
|
volumes:
|
||||||
|
nominatim-data:
|
||||||
|
postgres_data:
|
||||||
|
|
||||||
services:
|
services:
|
||||||
db:
|
db:
|
||||||
@@ -8,6 +10,20 @@ services:
|
|||||||
- POSTGRES_USER=postgres
|
- POSTGRES_USER=postgres
|
||||||
- POSTGRES_PASSWORD=admin
|
- POSTGRES_PASSWORD=admin
|
||||||
- POSTGRES_DB=sumoc
|
- POSTGRES_DB=sumoc
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
ports:
|
ports:
|
||||||
- "5432:5432"
|
- "5432:5432"
|
||||||
restart: always
|
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"
|
||||||
|
|||||||
+20
-8
@@ -1,3 +1,6 @@
|
|||||||
|
volumes:
|
||||||
|
nominatim-data:
|
||||||
|
postgres_data:
|
||||||
|
|
||||||
services:
|
services:
|
||||||
backend:
|
backend:
|
||||||
@@ -13,17 +16,26 @@ services:
|
|||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
db:
|
db:
|
||||||
image: postgres:15
|
image: postgres:16.2-alpine
|
||||||
container_name: sumoc-postgres
|
container_name: sumoc_db
|
||||||
environment:
|
environment:
|
||||||
POSTGRES_DB: sumoc
|
- POSTGRES_USER=postgres
|
||||||
POSTGRES_USER: postgres
|
- POSTGRES_PASSWORD=admin
|
||||||
POSTGRES_PASSWORD: admin
|
- POSTGRES_DB=sumoc
|
||||||
volumes:
|
volumes:
|
||||||
- postgres_data:/var/lib/postgresql/data
|
- postgres_data:/var/lib/postgresql/data
|
||||||
ports:
|
ports:
|
||||||
- "5432:5432"
|
- "5432:5432"
|
||||||
restart: unless-stopped
|
restart: always
|
||||||
|
|
||||||
volumes:
|
nominatim:
|
||||||
postgres_data:
|
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,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
|
||||||
|
|
||||||
|
# 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!"
|
||||||
+642
@@ -0,0 +1,642 @@
|
|||||||
|
openapi: 3.1.0
|
||||||
|
info:
|
||||||
|
title: SuMoC API
|
||||||
|
description: API-Dokumentation für SuMoC
|
||||||
|
version: "1.0"
|
||||||
|
servers:
|
||||||
|
- url: http://localhost:8080
|
||||||
|
description: Generated server url
|
||||||
|
security:
|
||||||
|
- bearerAuth: []
|
||||||
|
paths:
|
||||||
|
/user/setVisibilityPrivacy:
|
||||||
|
put:
|
||||||
|
tags:
|
||||||
|
- user-controller
|
||||||
|
summary: Nutzer ändert seine Sichtbarkeits- und Datenschutzeinstellungen
|
||||||
|
description: "Ein Nutzer kann seine Sichtbarkeits- und Datenschutzeinstellungen\
|
||||||
|
\ ändern, um zu steuern, wer seine Informationen sehen kann."
|
||||||
|
operationId: setVisibilityPrivacy
|
||||||
|
parameters:
|
||||||
|
- name: visibilityPrivacy
|
||||||
|
in: query
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
enum:
|
||||||
|
- NONE
|
||||||
|
- FRIENDS_ONLY
|
||||||
|
- PUBLIC
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: Sichtbarkeits- und Datenschutzeinstellungen erfolgreich geändert
|
||||||
|
content:
|
||||||
|
application/json: {}
|
||||||
|
"400":
|
||||||
|
description: Ungültige Eingabedaten
|
||||||
|
content:
|
||||||
|
application/json: {}
|
||||||
|
/user/setPrivateName/{id}:
|
||||||
|
put:
|
||||||
|
tags:
|
||||||
|
- user-controller
|
||||||
|
summary: Update a users private name.
|
||||||
|
description: A user can change it's own private name that is shown to friends.
|
||||||
|
operationId: setPrivateName
|
||||||
|
parameters:
|
||||||
|
- name: id
|
||||||
|
in: path
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
- name: newPrivateName
|
||||||
|
in: query
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
/user/setPassword/{id}:
|
||||||
|
put:
|
||||||
|
tags:
|
||||||
|
- user-controller
|
||||||
|
summary: Nutzer ändert sein Passwort
|
||||||
|
description: "Ein Nutzer kann sein Passwort ändern, um die Sicherheit seines\
|
||||||
|
\ Kontos zu gewährleisten."
|
||||||
|
operationId: setPassword
|
||||||
|
parameters:
|
||||||
|
- name: id
|
||||||
|
in: path
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
- name: newPassword
|
||||||
|
in: query
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: Passwort erfolgreich geändert
|
||||||
|
content:
|
||||||
|
application/json: {}
|
||||||
|
"400":
|
||||||
|
description: Ungültige Eingabedaten
|
||||||
|
content:
|
||||||
|
application/json: {}
|
||||||
|
/user/setEmail/{id}:
|
||||||
|
put:
|
||||||
|
tags:
|
||||||
|
- user-controller
|
||||||
|
summary: Nutzer ändert seine E-Mail-Adresse
|
||||||
|
description: "Ein Nutzer kann seine E-Mail-Adresse ändern, um sicherzustellen,\
|
||||||
|
\ dass seine Kontaktdaten aktuell sind."
|
||||||
|
operationId: setEmail
|
||||||
|
parameters:
|
||||||
|
- name: id
|
||||||
|
in: path
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
- name: newEmail
|
||||||
|
in: query
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: E-Mail-Adresse erfolgreich geändert
|
||||||
|
content:
|
||||||
|
application/json: {}
|
||||||
|
"400":
|
||||||
|
description: Ungültige Eingabedaten
|
||||||
|
content:
|
||||||
|
application/json: {}
|
||||||
|
/trip/uploadTrip:
|
||||||
|
post:
|
||||||
|
tags:
|
||||||
|
- trip-controller
|
||||||
|
summary: User uploads a new trip from the App.
|
||||||
|
operationId: uploadTrip
|
||||||
|
requestBody:
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/NewTripDTO"
|
||||||
|
required: true
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
/routing/alternative/request:
|
||||||
|
post:
|
||||||
|
tags:
|
||||||
|
- routing-alternative-controller
|
||||||
|
operationId: requestAlternativeRoutes
|
||||||
|
requestBody:
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/RouteAlternativeRequestDTO"
|
||||||
|
required: true
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
content:
|
||||||
|
'*/*':
|
||||||
|
schema:
|
||||||
|
type: array
|
||||||
|
items:
|
||||||
|
$ref: "#/components/schemas/RouteAlternativeDTO"
|
||||||
|
/friendship/unblock/{friendId}:
|
||||||
|
post:
|
||||||
|
tags:
|
||||||
|
- friendship-controller
|
||||||
|
summary: Unblock a user.
|
||||||
|
description: Unblocks the user with friendId for the logged in user.
|
||||||
|
operationId: unblockUser
|
||||||
|
parameters:
|
||||||
|
- name: friendId
|
||||||
|
in: path
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
/friendship/request/{friendId}:
|
||||||
|
post:
|
||||||
|
tags:
|
||||||
|
- friendship-controller
|
||||||
|
summary: Request a friendship with another user.
|
||||||
|
description: Sends a friendship request to another user from the logged in user.
|
||||||
|
operationId: requestFriendship
|
||||||
|
parameters:
|
||||||
|
- name: friendId
|
||||||
|
in: path
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
/friendship/reject/{friendId}:
|
||||||
|
post:
|
||||||
|
tags:
|
||||||
|
- friendship-controller
|
||||||
|
summary: Reject a friendship request.
|
||||||
|
description: Rejects a pending friendship request for the logged in user from
|
||||||
|
user with friendId.
|
||||||
|
operationId: rejectFriendship
|
||||||
|
parameters:
|
||||||
|
- name: friendId
|
||||||
|
in: path
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
/friendship/block/{friendId}:
|
||||||
|
post:
|
||||||
|
tags:
|
||||||
|
- friendship-controller
|
||||||
|
summary: Block a user.
|
||||||
|
description: Blocks the user with friendId for the logged in user.
|
||||||
|
operationId: blockUser
|
||||||
|
parameters:
|
||||||
|
- name: friendId
|
||||||
|
in: path
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
/friendship/accept/{friendId}:
|
||||||
|
post:
|
||||||
|
tags:
|
||||||
|
- friendship-controller
|
||||||
|
summary: Accept a friendship request.
|
||||||
|
description: Accepts a pending friendship request for the logged in user from
|
||||||
|
user with friendId.
|
||||||
|
operationId: acceptFriendship
|
||||||
|
parameters:
|
||||||
|
- name: friendId
|
||||||
|
in: path
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
/auth/user/registration:
|
||||||
|
post:
|
||||||
|
tags:
|
||||||
|
- user-authentication-controller
|
||||||
|
summary: Registriert einen neuen Benutzer
|
||||||
|
description: Erstellt einen neuen Benutzer und gibt die Benutzerdaten zurück
|
||||||
|
operationId: registerUser
|
||||||
|
requestBody:
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/UserRegistrationDTO"
|
||||||
|
required: true
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: Benutzer erfolgreich registriert
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/LoginResponseDTO"
|
||||||
|
"400":
|
||||||
|
description: Ungültige Eingabedaten
|
||||||
|
content:
|
||||||
|
application/json: {}
|
||||||
|
/auth/user/login:
|
||||||
|
post:
|
||||||
|
tags:
|
||||||
|
- user-authentication-controller
|
||||||
|
summary: Authentifiziert einen Benutzer
|
||||||
|
description: Prüft den Benutzernamen und das Passwort und gibt ein JWT zurück
|
||||||
|
operationId: login
|
||||||
|
requestBody:
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/UserAuthenticationPairDTO"
|
||||||
|
required: true
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: Erfolgreiche Anmeldung
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/LoginResponseDTO"
|
||||||
|
"401":
|
||||||
|
description: Ungültiger Benutzername oder Passwort
|
||||||
|
content:
|
||||||
|
application/json: {}
|
||||||
|
/user/profile:
|
||||||
|
get:
|
||||||
|
tags:
|
||||||
|
- user-controller
|
||||||
|
summary: Nutzer fragt sein eigenes Profil an
|
||||||
|
description: "Ein Nutzer kann sein eigenes Profil anfragen, um dessen Informationen\
|
||||||
|
\ einzusehen."
|
||||||
|
operationId: getUser
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: Nutzerprofil erfolgreich abgerufen
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/MinimalUserDTO"
|
||||||
|
"404":
|
||||||
|
description: Nutzerprofil nicht gefunden
|
||||||
|
content:
|
||||||
|
application/json: {}
|
||||||
|
/user/profile/{id}:
|
||||||
|
get:
|
||||||
|
tags:
|
||||||
|
- user-controller
|
||||||
|
summary: Nutzer fragt ein fremdes Nutzerprofil an
|
||||||
|
description: "Ein Nutzer kann das Profil eines anderen Nutzers anfragen, um\
|
||||||
|
\ dessen öffentliche Informationen einzusehen."
|
||||||
|
operationId: getUser_1
|
||||||
|
parameters:
|
||||||
|
- name: id
|
||||||
|
in: path
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: Nutzerprofil erfolgreich abgerufen
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/MinimalUserDTO"
|
||||||
|
"404":
|
||||||
|
description: Nutzerprofil nicht gefunden
|
||||||
|
content:
|
||||||
|
application/json: {}
|
||||||
|
/trip/getAllUserTrips:
|
||||||
|
get:
|
||||||
|
tags:
|
||||||
|
- trip-controller
|
||||||
|
summary: Retrieve all trips of the authenticated user.
|
||||||
|
operationId: getAllUserTrips
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
content:
|
||||||
|
'*/*':
|
||||||
|
schema:
|
||||||
|
type: array
|
||||||
|
items:
|
||||||
|
$ref: "#/components/schemas/TripDTO"
|
||||||
|
/friendship/blocked:
|
||||||
|
get:
|
||||||
|
tags:
|
||||||
|
- friendship-controller
|
||||||
|
summary: Get all users the logged in user has blocked.
|
||||||
|
description: Returns a list of all users that have been blocked by the logged
|
||||||
|
in user.
|
||||||
|
operationId: blockedUsers
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
content:
|
||||||
|
'*/*':
|
||||||
|
schema:
|
||||||
|
type: array
|
||||||
|
items:
|
||||||
|
$ref: "#/components/schemas/MinimalUserDTO"
|
||||||
|
/friendship/all:
|
||||||
|
get:
|
||||||
|
tags:
|
||||||
|
- friendship-controller
|
||||||
|
summary: Return all friendships of the logged in user.
|
||||||
|
description: |2
|
||||||
|
Returns all friendships of all statuses (pending, accepted, rejected, blocked) for the logged in user.
|
||||||
|
A friendship between two users always consists of one or two entries in the database. One for each direction.
|
||||||
|
The user is always the one to whom the status applies.
|
||||||
|
- If A requests friendship from B, B -> A = PENDING, A -> B = REQUESTED
|
||||||
|
- If A accepts friendship from B, B -> A = ACCEPTED, A -> B = ACCEPTED
|
||||||
|
- If A rejects friendship from B, B -> A = REJECTED
|
||||||
|
- If A blocks B, B -> A = BLOCKED
|
||||||
|
Per friendship system logic the logged in user is to whom the statuses apply.
|
||||||
|
Meaning a blocked status indicates that the logged in user has been blocked by the other user.
|
||||||
|
operationId: getFriendships
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
content:
|
||||||
|
'*/*':
|
||||||
|
schema:
|
||||||
|
type: array
|
||||||
|
items:
|
||||||
|
$ref: "#/components/schemas/FriendshipDTO"
|
||||||
|
/friendship/accepted:
|
||||||
|
get:
|
||||||
|
tags:
|
||||||
|
- friendship-controller
|
||||||
|
summary: Return all accepted friends of the logged in user.
|
||||||
|
description: Returns all friends with accepted status.
|
||||||
|
operationId: getAcceptedFriendships
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
content:
|
||||||
|
'*/*':
|
||||||
|
schema:
|
||||||
|
type: array
|
||||||
|
items:
|
||||||
|
$ref: "#/components/schemas/FriendshipDTO"
|
||||||
|
/user/delete/{id}:
|
||||||
|
delete:
|
||||||
|
tags:
|
||||||
|
- user-controller
|
||||||
|
summary: Nutzer löscht sein eigenes Profil
|
||||||
|
description: Ein Nutzer kann sein eigenes Profil löschen. Dies entfernt alle
|
||||||
|
seine Daten aus dem System.
|
||||||
|
operationId: deleteUser
|
||||||
|
parameters:
|
||||||
|
- name: id
|
||||||
|
in: path
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: Nutzerprofil erfolgreich gelöscht
|
||||||
|
content:
|
||||||
|
application/json: {}
|
||||||
|
"404":
|
||||||
|
description: Nutzerprofil nicht gefunden
|
||||||
|
content:
|
||||||
|
application/json: {}
|
||||||
|
/friendship/unfriend/{friendId}:
|
||||||
|
delete:
|
||||||
|
tags:
|
||||||
|
- friendship-controller
|
||||||
|
summary: Unfriend a user.
|
||||||
|
description: Removes an accepted friendship between the logged in user and user
|
||||||
|
with friendId.
|
||||||
|
operationId: unfriend
|
||||||
|
parameters:
|
||||||
|
- name: friendId
|
||||||
|
in: path
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
components:
|
||||||
|
schemas:
|
||||||
|
NewTripDTO:
|
||||||
|
type: object
|
||||||
|
description: DTO for creating a new Trip
|
||||||
|
properties:
|
||||||
|
startPlace:
|
||||||
|
type: string
|
||||||
|
endPlace:
|
||||||
|
type: string
|
||||||
|
startTime:
|
||||||
|
type: string
|
||||||
|
format: date-time
|
||||||
|
endTime:
|
||||||
|
type: string
|
||||||
|
format: date-time
|
||||||
|
mobilityScore:
|
||||||
|
type: number
|
||||||
|
format: float
|
||||||
|
tripSegments:
|
||||||
|
type: array
|
||||||
|
items:
|
||||||
|
$ref: "#/components/schemas/NewTripSegmentDTO"
|
||||||
|
maxItems: 2147483647
|
||||||
|
minItems: 1
|
||||||
|
uniqueItems: true
|
||||||
|
required:
|
||||||
|
- tripSegments
|
||||||
|
NewTripSegmentDTO:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
modality:
|
||||||
|
type: string
|
||||||
|
enum:
|
||||||
|
- IDLE
|
||||||
|
- WALKING
|
||||||
|
- BIKE
|
||||||
|
- ESCOOTER
|
||||||
|
- BUS
|
||||||
|
- TRAM
|
||||||
|
- TRAIN
|
||||||
|
- CAR
|
||||||
|
startTime:
|
||||||
|
type: string
|
||||||
|
format: date-time
|
||||||
|
distanceMeters:
|
||||||
|
type: number
|
||||||
|
format: float
|
||||||
|
RouteAlternativeRequestDTO:
|
||||||
|
type: object
|
||||||
|
RouteAlternativeDTO:
|
||||||
|
type: object
|
||||||
|
UserRegistrationDTO:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
privateName:
|
||||||
|
type: string
|
||||||
|
publicName:
|
||||||
|
type: string
|
||||||
|
email:
|
||||||
|
type: string
|
||||||
|
password:
|
||||||
|
type: string
|
||||||
|
required:
|
||||||
|
- email
|
||||||
|
- password
|
||||||
|
- privateName
|
||||||
|
- publicName
|
||||||
|
LoginResponseDTO:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
userDTO:
|
||||||
|
$ref: "#/components/schemas/UserDTO"
|
||||||
|
jwt:
|
||||||
|
type: string
|
||||||
|
UserDTO:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
userId:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
privateName:
|
||||||
|
type: string
|
||||||
|
publicName:
|
||||||
|
type: string
|
||||||
|
roles:
|
||||||
|
type: array
|
||||||
|
items:
|
||||||
|
type: string
|
||||||
|
enum:
|
||||||
|
- USER
|
||||||
|
- ADMIN
|
||||||
|
uniqueItems: true
|
||||||
|
id:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
UserAuthenticationPairDTO:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
email:
|
||||||
|
type: string
|
||||||
|
password:
|
||||||
|
type: string
|
||||||
|
required:
|
||||||
|
- email
|
||||||
|
- password
|
||||||
|
MinimalUserDTO:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
id:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
displayName:
|
||||||
|
type: string
|
||||||
|
TripDTO:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
tripId:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
userId:
|
||||||
|
type: integer
|
||||||
|
format: int32
|
||||||
|
startPlace:
|
||||||
|
type: string
|
||||||
|
endPlace:
|
||||||
|
type: string
|
||||||
|
startTime:
|
||||||
|
type: string
|
||||||
|
format: date-time
|
||||||
|
endTime:
|
||||||
|
type: string
|
||||||
|
format: date-time
|
||||||
|
mobilityScore:
|
||||||
|
type: number
|
||||||
|
format: float
|
||||||
|
tripSegments:
|
||||||
|
type: array
|
||||||
|
items:
|
||||||
|
$ref: "#/components/schemas/TripSegmentDTO"
|
||||||
|
TripSegmentDTO:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
tripSegmentId:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
tripId:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
modality:
|
||||||
|
type: string
|
||||||
|
enum:
|
||||||
|
- IDLE
|
||||||
|
- WALKING
|
||||||
|
- BIKE
|
||||||
|
- ESCOOTER
|
||||||
|
- BUS
|
||||||
|
- TRAM
|
||||||
|
- TRAIN
|
||||||
|
- CAR
|
||||||
|
startTime:
|
||||||
|
type: string
|
||||||
|
format: date-time
|
||||||
|
distanceMeters:
|
||||||
|
type: number
|
||||||
|
format: float
|
||||||
|
FriendshipDTO:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
friendshipId:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
userId:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
friend:
|
||||||
|
$ref: "#/components/schemas/MinimalUserDTO"
|
||||||
|
status:
|
||||||
|
type: string
|
||||||
|
enum:
|
||||||
|
- REQUESTED
|
||||||
|
- PENDING
|
||||||
|
- ACCEPTED
|
||||||
|
- REJECTED
|
||||||
|
- BLOCKED
|
||||||
|
createdAt:
|
||||||
|
type: string
|
||||||
|
format: date-time
|
||||||
|
securitySchemes:
|
||||||
|
bearerAuth:
|
||||||
|
type: http
|
||||||
|
name: bearerAuth
|
||||||
|
scheme: bearer
|
||||||
|
bearerFormat: JWT
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"$schema": "./node_modules/@openapitools/openapi-generator-cli/config.schema.json",
|
||||||
|
"spaces": 2,
|
||||||
|
"generator-cli": {
|
||||||
|
"version": "7.14.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -87,8 +87,31 @@
|
|||||||
<artifactId>spring-security-test</artifactId>
|
<artifactId>spring-security-test</artifactId>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</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>
|
<dependency>
|
||||||
<groupId>org.mapstruct</groupId>
|
<groupId>org.mapstruct</groupId>
|
||||||
<artifactId>mapstruct</artifactId>
|
<artifactId>mapstruct</artifactId>
|
||||||
@@ -103,7 +126,25 @@
|
|||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||||
</dependency>
|
</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>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@@ -112,8 +153,6 @@
|
|||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
|
|
||||||
<!-- MapStruct Annotation Processor einbinden -->
|
<!-- MapStruct Annotation Processor einbinden -->
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
@@ -123,27 +162,67 @@
|
|||||||
<source>21</source>
|
<source>21</source>
|
||||||
<target>21</target>
|
<target>21</target>
|
||||||
<annotationProcessorPaths>
|
<annotationProcessorPaths>
|
||||||
|
<path>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
<version>1.18.32</version>
|
||||||
|
</path>
|
||||||
<path>
|
<path>
|
||||||
<groupId>org.mapstruct</groupId>
|
<groupId>org.mapstruct</groupId>
|
||||||
<artifactId>mapstruct-processor</artifactId>
|
<artifactId>mapstruct-processor</artifactId>
|
||||||
<version>1.5.5.Final</version>
|
<version>1.6.3</version>
|
||||||
</path>
|
</path>
|
||||||
<path>
|
<path>
|
||||||
<groupId>org.projectlombok</groupId>
|
<groupId>org.projectlombok</groupId>
|
||||||
<artifactId>lombok</artifactId>
|
<artifactId>lombok-mapstruct-binding</artifactId>
|
||||||
<version>1.18.30</version>
|
<version>0.2.0</version>
|
||||||
</path>
|
</path>
|
||||||
</annotationProcessorPaths>
|
</annotationProcessorPaths>
|
||||||
<!--<compilerArgs>- -enable-preview</compilerArgs> -->
|
<!--<compilerArgs>- -enable-preview</compilerArgs> -->
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.openapitools</groupId>
|
<groupId>org.openapitools</groupId>
|
||||||
<artifactId>openapi-generator-maven-plugin</artifactId>
|
<artifactId>openapi-generator-maven-plugin</artifactId>
|
||||||
<version>7.8.0</version>
|
<version>7.18.0</version>
|
||||||
<executions>
|
<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>
|
<execution>
|
||||||
<id>generate-android-client</id>
|
<id>generate-android-client</id>
|
||||||
<phase>none</phase>
|
<phase>none</phase>
|
||||||
@@ -156,7 +235,6 @@
|
|||||||
<output>${project.basedir}/generated/android</output>
|
<output>${project.basedir}/generated/android</output>
|
||||||
</configuration>
|
</configuration>
|
||||||
</execution>
|
</execution>
|
||||||
|
|
||||||
<execution>
|
<execution>
|
||||||
<id>generate-ios-client</id>
|
<id>generate-ios-client</id>
|
||||||
<phase>none</phase>
|
<phase>none</phase>
|
||||||
@@ -182,6 +260,28 @@
|
|||||||
</activation>
|
</activation>
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<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>
|
<plugin>
|
||||||
<groupId>org.openapitools</groupId>
|
<groupId>org.openapitools</groupId>
|
||||||
<artifactId>openapi-generator-maven-plugin</artifactId>
|
<artifactId>openapi-generator-maven-plugin</artifactId>
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ package SuMoC.backend;
|
|||||||
|
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
|
@EnableScheduling
|
||||||
public class BackendApplication {
|
public class BackendApplication {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
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,86 @@
|
|||||||
|
package SuMoC.backend.dev;
|
||||||
|
|
||||||
|
import SuMoC.backend.meteo.ForecastService;
|
||||||
|
import SuMoC.backend.meteo.MeteoClient;
|
||||||
|
import SuMoC.backend.scheduling.ScheduledTasks;
|
||||||
|
import SuMoC.backend.trend.services.StatTableUpdateService;
|
||||||
|
import com.google.firebase.messaging.FirebaseMessaging;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.context.annotation.Profile;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/dev")
|
||||||
|
@Profile("dev")
|
||||||
|
public class DevController {
|
||||||
|
|
||||||
|
private final ScheduledTasks scheduledTasks;
|
||||||
|
private final StatTableUpdateService statTableUpdateService;
|
||||||
|
private final FirebaseMessaging firebaseMessaging;
|
||||||
|
private final MeteoClient meteoClient;
|
||||||
|
private final ForecastService forecastService;
|
||||||
|
|
||||||
|
public DevController(
|
||||||
|
ScheduledTasks scheduledTasks,
|
||||||
|
StatTableUpdateService statTableUpdateService,
|
||||||
|
@Autowired(required = false) FirebaseMessaging firebaseMessaging,
|
||||||
|
MeteoClient meteoClient,
|
||||||
|
ForecastService forecastService) {
|
||||||
|
this.scheduledTasks = scheduledTasks;
|
||||||
|
this.statTableUpdateService = statTableUpdateService;
|
||||||
|
this.firebaseMessaging = firebaseMessaging;
|
||||||
|
this.meteoClient = meteoClient;
|
||||||
|
this.forecastService = forecastService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/trigger-trend-calculation")
|
||||||
|
public void triggerTrendCalculation() {
|
||||||
|
LocalDate dayOfLastWeek = LocalDate.now().minusDays(7);
|
||||||
|
LocalDate day2WeeksAgo = LocalDate.now().minusDays(14);
|
||||||
|
LocalDate day3WeeksAgo = LocalDate.now().minusDays(21);
|
||||||
|
statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(dayOfLastWeek);
|
||||||
|
statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(day2WeeksAgo);
|
||||||
|
statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(day3WeeksAgo);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/test-firebase")
|
||||||
|
public ResponseEntity<String> testFirebaseConnection() {
|
||||||
|
if (firebaseMessaging == null) {
|
||||||
|
return ResponseEntity.status(503)
|
||||||
|
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
// Send to a topic (no device registration needed)
|
||||||
|
String message = firebaseMessaging.sendAsync(
|
||||||
|
com.google.firebase.messaging.Message.builder()
|
||||||
|
.setTopic("test-topic")
|
||||||
|
.putData("test", "connection-check")
|
||||||
|
.build()
|
||||||
|
).get();
|
||||||
|
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/test-meteo")
|
||||||
|
public void testMeteoClient() {
|
||||||
|
try {
|
||||||
|
// Test with Zurich coordinates
|
||||||
|
double lat = 51.44378662109375;
|
||||||
|
double lon = 7.007565975189209;
|
||||||
|
|
||||||
|
var forecast = forecastService.getTodayYesterdayForecast(
|
||||||
|
lat,
|
||||||
|
lon);
|
||||||
|
} catch (Exception e) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package SuMoC.backend.firebase;
|
||||||
|
|
||||||
|
import com.google.auth.oauth2.GoogleCredentials;
|
||||||
|
import com.google.firebase.FirebaseApp;
|
||||||
|
import com.google.firebase.FirebaseOptions;
|
||||||
|
import com.google.firebase.messaging.FirebaseMessaging;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableConfigurationProperties(FirebaseProperties.class)
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@ConditionalOnProperty(prefix = "firebase.config", name = "enabled", havingValue = "true", matchIfMissing = false)
|
||||||
|
public class FirebaseConfiguration {
|
||||||
|
|
||||||
|
private final FirebaseProperties firebaseProperties;
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
FirebaseMessaging firebaseMessaging(FirebaseApp firebaseApp) {
|
||||||
|
return FirebaseMessaging.getInstance(firebaseApp);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
FirebaseApp firebaseApp(GoogleCredentials credentials) {
|
||||||
|
FirebaseOptions options = FirebaseOptions.builder()
|
||||||
|
.setCredentials(credentials)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
return FirebaseApp.initializeApp(options);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
GoogleCredentials googleCredentials(FirebaseProperties firebaseProperties) throws IOException {
|
||||||
|
if (firebaseProperties.serviceAccount() != null) {
|
||||||
|
try (InputStream is = firebaseProperties.serviceAccount().getInputStream()) {
|
||||||
|
return GoogleCredentials.fromStream(is);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Use standard credentials chain. Useful when running inside GKE
|
||||||
|
return GoogleCredentials.getApplicationDefault();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package SuMoC.backend.firebase;
|
||||||
|
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.core.io.Resource;
|
||||||
|
|
||||||
|
@ConfigurationProperties(prefix = "firebase.config")
|
||||||
|
public record FirebaseProperties(
|
||||||
|
Boolean enabled,
|
||||||
|
Resource serviceAccount
|
||||||
|
) {
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,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,91 @@
|
|||||||
|
package SuMoC.backend.gamification.badges;
|
||||||
|
|
||||||
|
import SuMoC.backend.gamification.badges.models.Badge;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||||
|
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||||
|
import jakarta.annotation.security.RolesAllowed;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@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"),
|
||||||
|
@ApiResponse(responseCode = "400", description = "Invalid input data"),
|
||||||
|
@ApiResponse(responseCode = "409", description = "Badge already exists")
|
||||||
|
})
|
||||||
|
@PostMapping("/createBadge")
|
||||||
|
public ResponseEntity<Badge> createBadge(@RequestBody @Valid Badge badge) {
|
||||||
|
Badge createdBadge = badgeService.createBadge(badge);
|
||||||
|
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"),
|
||||||
|
@ApiResponse(responseCode = "404", description = "Badge not found"),
|
||||||
|
@ApiResponse(responseCode = "400", description = "Invalid input data")
|
||||||
|
})
|
||||||
|
@PutMapping("/modifyBadge")
|
||||||
|
public ResponseEntity<Badge> modifyBadgeById(
|
||||||
|
@RequestBody @Valid Badge badge) {
|
||||||
|
Badge modifiedBadge = badgeService.modifyBadge(badge);
|
||||||
|
return ResponseEntity.status(HttpStatus.OK).body(modifiedBadge);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Operation(summary = "Get a badge by ID")
|
||||||
|
@ApiResponses(value = {
|
||||||
|
@ApiResponse(responseCode = "200", description = "Badge retrieved successfully"),
|
||||||
|
@ApiResponse(responseCode = "404", description = "Badge not found")
|
||||||
|
})
|
||||||
|
@GetMapping("/getBadge/{badgeId}")
|
||||||
|
public ResponseEntity<Badge> getBadgeById(@PathVariable Long badgeId) {
|
||||||
|
Badge badge = badgeService.getBadgeById(badgeId);
|
||||||
|
return ResponseEntity.status(HttpStatus.OK).body(badge);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@Operation(summary = "Get all badges")
|
||||||
|
@ApiResponses(value = {
|
||||||
|
@ApiResponse(responseCode = "200", description = "Badges retrieved successfully"),
|
||||||
|
@ApiResponse(responseCode = "404", description = "No badges found")
|
||||||
|
})
|
||||||
|
@GetMapping("/getAllBadges")
|
||||||
|
public ResponseEntity<List<Badge>> getAllBadges(){
|
||||||
|
List<Badge> badges = badgeService.getAllBadges();
|
||||||
|
return ResponseEntity.status(HttpStatus.OK).body(badges);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,121 @@
|
|||||||
|
package SuMoC.backend.gamification.badges;
|
||||||
|
|
||||||
|
import SuMoC.backend.gamification.Timeframe;
|
||||||
|
import SuMoC.backend.gamification.badges.models.Badge;
|
||||||
|
import SuMoC.backend.gamification.badges.models.UserBadge;
|
||||||
|
import SuMoC.backend.gamification.badges.models.UserBadgeDTO;
|
||||||
|
import SuMoC.backend.user.models.User;
|
||||||
|
import SuMoC.backend.user.service.CurrentUserService;
|
||||||
|
import SuMoC.backend.user.service.PrivacyService;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import 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 Badge createBadge(Badge badge) {
|
||||||
|
badgeRepository.findByName(badge.getName())
|
||||||
|
.ifPresent(b -> {
|
||||||
|
throw new ResponseStatusException(HttpStatus.CONFLICT, "Badge existiert bereits");
|
||||||
|
});
|
||||||
|
return badgeRepository.save(badge);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public void checkAndAwardBadges(User user) {
|
||||||
|
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 Badge modifyBadge(Badge modifiedBadge) {
|
||||||
|
Badge badge = badgeRepository.findById(modifiedBadge.getId())
|
||||||
|
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Badge nicht gefunden"));
|
||||||
|
|
||||||
|
badge.setName(modifiedBadge.getName());
|
||||||
|
badge.setDescription(modifiedBadge.getDescription());
|
||||||
|
badge.setCriteria(modifiedBadge.getCriteria());
|
||||||
|
|
||||||
|
return badgeRepository.save(badge);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void deleteBadge(Long id) {
|
||||||
|
Badge badge = badgeRepository.findById(id)
|
||||||
|
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Badge nicht gefunden"));
|
||||||
|
badgeRepository.delete(badge);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Badge getBadgeById(Long badgeId) {
|
||||||
|
return badgeRepository.findById(badgeId)
|
||||||
|
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Badge nicht gefunden"));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public List<Badge> getAllBadges() {
|
||||||
|
return badgeRepository.findAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
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,36 @@
|
|||||||
|
package SuMoC.backend.gamification.badges;
|
||||||
|
|
||||||
|
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.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.setCriteria(badge.getCriteria());
|
||||||
|
dto.setAwardedAt(userBadge.getAwardedAt());
|
||||||
|
|
||||||
|
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,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,62 @@
|
|||||||
|
package SuMoC.backend.gamification.badges.models;
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
@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<>();
|
||||||
|
|
||||||
|
// Constructor
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Badge without criteria - if the Badge shouldn't be reachable by now
|
||||||
|
* @param name name of the badge
|
||||||
|
* @param description a short description
|
||||||
|
*/
|
||||||
|
public Badge(String name, String description) {
|
||||||
|
this.name = name;
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Badge with criteria
|
||||||
|
* @param name name of the badge
|
||||||
|
* @param description a short description
|
||||||
|
* @param criteria criteria Mapping StatField-Long
|
||||||
|
*/
|
||||||
|
public Badge(String name, String description, Map<String, Integer> criteria) {
|
||||||
|
this.name = name;
|
||||||
|
this.description = description;
|
||||||
|
this.criteria = criteria;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 Map<String, Integer> getCriteria() { return criteria; }
|
||||||
|
public void setCriteria(Map<String, Integer> criteria) { this.criteria = criteria; }
|
||||||
|
}
|
||||||
@@ -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,56 @@
|
|||||||
|
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 Map<String, Integer> criteria;
|
||||||
|
private LocalDateTime awardedAt;
|
||||||
|
|
||||||
|
// 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 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package SuMoC.backend.gamification.scoretable;
|
||||||
|
|
||||||
|
import SuMoC.backend.gamification.scoretable.models.Leaderboard;
|
||||||
|
import SuMoC.backend.gamification.Timeframe;
|
||||||
|
import SuMoC.backend.user.models.User;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||||
|
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/leaderboard")
|
||||||
|
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"),
|
||||||
|
@ApiResponse(responseCode = "400", description = "Bad request")
|
||||||
|
|
||||||
|
})
|
||||||
|
@GetMapping("/getLeaderboard")
|
||||||
|
public ResponseEntity<Leaderboard> getLeaderboard(@AuthenticationPrincipal User user,
|
||||||
|
@RequestParam Timeframe timeframe,
|
||||||
|
@RequestParam String field) {
|
||||||
|
Leaderboard leaderboard = this.leaderboardService.getLeaderboard(user, timeframe, field);
|
||||||
|
return ResponseEntity.status(HttpStatus.OK).body(leaderboard);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "Get the friend score table")
|
||||||
|
@ApiResponses(value = {
|
||||||
|
@ApiResponse(responseCode = "200", description = "Successfully retrieved friend score table"),
|
||||||
|
@ApiResponse(responseCode = "400", description = "Bad request")
|
||||||
|
})
|
||||||
|
@GetMapping("/getFriendLeaderboard")
|
||||||
|
public ResponseEntity<Leaderboard> getFriendLeaderboard(@AuthenticationPrincipal User user,
|
||||||
|
@RequestParam Timeframe timeframe,
|
||||||
|
@RequestParam String field) {
|
||||||
|
Leaderboard leaderboard = this.leaderboardService.getFriendLeaderboard(user, timeframe, field);
|
||||||
|
return ResponseEntity.status(HttpStatus.OK).body(leaderboard);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
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.user.models.User;
|
||||||
|
import SuMoC.backend.user.service.FriendshipService;
|
||||||
|
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;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class LeaderboardService {
|
||||||
|
private final FriendshipService friendshipService;
|
||||||
|
private final StatsListRepository statsListRepository;
|
||||||
|
|
||||||
|
public LeaderboardService(
|
||||||
|
FriendshipService friendshipService,
|
||||||
|
StatsListRepository statsListRepository
|
||||||
|
) {
|
||||||
|
|
||||||
|
this.friendshipService = friendshipService;
|
||||||
|
this.statsListRepository = statsListRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Method Overload to get the score table with a default limit of 30.
|
||||||
|
* @param user
|
||||||
|
* @param timeframe
|
||||||
|
* @param field
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public Leaderboard getLeaderboard(User user, Timeframe timeframe, String field) {
|
||||||
|
return getLeaderboard(user, timeframe, field, 30);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the global score table for a given user, timeframe, score type, and limit.
|
||||||
|
* @param user
|
||||||
|
* @param timeframe
|
||||||
|
* @param field
|
||||||
|
* @param limit
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public Leaderboard getLeaderboard(User user, Timeframe timeframe, String field, int limit) {
|
||||||
|
List<StatsList> topStats = getTopStats(timeframe, field, limit);
|
||||||
|
|
||||||
|
List<Long> topUserIds = topStats.stream()
|
||||||
|
.map(stats -> stats.getUser().getId())
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
Map<Long, FriendshipService.NameWithFriendship> nameMap =
|
||||||
|
friendshipService.getPrivateNameIfFriendshipAccepted(user, topUserIds)
|
||||||
|
.stream()
|
||||||
|
.collect(Collectors.toMap(FriendshipService.NameWithFriendship::id, n -> n));
|
||||||
|
|
||||||
|
Leaderboard leaderboard = new Leaderboard();
|
||||||
|
leaderboard.setEntries(new ArrayList<>());
|
||||||
|
|
||||||
|
for (StatsList statsList : topStats) {
|
||||||
|
User topUser = statsList.getUser();
|
||||||
|
FriendshipService.NameWithFriendship nwf = nameMap.get(topUser.getId());
|
||||||
|
|
||||||
|
String displayName = (nwf != null) ? nwf.name() : topUser.getPublicName();
|
||||||
|
boolean friendship = (nwf != null) && nwf.friendship();
|
||||||
|
|
||||||
|
LeaderboardEntry entry = new LeaderboardEntry(
|
||||||
|
topUser.getId(),
|
||||||
|
displayName,
|
||||||
|
friendship,
|
||||||
|
statsList.getStatValue(timeframe, field)
|
||||||
|
);
|
||||||
|
|
||||||
|
leaderboard.getEntries().add(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (leaderboard.getEntries().stream().noneMatch(e -> e.getUserId().equals(user.getId()))) {
|
||||||
|
LeaderboardEntry userEntry = new LeaderboardEntry(
|
||||||
|
user.getId(),
|
||||||
|
user.getPrivateName(),
|
||||||
|
true,
|
||||||
|
user.getStats().getStatValue(timeframe, field)
|
||||||
|
);
|
||||||
|
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 user
|
||||||
|
* @param timeframe
|
||||||
|
* @param field
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public Leaderboard getFriendLeaderboard(User user, Timeframe timeframe, String field) {
|
||||||
|
return getFriendLeaderboard(user, timeframe, field, 30);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the friend score table for a given user, timeframe, score type, and limit.
|
||||||
|
* @param user
|
||||||
|
* @param timeframe
|
||||||
|
* @param field
|
||||||
|
* @param limit
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public Leaderboard getFriendLeaderboard(User user, Timeframe timeframe, String field, int limit) {
|
||||||
|
List<User> friends = friendshipService.getAcceptedFriends(user);
|
||||||
|
|
||||||
|
Leaderboard leaderboard = new Leaderboard();
|
||||||
|
leaderboard.setEntries(new ArrayList<>()); // Initialize list
|
||||||
|
|
||||||
|
for (User friend : friends) {
|
||||||
|
StatsList statsList = friend.getStats();
|
||||||
|
if (statsList != null) {
|
||||||
|
Long statValue = statsList.getStatValue(timeframe, field);
|
||||||
|
if (statValue != null) {
|
||||||
|
LeaderboardEntry entry = new LeaderboardEntry(
|
||||||
|
friend.getId(),
|
||||||
|
friend.getPrivateName(),
|
||||||
|
true,
|
||||||
|
statValue
|
||||||
|
);
|
||||||
|
leaderboard.getEntries().add(entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (leaderboard.getEntries().stream().noneMatch(e -> e.getUserId().equals(user.getId()))) {
|
||||||
|
leaderboard.getEntries().add(new LeaderboardEntry(
|
||||||
|
user.getId(),
|
||||||
|
user.getPrivateName(),
|
||||||
|
true,
|
||||||
|
user.getStats().getStatValue(timeframe, field)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
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,30 @@
|
|||||||
|
package SuMoC.backend.gamification.scoretable.models;
|
||||||
|
|
||||||
|
public class LeaderboardEntry {
|
||||||
|
private Long userId;
|
||||||
|
private String username;
|
||||||
|
private Boolean isFriend;
|
||||||
|
private Long score;
|
||||||
|
|
||||||
|
public LeaderboardEntry(Long userId, String username, Boolean isFriend, Long score) {
|
||||||
|
this.userId = userId;
|
||||||
|
this.username = username;
|
||||||
|
this.isFriend = isFriend;
|
||||||
|
this.score = score;
|
||||||
|
}
|
||||||
|
|
||||||
|
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; }
|
||||||
|
}
|
||||||
@@ -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,37 @@
|
|||||||
|
package SuMoC.backend.geocoding;
|
||||||
|
|
||||||
|
import SuMoC.backend.nominatim.NominatimClient;
|
||||||
|
import SuMoC.backend.nominatim.ReverseResponse;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class GeoCodingService {
|
||||||
|
|
||||||
|
private final NominatimClient nominatimClient;
|
||||||
|
|
||||||
|
public GeoCodingService(NominatimClient nominatimClient) {
|
||||||
|
this.nominatimClient = nominatimClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Mono<AddressDTO> getAddress(double lat, double lon) {
|
||||||
|
return nominatimClient.reverse(lat, lon)
|
||||||
|
.map(this::mapToAddressDTO);
|
||||||
|
}
|
||||||
|
|
||||||
|
private AddressDTO mapToAddressDTO(ReverseResponse response) {
|
||||||
|
var addressMap = response.address();
|
||||||
|
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,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,31 @@
|
|||||||
|
package SuMoC.backend.h3;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@ConfigurationProperties(prefix = "h3")
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
public class H3Configuration {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* H3 resolution for route pattern detection.
|
||||||
|
* Typically slightly lower resolution for broader matching.
|
||||||
|
*/
|
||||||
|
private int routePatternResolution = 10;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Number of hexagonal rings to include when matching route patterns.
|
||||||
|
* K-ring depth where k=1 includes immediate neighbors (6 hexagons),
|
||||||
|
* k=2 includes two rings (18 hexagons), etc.
|
||||||
|
* Higher values allow fuzzier location matching but may incorrectly
|
||||||
|
* group distinct locations.
|
||||||
|
* Consider resolution when setting.
|
||||||
|
* Default: 1 (immediate neighbors only)
|
||||||
|
*/
|
||||||
|
private int routePatternNeighborRings = 1;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package SuMoC.backend.h3;
|
||||||
|
|
||||||
|
import com.uber.h3core.H3Core;
|
||||||
|
import com.uber.h3core.util.LatLng;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Service for H3 spatial indexing operations.
|
||||||
|
* H3 is a hierarchical hexagonal geospatial indexing system.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class H3Service {
|
||||||
|
|
||||||
|
private final H3Core h3;
|
||||||
|
private final H3Configuration config;
|
||||||
|
|
||||||
|
public H3Service(H3Configuration config) {
|
||||||
|
this.config = config;
|
||||||
|
try {
|
||||||
|
this.h3 = H3Core.newInstance();
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException("Failed to initialize H3Core", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert latitude/longitude to H3 cell ID with specific resolution.
|
||||||
|
*
|
||||||
|
* @param latitude Latitude in degrees
|
||||||
|
* @param longitude Longitude in degrees
|
||||||
|
* @param resolution H3 resolution (0-15, higher = more precise)
|
||||||
|
* @return H3 cell ID as hex string
|
||||||
|
*/
|
||||||
|
public String latLngToCell(double latitude, double longitude, int resolution) {
|
||||||
|
return h3.latLngToCellAddress(latitude, longitude, resolution);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert latitude/longitude to H3 cell ID using route pattern resolution.
|
||||||
|
* This is typically used for detecting regular trip patterns.
|
||||||
|
*
|
||||||
|
* @param latitude Latitude in degrees
|
||||||
|
* @param longitude Longitude in degrees
|
||||||
|
* @return H3 cell ID as hex string
|
||||||
|
*/
|
||||||
|
public String latLngToCellForRoute(double latitude, double longitude) {
|
||||||
|
return latLngToCell(latitude, longitude, config.getRoutePatternResolution());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert H3 cell ID to center latitude/longitude.
|
||||||
|
*
|
||||||
|
* @param cellId H3 cell ID as hex string
|
||||||
|
* @return LatLng of cell center
|
||||||
|
*/
|
||||||
|
public LatLng cellToLatLng(String cellId) {
|
||||||
|
return h3.cellToLatLng(cellId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all cells within k distance of the given cell (excluding the cell it self).
|
||||||
|
* K-ring distance means cells reachable in k steps on the hexagonal grid.
|
||||||
|
*
|
||||||
|
* @param cellId H3 cell ID as hex string
|
||||||
|
* @param k Distance (number of rings, 0 = only the cell itself)
|
||||||
|
* @return List of H3 cell IDs including the origin cell
|
||||||
|
*/
|
||||||
|
public List<String> getKRingNeighbors(String cellId, int k) {
|
||||||
|
return h3.gridRing(cellId, k);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get K-ring neighbors using the configured route pattern resolution distance.
|
||||||
|
* Ring means the center cell is not included.
|
||||||
|
* Useful for finding nearby locations when matching trip patterns.
|
||||||
|
*
|
||||||
|
* @param cellId H3 cell ID as hex string
|
||||||
|
* @return List of H3 cell IDs within configured neighbor distance
|
||||||
|
*/
|
||||||
|
public List<String> getRoutePatternNeighbors(String cellId) {
|
||||||
|
return getKRingNeighbors(cellId, config.getRoutePatternNeighborRings());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package SuMoC.backend.meteo;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public record ForecastResponse(
|
||||||
|
double latitude,
|
||||||
|
double longitude,
|
||||||
|
@JsonProperty("generationtime_ms") double generationtimeMs,
|
||||||
|
@JsonProperty("utc_offset_seconds") int utcOffsetSeconds,
|
||||||
|
String timezone,
|
||||||
|
@JsonProperty("timezone_abbreviation") String timezoneAbbreviation,
|
||||||
|
double elevation,
|
||||||
|
@JsonProperty("hourly_units") HourlyUnits hourlyUnits,
|
||||||
|
Hourly hourly
|
||||||
|
) {
|
||||||
|
private static int findIndex(ForecastResponse forecast, LocalDateTime target) {
|
||||||
|
int index = -1;
|
||||||
|
for (int i = 0; i < forecast.hourly().time().size(); i++) {
|
||||||
|
LocalDateTime entry = forecast.hourly().time().get(i);
|
||||||
|
if (entry.toLocalDate().equals(target.toLocalDate()) && entry.getHour() == target.getHour()) {
|
||||||
|
index = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (index == -1) throw new RuntimeException("Start or end not found in list received from meteo.");
|
||||||
|
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the weather code for a specific point in time.
|
||||||
|
*
|
||||||
|
* @param dateTime the target date and time
|
||||||
|
* @return the weather code if found, empty otherwise
|
||||||
|
*/
|
||||||
|
public Optional<Integer> getWeatherCodeAt(LocalDateTime dateTime) {
|
||||||
|
if (hourly == null || hourly.time == null || hourly.weatherCode == null) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < hourly.time.size(); i++) {
|
||||||
|
if (hourly.time.get(i).equals(dateTime)) {
|
||||||
|
return Optional.of(hourly.weatherCode.get(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<WeatherCondition> getWeatherConditionsBetween(
|
||||||
|
Instant start,
|
||||||
|
Instant end
|
||||||
|
) throws Exception {
|
||||||
|
LocalDateTime startDateTime = start.atZone(ZoneId.systemDefault()).toLocalDateTime();
|
||||||
|
LocalDateTime endDateTime = end.atZone(ZoneId.systemDefault()).toLocalDateTime();
|
||||||
|
if (start.isAfter(end)) {
|
||||||
|
throw new IllegalArgumentException("Start must be before end");
|
||||||
|
}
|
||||||
|
|
||||||
|
int startIndex = findIndex(this, startDateTime);
|
||||||
|
int endIndex = findIndex(this, endDateTime);
|
||||||
|
|
||||||
|
var results = new ArrayList<WeatherCondition>();
|
||||||
|
for (int i = startIndex; i <= endIndex; i++)
|
||||||
|
results.add(WeatherCondition.from(this.hourly().weatherCode().get(i)));
|
||||||
|
return results;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public record HourlyUnits(
|
||||||
|
String time,
|
||||||
|
@JsonProperty("weather_code") String weatherCode
|
||||||
|
) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record Hourly(
|
||||||
|
List<LocalDateTime> time,
|
||||||
|
@JsonProperty("weather_code") List<Integer> weatherCode
|
||||||
|
) {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package SuMoC.backend.meteo;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class ForecastService {
|
||||||
|
|
||||||
|
private final MeteoClient meteoClient;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns forecast for today and yesterday.
|
||||||
|
*/
|
||||||
|
public ForecastResponse getTodayYesterdayForecast(
|
||||||
|
double latitude,
|
||||||
|
double longitude) {
|
||||||
|
return meteoClient.getForecastWeatherCodeTodayYesterday(latitude, longitude).block();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package SuMoC.backend.meteo;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class MeteoClient {
|
||||||
|
|
||||||
|
private final WebClient meteoClient;
|
||||||
|
|
||||||
|
public MeteoClient(@Qualifier("meteoWebClient") WebClient meteoClient) {
|
||||||
|
this.meteoClient = meteoClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Simple wrapper around meteo's forecast API.
|
||||||
|
* https://open-meteo.com/en/docs
|
||||||
|
*/
|
||||||
|
public Mono<ForecastResponse> getForecastWeatherCodeTodayYesterday(
|
||||||
|
double lat,
|
||||||
|
double lon
|
||||||
|
) {
|
||||||
|
String today = LocalDate.now().toString(); // Uses ISO-8601 format: yyyy-MM-dd
|
||||||
|
// We include yesterday for cases where routes cross midnight
|
||||||
|
String yesterday = LocalDate.now().minusDays(1).toString();
|
||||||
|
|
||||||
|
return meteoClient.get()
|
||||||
|
.uri(uriBuilder -> uriBuilder.path("/forecast")
|
||||||
|
.queryParam("latitude", lat)
|
||||||
|
.queryParam("longitude", lon)
|
||||||
|
.queryParam("hourly", "weather_code")
|
||||||
|
.queryParam("start_date", yesterday)
|
||||||
|
.queryParam("end_date", today)
|
||||||
|
.build())
|
||||||
|
.retrieve()
|
||||||
|
.bodyToMono(ForecastResponse.class);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package SuMoC.backend.meteo;
|
||||||
|
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableConfigurationProperties(MeteoProperties.class)
|
||||||
|
public class MeteoClientConfig {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public WebClient meteoWebClient(MeteoProperties properties) {
|
||||||
|
return WebClient.builder()
|
||||||
|
.baseUrl(properties.baseUrl())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package SuMoC.backend.meteo;
|
||||||
|
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
|
||||||
|
@ConfigurationProperties(prefix = "meteo")
|
||||||
|
public record MeteoProperties(
|
||||||
|
String baseUrl
|
||||||
|
) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
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,27 @@
|
|||||||
|
package SuMoC.backend.nominatim;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class NominatimClient {
|
||||||
|
|
||||||
|
private final WebClient nominatimClient;
|
||||||
|
|
||||||
|
public NominatimClient(@Qualifier("nominatimWebClient") WebClient nominatimClient) {
|
||||||
|
this.nominatimClient = nominatimClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Mono<ReverseResponse> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package SuMoC.backend.nominatim;
|
||||||
|
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableConfigurationProperties(NominatimProperties.class)
|
||||||
|
public class NominatimClientConfig {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public WebClient nominatimWebClient(NominatimProperties properties) {
|
||||||
|
return WebClient.builder()
|
||||||
|
.baseUrl(properties.baseUrl())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package SuMoC.backend.nominatim;
|
||||||
|
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
|
||||||
|
@ConfigurationProperties(prefix = "nominatim")
|
||||||
|
public record NominatimProperties(
|
||||||
|
String baseUrl
|
||||||
|
) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package SuMoC.backend.nominatim;
|
||||||
|
|
||||||
|
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,7 @@
|
|||||||
|
package SuMoC.backend.notification.enums;
|
||||||
|
|
||||||
|
public enum NotificationStatus {
|
||||||
|
PENDING,
|
||||||
|
SENT,
|
||||||
|
FAILED
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package SuMoC.backend.notification.factories;
|
||||||
|
|
||||||
|
import SuMoC.backend.notification.models.Notification;
|
||||||
|
import SuMoC.backend.trend.TrendDetection;
|
||||||
|
import SuMoC.backend.trend.services.TrendMessageGenerator;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class TrendNotificationFactory {
|
||||||
|
|
||||||
|
private final TrendMessageGenerator trendMessageGenerator;
|
||||||
|
|
||||||
|
public Notification createNotification(TrendDetection trend) {
|
||||||
|
return Notification.builder()
|
||||||
|
.user(trend.getUser())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
package SuMoC.backend.notification.interfaces;
|
||||||
|
|
||||||
|
public interface NotificationPublisher {
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
package SuMoC.backend.notification.interfaces;
|
||||||
|
|
||||||
|
public interface NotificationSender {
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package SuMoC.backend.notification.models;
|
||||||
|
|
||||||
|
import SuMoC.backend.notification.enums.NotificationStatus;
|
||||||
|
import SuMoC.backend.user.models.User;
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.*;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.LocalTime;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "notifications")
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class Notification {
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@ManyToOne
|
||||||
|
@JoinColumn(name = "user_id", nullable = false)
|
||||||
|
private User user;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private String message;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Time of day from which on a notification might be sent.
|
||||||
|
* Useful since we might want to send messages about specific trips immediately but not inform about trend changes
|
||||||
|
* etc. in the middle of night when calculating jobs might run.
|
||||||
|
*/
|
||||||
|
@Column(nullable = false)
|
||||||
|
private LocalTime earliestTimeOfDayToSend;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private NotificationStatus status;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private int retryCount;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package SuMoC.backend.notification.repositories;
|
||||||
|
|
||||||
|
import SuMoC.backend.notification.models.Notification;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
public interface NotificationRepository extends JpaRepository<Notification, Long> {
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package SuMoC.backend.notification.services;
|
||||||
|
|
||||||
|
import SuMoC.backend.notification.factories.TrendNotificationFactory;
|
||||||
|
import SuMoC.backend.notification.models.Notification;
|
||||||
|
import SuMoC.backend.notification.repositories.NotificationRepository;
|
||||||
|
import SuMoC.backend.trend.TrendDetection;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class TrendNotificationService {
|
||||||
|
|
||||||
|
private final NotificationRepository notificationRepository;
|
||||||
|
|
||||||
|
private final TrendNotificationFactory trendNotificationFactory;
|
||||||
|
|
||||||
|
public List<Notification> generateTrendNotifications(List<TrendDetection> trendList) {
|
||||||
|
List<Notification> notificationList = trendList.stream().map(trendNotificationFactory::createNotification).toList();
|
||||||
|
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package SuMoC.backend.regulartrip.config;
|
||||||
|
|
||||||
|
import SuMoC.backend.regulartrip.detectionapproaches.Detector;
|
||||||
|
import SuMoC.backend.regulartrip.detectionapproaches.IterativeClusterer;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class DetectorConfiguration {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@ConditionalOnProperty(
|
||||||
|
prefix = "regulartripdetection",
|
||||||
|
name = "detection-algorithm",
|
||||||
|
havingValue = "iterative",
|
||||||
|
matchIfMissing = true
|
||||||
|
)
|
||||||
|
public Detector iterativeClusterer(RegularTripDetectionProperties properties) {
|
||||||
|
return new IterativeClusterer(properties);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package SuMoC.backend.regulartrip.config;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Component
|
||||||
|
@ConfigurationProperties(prefix = "regulartripdetection")
|
||||||
|
public class RegularTripDetectionProperties {
|
||||||
|
|
||||||
|
// TODO at end check if this is really right place for these vals
|
||||||
|
/**
|
||||||
|
* Minimum number of trips a user must have made between the same start and end locations
|
||||||
|
* for those trips to be considered regular.
|
||||||
|
*/
|
||||||
|
private Integer minTripsForRegularity = 2;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Time window in days to look back for detecting regular trips.
|
||||||
|
*/
|
||||||
|
private Integer detectionTimeWindowDays = 30;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Maximum time difference in minutes between trips to be considered the same regular trip.
|
||||||
|
*/
|
||||||
|
private Integer timeWindowSeconds = 90 * 60;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Number of times the iterative algorithm is run on randomly shuffled trip lists to pick best results.
|
||||||
|
*/
|
||||||
|
private Integer iterativeShuffleAmounts = 5;
|
||||||
|
|
||||||
|
private String detectionAlgorithm = "iterative";
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package SuMoC.backend.regulartrip.detectionapproaches;
|
||||||
|
|
||||||
|
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
|
||||||
|
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface Detector {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Core function to analyze a list of one users trips for regular trips. Assumes all trips have the same modality and user.
|
||||||
|
*/
|
||||||
|
List<DetectedRegularTripDTO> detectRegularTrips(List<RegularTripDetectionDTO> trips);
|
||||||
|
}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
package SuMoC.backend.regulartrip.detectionapproaches;
|
||||||
|
|
||||||
|
import SuMoC.backend.regulartrip.config.RegularTripDetectionProperties;
|
||||||
|
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
|
||||||
|
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
|
||||||
|
|
||||||
|
import java.time.LocalTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This is the first approach of a regular trip detection algorithm.
|
||||||
|
*/
|
||||||
|
public class IterativeClusterer implements Detector {
|
||||||
|
|
||||||
|
private final RegularTripDetectionProperties properties;
|
||||||
|
|
||||||
|
public IterativeClusterer(RegularTripDetectionProperties properties) {
|
||||||
|
this.properties = properties;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<DetectedRegularTripDTO> detectRegularTrips(List<RegularTripDetectionDTO> trips) {
|
||||||
|
// Step 1: Init potential detected trip for all trips
|
||||||
|
HashMap<Long, DetectedRegularTripDTO> baseDetectedTripsMap = initDetectedTripsMap(trips);
|
||||||
|
// Step 2: Find trips supported by min number of supporters
|
||||||
|
|
||||||
|
List<List<DetectedRegularTripDTO>> iterationResults = new ArrayList<>();
|
||||||
|
for (int i = 0; i < properties.getIterativeShuffleAmounts(); i++) {
|
||||||
|
// Deep copy the map for each iteration
|
||||||
|
HashMap<Long, DetectedRegularTripDTO> iterationMap = deepCopyDetectedTripsMap(baseDetectedTripsMap);
|
||||||
|
Collections.shuffle(trips);
|
||||||
|
iterationResults.add(aggregateToSupportedDetections(iterationMap, trips, properties.getMinTripsForRegularity()));
|
||||||
|
}
|
||||||
|
|
||||||
|
List<DetectedRegularTripDTO> bestIteration = pickBestIteration(iterationResults);
|
||||||
|
return deduplicateOverlappingDetections(bestIteration);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Picks the best detection results by picking iteration with the highest total number of supporters.
|
||||||
|
*/
|
||||||
|
private List<DetectedRegularTripDTO> pickBestIteration(List<List<DetectedRegularTripDTO>> iterationResults) {
|
||||||
|
return iterationResults.stream()
|
||||||
|
.max(Comparator.comparingInt(iteration ->
|
||||||
|
iteration.stream()
|
||||||
|
// subtracting 1 to avoid inflation by self supporting -> less detections with more supporters are better
|
||||||
|
.mapToInt(detection -> detection.getSupportingTrips().size() - 1)
|
||||||
|
.sum()))
|
||||||
|
.orElse(List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes overlapping detections by greedily selecting the best non-overlapping set.
|
||||||
|
* Detections with more supporters are prioritized.
|
||||||
|
*/
|
||||||
|
private List<DetectedRegularTripDTO> deduplicateOverlappingDetections(List<DetectedRegularTripDTO> detections) {
|
||||||
|
// Sort by supporter count (descending)
|
||||||
|
List<DetectedRegularTripDTO> sorted = new ArrayList<>(detections);
|
||||||
|
sorted.sort(Comparator.comparingInt(d -> -d.getSupportingTrips().size()));
|
||||||
|
|
||||||
|
List<DetectedRegularTripDTO> result = new ArrayList<>();
|
||||||
|
Set<Long> usedTripIds = new HashSet<>();
|
||||||
|
|
||||||
|
for (DetectedRegularTripDTO detection : sorted) {
|
||||||
|
// Get all trip IDs involved in this detection
|
||||||
|
Set<Long> detectionTripIds = new HashSet<>();
|
||||||
|
for (RegularTripDetectionDTO trip : detection.getSupportingTrips()) {
|
||||||
|
detectionTripIds.add(trip.getTripId());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if any trips are already used
|
||||||
|
boolean hasOverlap = detectionTripIds.stream().anyMatch(usedTripIds::contains);
|
||||||
|
|
||||||
|
if (!hasOverlap) {
|
||||||
|
result.add(detection);
|
||||||
|
usedTripIds.addAll(detectionTripIds);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Takes a map with potential detected regular trips and checks against a list of trips which are supported
|
||||||
|
* If a trip supports another detected regular trips, its own regular trip is removed.
|
||||||
|
*/
|
||||||
|
private List<DetectedRegularTripDTO> aggregateToSupportedDetections(
|
||||||
|
HashMap<Long, DetectedRegularTripDTO> potentialDetectedRegularTrips,
|
||||||
|
List<RegularTripDetectionDTO> trips,
|
||||||
|
int necessarySupporters
|
||||||
|
) {
|
||||||
|
// We need to dupe deletions with this list since we cant modify other list entries while iterating over it
|
||||||
|
Set<Long> deletedDetections = new HashSet<>();
|
||||||
|
|
||||||
|
for (Map.Entry<Long, DetectedRegularTripDTO> entry : potentialDetectedRegularTrips.entrySet()) {
|
||||||
|
if (deletedDetections.contains(entry.getKey())) continue;
|
||||||
|
|
||||||
|
// Check for all other trips if they support this detected regular trip
|
||||||
|
for (RegularTripDetectionDTO trip : trips) {
|
||||||
|
// prevent checking against trip the detected regular trip stems from
|
||||||
|
if (entry.getKey() == trip.getTripId()) continue;
|
||||||
|
|
||||||
|
if (supportsDetectedRegularTrip(entry.getValue(), trip)) {
|
||||||
|
entry.getValue().getSupportingTrips().add(trip);
|
||||||
|
// remove trip's own potential regular trip since its now a supporter
|
||||||
|
deletedDetections.add(trip.getTripId());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate final results
|
||||||
|
List<DetectedRegularTripDTO> detectedTrips = new ArrayList<>();
|
||||||
|
for (Map.Entry<Long, DetectedRegularTripDTO> entry : potentialDetectedRegularTrips.entrySet()) {
|
||||||
|
if (deletedDetections.contains(entry.getKey())) continue;
|
||||||
|
if (entry.getValue().getSupportingTrips().size() >= necessarySupporters) {
|
||||||
|
detectedTrips.add(entry.getValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return detectedTrips;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method holds the core logic to determine if a trip supports a detected regular trip.
|
||||||
|
*/
|
||||||
|
private boolean supportsDetectedRegularTrip(DetectedRegularTripDTO regularTrip, RegularTripDetectionDTO trip) {
|
||||||
|
// Conditions:
|
||||||
|
// 1. same day of week
|
||||||
|
if (regularTrip.getDayOfWeek() == trip.getDayOfTheWeek()) {
|
||||||
|
// 2. Departure and arrival within window
|
||||||
|
if (isWithinTimeWindow(regularTrip, trip)) {
|
||||||
|
// 3. Same start and end area
|
||||||
|
if (sameStartAndEndCellArea(regularTrip, trip)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* We consider start and end to be the same place when cells match or are direct neighbours.
|
||||||
|
*/
|
||||||
|
private boolean sameStartAndEndCellArea(DetectedRegularTripDTO regularTripDTO, RegularTripDetectionDTO trip) {
|
||||||
|
if (trip.getStartH3Cell().equals(regularTripDTO.getStartH3Center()) || regularTripDTO.getStartH3neighbours().contains(trip.getStartH3Cell())) {
|
||||||
|
return trip.getEndH3Cell().equals(regularTripDTO.getEndH3Center()) || regularTripDTO.getEndH3Neighbours().contains(trip.getEndH3Cell());
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isWithinTimeWindow(DetectedRegularTripDTO regularTrip, RegularTripDetectionDTO trip) {
|
||||||
|
LocalTime departure = LocalTime.ofInstant(trip.getStartTime(), ZoneId.systemDefault());
|
||||||
|
LocalTime arrival = LocalTime.ofInstant(trip.getEndTime(), ZoneId.systemDefault());
|
||||||
|
if (departure.isAfter(regularTrip.getDepartureWindowStart()) && departure.isBefore(regularTrip.getDepartureWindowEnd())) {
|
||||||
|
return arrival.isAfter(regularTrip.getArrivalWindowStart()) && arrival.isBefore(regularTrip.getArrivalWindowEnd());
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts all trips to a detected regular trip, using original tripId as map key
|
||||||
|
*/
|
||||||
|
private HashMap<Long, DetectedRegularTripDTO> initDetectedTripsMap(List<RegularTripDetectionDTO> trips) {
|
||||||
|
HashMap<Long, DetectedRegularTripDTO> potentialDetectedTrips = new HashMap<>();
|
||||||
|
|
||||||
|
for (RegularTripDetectionDTO trip : trips) {
|
||||||
|
LocalTime departure = LocalTime.ofInstant(trip.getStartTime(), ZoneId.systemDefault());
|
||||||
|
LocalTime arrival = LocalTime.ofInstant(trip.getEndTime(), ZoneId.systemDefault());
|
||||||
|
|
||||||
|
potentialDetectedTrips.put(trip.getTripId(), DetectedRegularTripDTO.builder()
|
||||||
|
.modality(trip.getMainModality())
|
||||||
|
.userId(trip.getUserId())
|
||||||
|
.dayOfWeek(trip.getDayOfTheWeek())
|
||||||
|
.departureWindowStart(departure.minusSeconds(properties.getTimeWindowSeconds() / 2))
|
||||||
|
.departureWindowEnd(departure.plusSeconds(properties.getTimeWindowSeconds() / 2))
|
||||||
|
.arrivalWindowStart(arrival.minusSeconds(properties.getTimeWindowSeconds() / 2))
|
||||||
|
.arrivalWindowEnd(arrival.plusSeconds(properties.getTimeWindowSeconds() / 2))
|
||||||
|
.startH3Center(trip.getStartH3Cell())
|
||||||
|
.endH3Center(trip.getEndH3Cell())
|
||||||
|
.startH3neighbours(trip.getStartH3CellKRingNeighboors())
|
||||||
|
.endH3Neighbours(trip.getEndH3CellKRingNeighboors())
|
||||||
|
.supportingTrips(new ArrayList<RegularTripDetectionDTO>(List.of(trip)))
|
||||||
|
.build());
|
||||||
|
}
|
||||||
|
return potentialDetectedTrips;
|
||||||
|
}
|
||||||
|
|
||||||
|
private HashMap<Long, DetectedRegularTripDTO> deepCopyDetectedTripsMap(
|
||||||
|
HashMap<Long, DetectedRegularTripDTO> original) {
|
||||||
|
|
||||||
|
HashMap<Long, DetectedRegularTripDTO> copy = new HashMap<>();
|
||||||
|
|
||||||
|
for (Map.Entry<Long, DetectedRegularTripDTO> entry : original.entrySet()) {
|
||||||
|
DetectedRegularTripDTO originalDto = entry.getValue();
|
||||||
|
|
||||||
|
// Create new DTO with copied supporting trips list
|
||||||
|
DetectedRegularTripDTO copiedDto = DetectedRegularTripDTO.builder()
|
||||||
|
.modality(originalDto.getModality())
|
||||||
|
.userId(originalDto.getUserId())
|
||||||
|
.dayOfWeek(originalDto.getDayOfWeek())
|
||||||
|
.departureWindowStart(originalDto.getDepartureWindowStart())
|
||||||
|
.departureWindowEnd(originalDto.getDepartureWindowEnd())
|
||||||
|
.arrivalWindowStart(originalDto.getArrivalWindowStart())
|
||||||
|
.arrivalWindowEnd(originalDto.getArrivalWindowEnd())
|
||||||
|
.startH3Center(originalDto.getStartH3Center())
|
||||||
|
.endH3Center(originalDto.getEndH3Center())
|
||||||
|
.startH3neighbours(originalDto.getStartH3neighbours())
|
||||||
|
.endH3Neighbours(originalDto.getEndH3Neighbours())
|
||||||
|
.supportingTrips(new ArrayList<>(originalDto.getSupportingTrips())) // New list
|
||||||
|
.build();
|
||||||
|
|
||||||
|
copy.put(entry.getKey(), copiedDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package SuMoC.backend.regulartrip.dtos;
|
||||||
|
|
||||||
|
import SuMoC.backend.trip.Modality;
|
||||||
|
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
|
||||||
|
import lombok.*;
|
||||||
|
|
||||||
|
import java.time.LocalTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A DTO representing the details of a detected regular trip.
|
||||||
|
*/
|
||||||
|
@Builder
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class DetectedRegularTripDTO {
|
||||||
|
private long userId;
|
||||||
|
private Modality modality;
|
||||||
|
private int dayOfWeek;
|
||||||
|
private LocalTime departureWindowStart;
|
||||||
|
private LocalTime departureWindowEnd;
|
||||||
|
private LocalTime arrivalWindowStart;
|
||||||
|
private LocalTime arrivalWindowEnd;
|
||||||
|
private String startH3Center;
|
||||||
|
private String endH3Center;
|
||||||
|
private List<String> startH3neighbours;
|
||||||
|
private List<String> endH3Neighbours;
|
||||||
|
private List<RegularTripDetectionDTO> supportingTrips;
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package SuMoC.backend.regulartrip.services;
|
||||||
|
|
||||||
|
import SuMoC.backend.regulartrip.config.RegularTripDetectionProperties;
|
||||||
|
import SuMoC.backend.regulartrip.detectionapproaches.Detector;
|
||||||
|
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
|
||||||
|
import SuMoC.backend.trip.Modality;
|
||||||
|
import SuMoC.backend.trip.TripMapper;
|
||||||
|
import SuMoC.backend.trip.TripRepository;
|
||||||
|
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class RegularTripDetectionService {
|
||||||
|
|
||||||
|
RegularTripDetectionProperties properties;
|
||||||
|
|
||||||
|
TripRepository tripRepository;
|
||||||
|
|
||||||
|
TripMapper tripMapper;
|
||||||
|
|
||||||
|
Detector tripDetector;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detects regular trips for all users based on saved trip data and RegularTripDetectionProperties.
|
||||||
|
* This is the main method that orchestrates the detection process and should be used to detect trips
|
||||||
|
* we want to suggest alternatives for.
|
||||||
|
*/
|
||||||
|
public HashMap<Long, List<DetectedRegularTripDTO>> detectRegularCarTrips() {
|
||||||
|
var tripsByUser = getTripsByUser(Modality.CAR);
|
||||||
|
|
||||||
|
// TODO this could be parallelized in the future
|
||||||
|
HashMap<Long, List<DetectedRegularTripDTO>> results = new HashMap<>();
|
||||||
|
for (Long userId : tripsByUser.keySet()) {
|
||||||
|
results.put(userId, tripDetector.detectRegularTrips(tripsByUser.get(userId)));
|
||||||
|
}
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
private HashMap<Long, List<RegularTripDetectionDTO>> getTripsByUser(Modality modality) {
|
||||||
|
Instant fromDate = Instant.now().minusSeconds(properties.getDetectionTimeWindowDays() * 24 * 60 * 60);
|
||||||
|
List<RegularTripDetectionDTO> dtoList = tripMapper.toRegularTripDetectionDTOS(tripRepository.findAllValidFromDateWithMainModality(fromDate, modality));
|
||||||
|
|
||||||
|
HashMap<Long, List<RegularTripDetectionDTO>> tripsByUser = new HashMap<>();
|
||||||
|
for (RegularTripDetectionDTO dto : dtoList) {
|
||||||
|
tripsByUser.computeIfAbsent(dto.getUserId(), k -> new ArrayList<>()).add(dto);
|
||||||
|
}
|
||||||
|
return tripsByUser;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,56 @@
|
|||||||
|
package SuMoC.backend.routing;
|
||||||
|
|
||||||
|
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||||
|
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
|
||||||
|
import SuMoC.backend.routing.dtos.RoutingPreferencesDTO;
|
||||||
|
import SuMoC.backend.routing.services.RoutingService;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import org.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 org.springframework.web.reactive.function.client.WebClientRequestException;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/routing/alternative")
|
||||||
|
public class RoutingController {
|
||||||
|
|
||||||
|
private final Logger logger = Logger.getLogger(RoutingController.class.getName());
|
||||||
|
|
||||||
|
private final RoutingService routingService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
public RoutingController(RoutingService routingService) {
|
||||||
|
this.routingService = routingService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/request")
|
||||||
|
@Schema(description = "Calculates alternative, sustainable routes for the request. The delta of departure and arrival in the requestdto is used as baseline to determine if alternatives are acceptable.")
|
||||||
|
public ResponseEntity<List<RouteDTO>> requestAlternativeRoutes(@Valid @RequestBody RoutingAlternativeRequestDTO routingAlternativeRequestDTO) {
|
||||||
|
try {
|
||||||
|
if (routingAlternativeRequestDTO.getRoutingPreferencesDTO() == null) { // Use default preferences if none are provided
|
||||||
|
// TODO we might want to also save users preferences in the future
|
||||||
|
var preferences = new RoutingPreferencesDTO(); // use default preferences
|
||||||
|
routingAlternativeRequestDTO.setRoutingPreferencesDTO(preferences);
|
||||||
|
}
|
||||||
|
|
||||||
|
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,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
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package SuMoC.backend.routing.dtos;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import jakarta.annotation.Nullable;
|
||||||
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import lombok.*;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@Builder
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
@Schema(description = "This DTO represents a request for alternative routes between an origin and a destination.")
|
||||||
|
public class RoutingAlternativeRequestDTO {
|
||||||
|
@NotNull
|
||||||
|
private Double originLat;
|
||||||
|
@NotNull
|
||||||
|
private Double originLon;
|
||||||
|
@NotNull
|
||||||
|
private Double destinationLat;
|
||||||
|
@NotNull
|
||||||
|
private Double destinationLon;
|
||||||
|
@NotNull
|
||||||
|
private Instant arrivalTime;
|
||||||
|
@NotNull
|
||||||
|
private Instant departureTime; // We need both times to calculate duration to compare alternatives
|
||||||
|
@Nullable
|
||||||
|
private RoutingPreferencesDTO routingPreferencesDTO;
|
||||||
|
}
|
||||||
@@ -1,37 +1,20 @@
|
|||||||
package SuMoC.backend.routing.dtos;
|
package SuMoC.backend.routing.dtos;
|
||||||
|
|
||||||
import SuMoC.backend.trip.Modality;
|
import SuMoC.backend.trip.Modality;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
@Getter
|
||||||
* This DTO represents the user preferences for routing / alternative route suggestions.
|
@Setter
|
||||||
* Provides default values for all fields.
|
@Schema(description = "This DTO represents the user preferences for routing / alternative route suggestions.")
|
||||||
*/
|
|
||||||
public class RoutingPreferencesDTO {
|
public class RoutingPreferencesDTO {
|
||||||
private boolean preferPhysicalActivity = false;
|
private boolean preferPhysicalActivity = false;
|
||||||
private List<Modality> excludedModalities = List.of();
|
private boolean considerWeatherConditions = true;
|
||||||
|
private List<Modality> modalitiesToConsider = new ArrayList<>(
|
||||||
public RoutingPreferencesDTO() {}
|
List.of(Modality.WALKING, Modality.BICYCLE, Modality.ESCOOTER, Modality.BUS, Modality.TRAM, Modality.TRAIN)
|
||||||
|
);
|
||||||
public RoutingPreferencesDTO(boolean preferPhysicalActivity, List<Modality> excludedModalities) {
|
|
||||||
this.preferPhysicalActivity = preferPhysicalActivity;
|
|
||||||
this.excludedModalities = excludedModalities;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isPreferPhysicalActivity() {
|
|
||||||
return preferPhysicalActivity;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPreferPhysicalActivity(boolean preferPhysicalActivity) {
|
|
||||||
this.preferPhysicalActivity = preferPhysicalActivity;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<Modality> getExcludedModalities() {
|
|
||||||
return excludedModalities;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExcludedModalities(List<Modality> excludedModalities) {
|
|
||||||
this.excludedModalities = excludedModalities;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package SuMoC.backend.routing.dtos;
|
||||||
|
|
||||||
|
import SuMoC.backend.trip.Modality;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Schema(description = "A single step within a suggested alternative route.")
|
||||||
|
public class StepDTO {
|
||||||
|
private Modality modality;
|
||||||
|
private String lineNumber;
|
||||||
|
private double distanceMeters;
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package SuMoC.backend.routing.exceptions;
|
||||||
|
|
||||||
|
public class NoCarRouteFoundException extends RuntimeException {
|
||||||
|
public NoCarRouteFoundException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package SuMoC.backend.routing.exceptions;
|
||||||
|
|
||||||
|
public class NoCarbonEmissionFoundException extends RuntimeException {
|
||||||
|
public NoCarbonEmissionFoundException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
package SuMoC.backend.routing.services;
|
||||||
|
|
||||||
|
import SuMoC.backend.meteo.ForecastResponse;
|
||||||
|
import SuMoC.backend.meteo.ForecastService;
|
||||||
|
import SuMoC.backend.meteo.WeatherCondition;
|
||||||
|
import SuMoC.backend.routing.config.RoutingProperties;
|
||||||
|
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||||
|
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This services bundles functionality to filter suggested alternative routes to prevent us from suggesting
|
||||||
|
* routes with unacceptable additional travel time etc.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AlternativeFilterService {
|
||||||
|
|
||||||
|
private static final Logger logger = Logger.getLogger(AlternativeFilterService.class.getName());
|
||||||
|
private final ForecastService forecastService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* We apply the following logic to filter out trips:
|
||||||
|
* Regular:
|
||||||
|
* - A minimum of X minutes extra is acceptable
|
||||||
|
* - Y% more travel time is acceptable
|
||||||
|
* If user wants more phyiscal activity, for cycling and walking:
|
||||||
|
* - A minimum of Z minutes extra is acceptable
|
||||||
|
* - W% more travel time is acceptable
|
||||||
|
*/
|
||||||
|
public List<RouteDTO> filterForAdditionalTravelTime(
|
||||||
|
RoutingAlternativeRequestDTO alternativeRequestDTO,
|
||||||
|
List<RouteDTO> alternatives,
|
||||||
|
RoutingProperties routingProperties
|
||||||
|
) {
|
||||||
|
List<RouteDTO> filteredAlternatives = new ArrayList<>();
|
||||||
|
|
||||||
|
long originalTravelTimeSeconds = alternativeRequestDTO.getArrivalTime().getEpochSecond() - alternativeRequestDTO.getDepartureTime().getEpochSecond();
|
||||||
|
double toleratedMaximumRegular = originalTravelTimeSeconds * routingProperties.getAcceptableAdditionalMultiplierRegular();
|
||||||
|
double toleratedMaximumPhysical = originalTravelTimeSeconds * routingProperties.getAcceptableAdditionalMultiplierPrefersPhysical();
|
||||||
|
|
||||||
|
for (RouteDTO routeDTO : alternatives) {
|
||||||
|
long travelTimeDeltaSeconds = routeDTO.getDurationSeconds() - originalTravelTimeSeconds;
|
||||||
|
|
||||||
|
if (routeDTO.isPhysicalActivity() && alternativeRequestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity()) {
|
||||||
|
if (travelTimeDeltaSeconds < routingProperties.getMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity()
|
||||||
|
|| (long) travelTimeDeltaSeconds < toleratedMaximumPhysical) {
|
||||||
|
filteredAlternatives.add(routeDTO);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (travelTimeDeltaSeconds < routingProperties.getMinimumAcceptedAdditionalSecondsRegular()
|
||||||
|
|| (long) travelTimeDeltaSeconds < toleratedMaximumRegular) {
|
||||||
|
filteredAlternatives.add(routeDTO);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return filteredAlternatives;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If weather conditions at point of travel are considered not acceptable for "outdoor" modalities such as
|
||||||
|
* walking and biking, the routes are removed. This does not affect transit routes which necessarily have to contain
|
||||||
|
* some walking elements.
|
||||||
|
*/
|
||||||
|
public List<RouteDTO> filterForBadWeather(
|
||||||
|
RoutingAlternativeRequestDTO requestDTO,
|
||||||
|
List<RouteDTO> alternatives,
|
||||||
|
RoutingProperties routingProperties
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
ForecastResponse forecast = forecastService.getTodayYesterdayForecast(requestDTO.getOriginLat(), requestDTO.getOriginLon());
|
||||||
|
|
||||||
|
ArrayList<RouteDTO> filteredAlternatives = new ArrayList<>();
|
||||||
|
for (RouteDTO route : alternatives) {
|
||||||
|
if (route.isPhysicalActivity()) {
|
||||||
|
var weatherConditions = forecast.getWeatherConditionsBetween(route.getStartDateTime(), route.getEndDateTime());
|
||||||
|
if (route.isCyclingRoute() && allConditionsAcceptable(weatherConditions, routingProperties.getAcceptableCyclingConditions())) {
|
||||||
|
filteredAlternatives.add(route);
|
||||||
|
} else if (route.isWalkingRoute() && allConditionsAcceptable(weatherConditions, routingProperties.getAcceptableWalkingConditions())) {
|
||||||
|
filteredAlternatives.add(route);
|
||||||
|
} else {
|
||||||
|
throw new RuntimeException("Unexpected case of a physical activity route that is not pure cycling or walking");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
filteredAlternatives.add(route);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return filteredAlternatives;
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.warning(e.getMessage());
|
||||||
|
return alternatives;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean allConditionsAcceptable(List<WeatherCondition> conditions, List<WeatherCondition> acceptableConditions) {
|
||||||
|
return new HashSet<>(acceptableConditions).containsAll(conditions);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package SuMoC.backend.routing.services;
|
||||||
|
|
||||||
|
import SuMoC.backend.routing.dtos.StepDTO;
|
||||||
|
import SuMoC.backend.trip.Modality;
|
||||||
|
import sumoc.backend.carta.client.model.Route;
|
||||||
|
import sumoc.backend.carta.client.model.Step;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Processes a Carta Route and extracts StepDTOs and first , last stop name.
|
||||||
|
*/
|
||||||
|
public class CartaTransitRouteProcessor {
|
||||||
|
private final Route cartaRoute;
|
||||||
|
|
||||||
|
private List<StepDTO> steps = null;
|
||||||
|
|
||||||
|
private String firstStopName = null;
|
||||||
|
|
||||||
|
private String lastStopName = null;
|
||||||
|
|
||||||
|
public CartaTransitRouteProcessor(Route cartaRoute) {
|
||||||
|
this.cartaRoute = cartaRoute;
|
||||||
|
this.process();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extracts information from the route.
|
||||||
|
*/
|
||||||
|
public void process() {
|
||||||
|
ArrayList<StepDTO> steps = new ArrayList<>();
|
||||||
|
|
||||||
|
assert cartaRoute.getSteps() != null;
|
||||||
|
for (Step step : cartaRoute.getSteps()) {
|
||||||
|
// Get first stop name
|
||||||
|
if (this.firstStopName == null && step.getType().equals("TransitStep")) {
|
||||||
|
this.firstStopName = step.getStops().getFirst().getName();
|
||||||
|
}
|
||||||
|
// always set last stop as lastStopName so it will match in the end
|
||||||
|
if (step.getType().equals("TransitStep")) {
|
||||||
|
this.lastStopName = step.getStops().getLast().getName();
|
||||||
|
}
|
||||||
|
|
||||||
|
Modality stepModality = step.getType().equals("TransitStep")
|
||||||
|
? Modality.fromCartaString(step.getLine().getType().toString())
|
||||||
|
: Modality.fromCartaString(step.getType());
|
||||||
|
|
||||||
|
steps.add(new StepDTO(
|
||||||
|
stepModality,
|
||||||
|
step.getType().equals("TransitStep") ? step.getLine().getCode() : null,
|
||||||
|
step.getDistance()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
this.steps = steps;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<StepDTO> getSteps() {
|
||||||
|
if (this.steps == null) {
|
||||||
|
throw new IllegalStateException("Getter called before processing");
|
||||||
|
}
|
||||||
|
return this.steps;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFirstStopName() {
|
||||||
|
if (this.firstStopName == null) {
|
||||||
|
throw new IllegalStateException("Getter called before processing");
|
||||||
|
}
|
||||||
|
return this.firstStopName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLastStopName() {
|
||||||
|
if (this.lastStopName == null) {
|
||||||
|
throw new IllegalStateException("Getter called before processing");
|
||||||
|
}
|
||||||
|
return this.lastStopName;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,268 @@
|
|||||||
|
package SuMoC.backend.routing.services;
|
||||||
|
|
||||||
|
import SuMoC.backend.carta.CartaClient;
|
||||||
|
import SuMoC.backend.geocoding.AddressDTO;
|
||||||
|
import SuMoC.backend.geocoding.GeoCodingService;
|
||||||
|
import SuMoC.backend.routing.config.AdHocRoutingProperties;
|
||||||
|
import SuMoC.backend.routing.config.OnCallRoutingProperties;
|
||||||
|
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||||
|
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
|
||||||
|
import SuMoC.backend.routing.dtos.StepDTO;
|
||||||
|
import SuMoC.backend.routing.exceptions.NoCarRouteFoundException;
|
||||||
|
import SuMoC.backend.routing.exceptions.NoCarbonEmissionFoundException;
|
||||||
|
import SuMoC.backend.trip.Modality;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
import sumoc.backend.carta.client.model.Direction;
|
||||||
|
import sumoc.backend.carta.client.model.Route;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class RoutingService {
|
||||||
|
|
||||||
|
private final GeoCodingService geoCodingService;
|
||||||
|
|
||||||
|
private final CartaClient cartaClient;
|
||||||
|
|
||||||
|
private final AlternativeFilterService alternativeFilterService;
|
||||||
|
|
||||||
|
private final OnCallRoutingProperties onCallRoutingProperties;
|
||||||
|
|
||||||
|
private final AdHocRoutingProperties adHocRoutingProperties;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Makes an individual call to the CARTA API and returns a direction future.
|
||||||
|
*/
|
||||||
|
private CompletableFuture<Direction> getCartaFuture(
|
||||||
|
RoutingAlternativeRequestDTO requestDTO,
|
||||||
|
String mode,
|
||||||
|
String types,
|
||||||
|
int alternatives
|
||||||
|
) {
|
||||||
|
return cartaClient.asyncGetRoute(
|
||||||
|
requestDTO.getOriginLat() + "," + requestDTO.getOriginLon(),
|
||||||
|
requestDTO.getDestinationLat() + "," + requestDTO.getDestinationLon(),
|
||||||
|
mode,
|
||||||
|
requestDTO.getArrivalTime(),
|
||||||
|
null,
|
||||||
|
alternatives, // alternatives
|
||||||
|
null, // walkingSpeed
|
||||||
|
null, // transferTime TODO what is default? adapt?
|
||||||
|
types,
|
||||||
|
null, // range
|
||||||
|
requestDTO.getOriginLat() + "," + requestDTO.getOriginLon()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Makes concurrent direction calls to CARTA for all modes requested + car as baseline.
|
||||||
|
* Possible keys of the returned Map:
|
||||||
|
* - car (always)
|
||||||
|
* - walk (optional)
|
||||||
|
* - bike (optional)
|
||||||
|
* - transit (optional)
|
||||||
|
*/
|
||||||
|
private HashMap<String, Direction> getPossibleDirectionsFromCarta(RoutingAlternativeRequestDTO requestDTO) {
|
||||||
|
Map<String, CompletableFuture<Direction>> futuresByMode = new HashMap<>();
|
||||||
|
assert requestDTO.getRoutingPreferencesDTO() != null;
|
||||||
|
|
||||||
|
// serves as baseline
|
||||||
|
futuresByMode.put("car", getCartaFuture(requestDTO, "driving", "", 1));
|
||||||
|
// type string for carta api
|
||||||
|
List<String> typeList = new ArrayList<>();
|
||||||
|
// add request futures for all modes request by user + assemble type string for a possible transit directions request
|
||||||
|
for (Modality modality : requestDTO.getRoutingPreferencesDTO().getModalitiesToConsider()) {
|
||||||
|
switch (modality) {
|
||||||
|
case WALKING -> futuresByMode.put("walk", getCartaFuture(requestDTO, "walking", "", 1));
|
||||||
|
case BICYCLE -> futuresByMode.put("bike", getCartaFuture(requestDTO, "cycling", "", 1));
|
||||||
|
case BUS -> {
|
||||||
|
typeList.add("3"); // bus
|
||||||
|
typeList.add("8"); // trolleybus
|
||||||
|
}
|
||||||
|
// case ESCOOTER -> typeList.add("X"); TODO - check if this and bike should be included in transit or separate
|
||||||
|
case TRAM -> typeList.add("0");
|
||||||
|
case TRAIN -> {
|
||||||
|
typeList.add("1"); // subway
|
||||||
|
typeList.add("2"); // rail
|
||||||
|
typeList.add("9"); // monorail
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!typeList.isEmpty()) { // if any public transit the app allows toggling is selcted we add the funny transit types and make the transit request
|
||||||
|
typeList.add("4"); // Ferry
|
||||||
|
typeList.add("5"); // cablecar
|
||||||
|
typeList.add("6"); // gondola
|
||||||
|
typeList.add("7"); // funicular
|
||||||
|
String types = String.join(",", typeList);
|
||||||
|
futuresByMode.put("transit", getCartaFuture(requestDTO, "transit", types, 3));
|
||||||
|
}
|
||||||
|
|
||||||
|
// return all future results as list when resvoled
|
||||||
|
HashMap<String, Direction> directions = new HashMap<>();
|
||||||
|
for (Map.Entry<String, CompletableFuture<Direction>> entry : futuresByMode.entrySet()) {
|
||||||
|
directions.put(entry.getKey(), entry.getValue().join());
|
||||||
|
}
|
||||||
|
return directions;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets possible routes from CARTA, converts them to our format and applies filter to only provide acceptable solutions without excessive additional travel time.
|
||||||
|
* This is the public method for alternatives explicitly asked for by the client.
|
||||||
|
*/
|
||||||
|
public List<RouteDTO> determineAlternativeRoutesOnUserRequest(RoutingAlternativeRequestDTO requestDTO) {
|
||||||
|
List<RouteDTO> routes = getPossibleAlternativeRoutes(requestDTO);
|
||||||
|
routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, onCallRoutingProperties);
|
||||||
|
|
||||||
|
return routes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Public alternative retrieval method which is used to check for alternatives we suggest to user via notification
|
||||||
|
* right after user finished the trip.
|
||||||
|
* Similar to determineAlternativeRoutesOnUserRequest but here we apply stricter thresholds for alternatives
|
||||||
|
* and also apply weather filtering (if enabled) to not suggest routes the user definitly would not have consideres.
|
||||||
|
*/
|
||||||
|
public List<RouteDTO> determineAlternativeRoutesAdHoc(RoutingAlternativeRequestDTO requestDTO) {
|
||||||
|
assert requestDTO.getRoutingPreferencesDTO() != null;
|
||||||
|
|
||||||
|
List<RouteDTO> routes = getPossibleAlternativeRoutes(requestDTO);
|
||||||
|
routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, adHocRoutingProperties);
|
||||||
|
|
||||||
|
if (requestDTO.getRoutingPreferencesDTO().isConsiderWeatherConditions()) {
|
||||||
|
routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties);
|
||||||
|
}
|
||||||
|
|
||||||
|
return routes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns possible alternative routes for the request - no sanity filtering regarding travel times etc. is applied.
|
||||||
|
*/
|
||||||
|
private List<RouteDTO> getPossibleAlternativeRoutes(RoutingAlternativeRequestDTO requestDTO) {
|
||||||
|
assert requestDTO.getRoutingPreferencesDTO() != null;
|
||||||
|
HashMap<String, Direction> directionMap = getPossibleDirectionsFromCarta(requestDTO);
|
||||||
|
ArrayList<RouteDTO> suggestedAlternatives = new ArrayList<>();
|
||||||
|
|
||||||
|
// Fetch origin and destination addresses concurrently
|
||||||
|
var addressesMono = Mono.zip(
|
||||||
|
geoCodingService.getAddress(requestDTO.getOriginLat(), requestDTO.getOriginLon()),
|
||||||
|
geoCodingService.getAddress(requestDTO.getDestinationLat(), requestDTO.getDestinationLon())
|
||||||
|
);
|
||||||
|
var addressesTuple = addressesMono.block();
|
||||||
|
AddressDTO originAddress = addressesTuple.getT1();
|
||||||
|
AddressDTO destinationAddress = addressesTuple.getT2();
|
||||||
|
|
||||||
|
// Setting up car data for baseline
|
||||||
|
Route carRoute;
|
||||||
|
try {
|
||||||
|
carRoute = directionMap.get("car").getRoutes().getFirst();
|
||||||
|
} catch (NullPointerException e) {
|
||||||
|
throw new NoCarRouteFoundException("No car route to compare to was found.");
|
||||||
|
}
|
||||||
|
double carCarbondDioxide;
|
||||||
|
try {
|
||||||
|
carCarbondDioxide = carRoute.getEmission().getCarbonDioxide();
|
||||||
|
} catch (NullPointerException e) {
|
||||||
|
throw new NoCarbonEmissionFoundException("No carbon emission was provided for the car route.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (directionMap.containsKey("bike")) {
|
||||||
|
Direction bikeDirection = directionMap.get("bike");
|
||||||
|
if (bikeDirection.getRoutes() != null && !bikeDirection.getRoutes().isEmpty()) {
|
||||||
|
Route bikeRoute = bikeDirection.getRoutes().getFirst();
|
||||||
|
ArrayList<StepDTO> steps = new ArrayList<>();
|
||||||
|
steps.add(new StepDTO(
|
||||||
|
Modality.BICYCLE,
|
||||||
|
null,
|
||||||
|
bikeRoute.getDistance()
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
RouteDTO routeDTO = new RouteDTO(
|
||||||
|
originAddress,
|
||||||
|
null,
|
||||||
|
bikeRoute.getSourceCoordinate().getLatitude(),
|
||||||
|
bikeRoute.getSourceCoordinate().getLongitude(),
|
||||||
|
destinationAddress,
|
||||||
|
null,
|
||||||
|
bikeRoute.getTargetCoordinate().getLatitude(),
|
||||||
|
bikeRoute.getTargetCoordinate().getLongitude(),
|
||||||
|
requestDTO.getArrivalTime().minusSeconds(bikeRoute.getDuration()),
|
||||||
|
requestDTO.getArrivalTime(),
|
||||||
|
steps,
|
||||||
|
carCarbondDioxide,
|
||||||
|
bikeRoute.getDuration() - carRoute.getDuration(),
|
||||||
|
0.0
|
||||||
|
);
|
||||||
|
suggestedAlternatives.add(routeDTO);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (directionMap.containsKey("walk")) {
|
||||||
|
Direction walkDirection = directionMap.get("walk");
|
||||||
|
if (walkDirection.getRoutes() != null && !walkDirection.getRoutes().isEmpty()) {
|
||||||
|
Route walkRoute = walkDirection.getRoutes().getFirst();
|
||||||
|
ArrayList<StepDTO> steps = new ArrayList<>();
|
||||||
|
steps.add(new StepDTO(
|
||||||
|
Modality.WALKING,
|
||||||
|
null,
|
||||||
|
walkRoute.getDistance()
|
||||||
|
));
|
||||||
|
|
||||||
|
RouteDTO routeDTO = new RouteDTO(
|
||||||
|
originAddress,
|
||||||
|
null,
|
||||||
|
walkRoute.getSourceCoordinate().getLatitude(),
|
||||||
|
walkRoute.getSourceCoordinate().getLongitude(),
|
||||||
|
destinationAddress,
|
||||||
|
null,
|
||||||
|
walkRoute.getTargetCoordinate().getLatitude(),
|
||||||
|
walkRoute.getTargetCoordinate().getLongitude(),
|
||||||
|
requestDTO.getArrivalTime().minusSeconds(walkRoute.getDuration()),
|
||||||
|
requestDTO.getArrivalTime(),
|
||||||
|
steps,
|
||||||
|
carCarbondDioxide,
|
||||||
|
walkRoute.getDuration() - carRoute.getDuration(),
|
||||||
|
0.0
|
||||||
|
);
|
||||||
|
suggestedAlternatives.add(routeDTO);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (directionMap.containsKey("transit")) {
|
||||||
|
Direction transitDirection = directionMap.get("transit");
|
||||||
|
if (transitDirection.getRoutes() != null && !transitDirection.getRoutes().isEmpty()) {
|
||||||
|
for (Route route : transitDirection.getRoutes()) {
|
||||||
|
CartaTransitRouteProcessor routeProcessor = new CartaTransitRouteProcessor(route);
|
||||||
|
|
||||||
|
RouteDTO routeDTO = new RouteDTO(
|
||||||
|
originAddress,
|
||||||
|
routeProcessor.getFirstStopName(),
|
||||||
|
route.getSourceCoordinate().getLatitude(),
|
||||||
|
route.getSourceCoordinate().getLongitude(),
|
||||||
|
destinationAddress,
|
||||||
|
routeProcessor.getLastStopName(),
|
||||||
|
route.getTargetCoordinate().getLatitude(),
|
||||||
|
route.getTargetCoordinate().getLongitude(),
|
||||||
|
requestDTO.getArrivalTime().minusSeconds(route.getDuration()),
|
||||||
|
requestDTO.getArrivalTime(),
|
||||||
|
routeProcessor.getSteps(),
|
||||||
|
carCarbondDioxide - route.getEmission().getCarbonDioxide(),
|
||||||
|
route.getDuration() - carRoute.getDuration(),
|
||||||
|
route.getEmission().getCarbonDioxide()
|
||||||
|
);
|
||||||
|
suggestedAlternatives.add(routeDTO);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return suggestedAlternatives;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package SuMoC.backend.scheduling;
|
||||||
|
|
||||||
|
import SuMoC.backend.trend.services.StatTableUpdateService;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class ScheduledTasks {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);
|
||||||
|
|
||||||
|
private final SchedulingProperties properties;
|
||||||
|
|
||||||
|
private final StatTableUpdateService statTableUpdateService;
|
||||||
|
|
||||||
|
@Scheduled(cron = "#{@schedulingProperties.calculateWeeklyMobilityStats}")
|
||||||
|
public void scheduleCalculateWeeklyMobilityStats() {
|
||||||
|
logger.info("Scheduled task triggered: calculateWeeklyMobilityStatsForAllUsers");
|
||||||
|
try {
|
||||||
|
LocalDate dayOfLastWeek = LocalDate.now().minusDays(7);
|
||||||
|
statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(dayOfLastWeek);
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error("Error calculating weekly mobility stats.", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package SuMoC.backend.scheduling;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.scheduling.TaskScheduler;
|
||||||
|
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SchedulingConfig {
|
||||||
|
|
||||||
|
private final SchedulingProperties schedulingProperties;
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public TaskScheduler taskScheduler() {
|
||||||
|
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
|
||||||
|
scheduler.setPoolSize(schedulingProperties.getPoolSize());
|
||||||
|
scheduler.setThreadNamePrefix("sumoc-scheduler-");
|
||||||
|
scheduler.setAwaitTerminationSeconds(30);
|
||||||
|
scheduler.setWaitForTasksToCompleteOnShutdown(true);
|
||||||
|
return scheduler;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package SuMoC.backend.scheduling;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@ConfigurationProperties(prefix = "sumoc.scheduling")
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
public class SchedulingProperties {
|
||||||
|
private int poolSize = 5;
|
||||||
|
private String calculateWeeklyMobilityStats = "1 30 0 * * 1"; // Once per week
|
||||||
|
}
|
||||||
@@ -88,13 +88,21 @@ public class SecurityConfiguration {
|
|||||||
.cors(withDefaults())
|
.cors(withDefaults())
|
||||||
//.authorizeHttpRequests(auth -> auth.anyRequest().permitAll()) //allows Access To ALL APIs, Security is off
|
//.authorizeHttpRequests(auth -> auth.anyRequest().permitAll()) //allows Access To ALL APIs, Security is off
|
||||||
.authorizeHttpRequests(auth -> {
|
.authorizeHttpRequests(auth -> {
|
||||||
|
auth.requestMatchers(AUTH_WHITELIST).permitAll();
|
||||||
auth.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll();
|
auth.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll();
|
||||||
|
auth.requestMatchers("/dev/**").permitAll();
|
||||||
|
auth.requestMatchers("/routing/alternative/**").permitAll();
|
||||||
auth.requestMatchers("/auth/user/**").permitAll();
|
auth.requestMatchers("/auth/user/**").permitAll();
|
||||||
auth.requestMatchers("/admin/**").hasRole("ADMIN"); //looks for "ROLE_ADMIN" //alternative: hasAuthoritiy("ADMIN")
|
auth.requestMatchers("/admin/**").hasRole("ADMIN"); //looks for "ROLE_ADMIN" //alternative: hasAuthoritiy("ADMIN")
|
||||||
auth.requestMatchers("/user/**").hasAnyRole("ADMIN", "USER");
|
auth.requestMatchers("/user/**").hasAnyRole("ADMIN", "USER");
|
||||||
auth.requestMatchers("/friendship/**").hasAnyRole("ADMIN", "USER");
|
auth.requestMatchers("/friendship/**").hasAnyRole("ADMIN", "USER");
|
||||||
auth.requestMatchers("/trip/**").hasAnyRole("USER", "ADMIN");
|
auth.requestMatchers("/trip/**").hasAnyRole("USER", "ADMIN");
|
||||||
auth.requestMatchers(AUTH_WHITELIST).permitAll();
|
auth.requestMatchers("/geocoding/**").hasAnyRole("USER", "ADMIN");
|
||||||
|
|
||||||
|
// gamification
|
||||||
|
auth.requestMatchers("/badges/**").hasAnyRole("ADMIN", "USER");
|
||||||
|
auth.requestMatchers("/leaderboard/**").hasAnyRole("ADMIN", "USER");
|
||||||
|
|
||||||
//auth.requestMatchers("/error").permitAll();
|
//auth.requestMatchers("/error").permitAll();
|
||||||
auth.anyRequest().authenticated();
|
auth.anyRequest().authenticated();
|
||||||
|
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ public class UserAuthenticationController {
|
|||||||
@Operation(summary = "Registriert einen neuen Benutzer", description = "Erstellt einen neuen Benutzer und gibt die Benutzerdaten zurück")
|
@Operation(summary = "Registriert einen neuen Benutzer", description = "Erstellt einen neuen Benutzer und gibt die Benutzerdaten zurück")
|
||||||
@ApiResponses(value = {
|
@ApiResponses(value = {
|
||||||
@ApiResponse(responseCode = "200", description = "Benutzer erfolgreich registriert",
|
@ApiResponse(responseCode = "200", description = "Benutzer erfolgreich registriert",
|
||||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = LoginResponseDTO.class))),
|
content = @Content(mediaType = "application/json", schema = @Schema(implementation = RegistrationResponseDTO.class))),
|
||||||
@ApiResponse(responseCode = "400", description = "Ungültige Eingabedaten",
|
@ApiResponse(responseCode = "400", description = "Ungültige Eingabedaten",
|
||||||
content = @Content(mediaType = "application/json"))
|
content = @Content(mediaType = "application/json"))
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
package SuMoC.backend.security.dtos;
|
package SuMoC.backend.security.dtos;
|
||||||
|
|
||||||
import jakarta.validation.constraints.NotNull;
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import lombok.Builder;
|
||||||
|
|
||||||
|
@Builder
|
||||||
public class UserRegistrationDTO {
|
public class UserRegistrationDTO {
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package SuMoC.backend.seed.trip;
|
||||||
|
|
||||||
|
import SuMoC.backend.trip.TripFactory;
|
||||||
|
import SuMoC.backend.trip.TripService;
|
||||||
|
import SuMoC.backend.trip.dtos.NewTripDTO;
|
||||||
|
import SuMoC.backend.user.repository.UserRepository;
|
||||||
|
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;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@Profile("dev")
|
||||||
|
@Order(2)
|
||||||
|
public class DevTripSeeder implements CommandLineRunner {
|
||||||
|
|
||||||
|
private final TripService tripService;
|
||||||
|
|
||||||
|
private final UserRepository userRepository;
|
||||||
|
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
public DevTripSeeder(TripService tripService, UserRepository userRepository) {
|
||||||
|
this.tripService = tripService;
|
||||||
|
this.userRepository = userRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run(String... args) throws Exception {
|
||||||
|
// Iterate over all users and create 5 random trips for each of the last 5 weeks
|
||||||
|
userRepository.findAll().forEach(user -> {
|
||||||
|
for (int week = 0; week < 5; week++) {
|
||||||
|
for (int i = 0; i < 5; i++) {
|
||||||
|
// Create trips within each week's time range
|
||||||
|
long daysAgo = week * 7 + (long) (Math.random() * 7);
|
||||||
|
NewTripDTO newTrip = TripFactory.randomNewTripDTO(
|
||||||
|
java.time.Instant.now().minus(java.time.Duration.ofDays((long) (Math.random() * 30))));
|
||||||
|
tripService.addTrip(user, newTrip);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package SuMoC.backend.seed.user;
|
||||||
|
|
||||||
|
import SuMoC.backend.security.dtos.UserRegistrationDTO;
|
||||||
|
import SuMoC.backend.security.services.AuthenticationService;
|
||||||
|
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;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@Profile("dev")
|
||||||
|
@Order(1)
|
||||||
|
public class DevUserSeeder implements CommandLineRunner {
|
||||||
|
|
||||||
|
private final AuthenticationService authenticationService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
public DevUserSeeder(AuthenticationService authenticationService) {
|
||||||
|
this.authenticationService = authenticationService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run(String... args) throws Exception {
|
||||||
|
UserRegistrationDTO user1 = UserRegistrationDTO.builder()
|
||||||
|
.email("user1@email.com")
|
||||||
|
.publicName("Nutzer 1 Public")
|
||||||
|
.privateName("Nutzer 1 Privat")
|
||||||
|
.password("password1")
|
||||||
|
.build();
|
||||||
|
authenticationService.registerUser(user1);
|
||||||
|
UserRegistrationDTO user2 = UserRegistrationDTO.builder()
|
||||||
|
.email("user2@email.com")
|
||||||
|
.publicName("Nutzer 2 Public")
|
||||||
|
.privateName("Nutzer 2 Privat")
|
||||||
|
.password("password2")
|
||||||
|
.build();
|
||||||
|
authenticationService.registerUser(user2);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package SuMoC.backend.suggestion.config;
|
||||||
|
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Component
|
||||||
|
@ConfigurationProperties(prefix = "adhocsuggestion")
|
||||||
|
public class AdHocSuggestionProperties {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Maximum time after which an uploaded trip is considered recent enough to send
|
||||||
|
* an alternative routing suggestion for if available.
|
||||||
|
*/
|
||||||
|
private Integer recentTripThresholdSeconds = 60 * 60;
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package SuMoC.backend.suggestion.services;
|
||||||
|
|
||||||
|
|
||||||
|
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
|
||||||
|
import SuMoC.backend.routing.dtos.RoutingPreferencesDTO;
|
||||||
|
import SuMoC.backend.routing.services.RoutingService;
|
||||||
|
import SuMoC.backend.suggestion.config.AdHocSuggestionProperties;
|
||||||
|
import SuMoC.backend.trip.models.Trip;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.scheduling.annotation.Async;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AdHocSuggestionService {
|
||||||
|
|
||||||
|
private final RoutingService routingService;
|
||||||
|
|
||||||
|
private final AdHocSuggestionProperties adHocSuggestionProperties;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Receives a trip a user has just uploaded, if it is a recent trip and there is a more sustainable alternative,
|
||||||
|
* schedules a notification to push to the user.
|
||||||
|
*/
|
||||||
|
@Async
|
||||||
|
public void checkNewTripForNotifiedAlternativeSuggestion(Trip newTrip) {
|
||||||
|
if (!isRecentTrip(newTrip)) return;
|
||||||
|
|
||||||
|
var viableAlternatives = routingService.determineAlternativeRoutesAdHoc(alternativeRequestFromTrip(newTrip));
|
||||||
|
|
||||||
|
// check if there are viable alternative routings
|
||||||
|
// if yes, generate notification
|
||||||
|
// TODO notification generator
|
||||||
|
// schedule send of notification
|
||||||
|
// TODO sending of notification
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isRecentTrip(Trip trip) {
|
||||||
|
long secondsSinceTripCompletion = Instant.now().getEpochSecond() - trip.getEndTime().getEpochSecond();
|
||||||
|
return secondsSinceTripCompletion < adHocSuggestionProperties.getRecentTripThresholdSeconds();
|
||||||
|
}
|
||||||
|
|
||||||
|
private RoutingAlternativeRequestDTO alternativeRequestFromTrip(Trip trip) {
|
||||||
|
// TODO for now we assume the preferences here, it would be better if we store these per user
|
||||||
|
var preferences = new RoutingPreferencesDTO();
|
||||||
|
return RoutingAlternativeRequestDTO.builder()
|
||||||
|
.originLat(trip.getStartLatitude())
|
||||||
|
.originLon(trip.getStartLongitude())
|
||||||
|
.destinationLat(trip.getEndLatitude())
|
||||||
|
.destinationLon(trip.getEndLongitude())
|
||||||
|
.arrivalTime(trip.getEndTime())
|
||||||
|
.departureTime(trip.getStartTime())
|
||||||
|
.routingPreferencesDTO(preferences).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package SuMoC.backend.trend;
|
||||||
|
|
||||||
|
import SuMoC.backend.trend.enums.*;
|
||||||
|
import SuMoC.backend.user.models.User;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class TrendDetection {
|
||||||
|
private User user;
|
||||||
|
private TrendTimespan timespan;
|
||||||
|
private TrendType type;
|
||||||
|
private StatAttribute attribute;
|
||||||
|
private DeltaType deltaType;
|
||||||
|
private double changeValue;
|
||||||
|
|
||||||
|
public TrendConnotation getTrendConnotation() {
|
||||||
|
if (this.type == TrendType.INCREASING) {
|
||||||
|
return switch (attribute) {
|
||||||
|
case CAR_DISTANCE -> TrendConnotation.NEGATIVE;
|
||||||
|
default -> TrendConnotation.NEUTRAL;
|
||||||
|
};
|
||||||
|
} else if (type == TrendType.DECREASING) {
|
||||||
|
return switch (attribute) {
|
||||||
|
case CAR_DISTANCE -> TrendConnotation.POSITIVE;
|
||||||
|
default -> TrendConnotation.NEUTRAL;
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
return TrendConnotation.NEUTRAL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package SuMoC.backend.trend;
|
||||||
|
|
||||||
|
import SuMoC.backend.trend.models.WeeklyMobilityStats;
|
||||||
|
import SuMoC.backend.trend.models.WeeklyMobilityStatsId;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.data.jpa.repository.Query;
|
||||||
|
import org.springframework.data.repository.query.Param;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface WeeklyMobilityStatsRepository extends JpaRepository<WeeklyMobilityStats, WeeklyMobilityStatsId> {
|
||||||
|
|
||||||
|
@Query("SELECT wms FROM WeeklyMobilityStats wms JOIN FETCH wms.user WHERE wms.year = :year AND wms.weekNumber = :weekNumber")
|
||||||
|
List<WeeklyMobilityStats> findAllByYearAndWeekNumberWithUser(@Param("year") Integer year, @Param("weekNumber") Integer weekNumber);
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package SuMoC.backend.trend.config;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Component
|
||||||
|
@ConfigurationProperties(prefix = "trenddetection")
|
||||||
|
public class TrendDetectionProperties {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Minimum percentage change to detect a positive trend (e.g., 25.0 for 25%)
|
||||||
|
*/
|
||||||
|
private double positiveThreshold = 25.0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Minimum percentage change to detect a negative trend (e.g., -25.0 for -25%)
|
||||||
|
*/
|
||||||
|
private double negativeThreshold = -25.0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package SuMoC.backend.trend.enums;
|
||||||
|
|
||||||
|
public enum DeltaType {
|
||||||
|
ABSOLUTE,
|
||||||
|
PERCENTAGE
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package SuMoC.backend.trend.enums;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents statistical attributes a detected trend can pertain to.
|
||||||
|
*/
|
||||||
|
public enum StatAttribute {
|
||||||
|
CAR_DISTANCE,
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package SuMoC.backend.trend.enums;
|
||||||
|
|
||||||
|
public enum TrendConnotation {
|
||||||
|
POSITIVE,
|
||||||
|
NEGATIVE,
|
||||||
|
NEUTRAL
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package SuMoC.backend.trend.enums;
|
||||||
|
|
||||||
|
public enum TrendTimespan {
|
||||||
|
WEEKLY,
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package SuMoC.backend.trend.enums;
|
||||||
|
|
||||||
|
public enum TrendType {
|
||||||
|
INCREASING,
|
||||||
|
DECREASING,
|
||||||
|
STABLE
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package SuMoC.backend.trend.models;
|
||||||
|
|
||||||
|
import SuMoC.backend.trend.enums.StatAttribute;
|
||||||
|
import SuMoC.backend.user.models.User;
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.*;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "weekly_mobility_stats")
|
||||||
|
@IdClass(WeeklyMobilityStatsId.class)
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class WeeklyMobilityStats {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@ManyToOne
|
||||||
|
@JoinColumn(name = "user_id", nullable = false)
|
||||||
|
private User user;
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Integer year;
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Integer weekNumber;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Double totalDistance;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Integer tripCount;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Double sumMobilityScore;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The average mobility score for the week. sumMobilityScore / tripCount
|
||||||
|
*/
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Double averageMobilityScore;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Long sumMetersTraveled = 0L;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Long sumMetersWalkingAndCycling = 0L;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Long sumMetersPublicTransport = 0L;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Long sumMetersWalking = 0L;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Long sumMetersBicycle = 0L;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Long sumMetersEscooter = 0L;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Long sumMetersBus = 0L;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Long sumMetersTram = 0L;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Long sumMetersTrain = 0L;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Long sumMetersCar = 0L;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Long sumMetersMotorcycle = 0L;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private Long sumMetersTaxi = 0L;
|
||||||
|
|
||||||
|
public Long getValueFor(StatAttribute attribute) {
|
||||||
|
return switch (attribute) {
|
||||||
|
case CAR_DISTANCE -> sumMetersCar;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package SuMoC.backend.trend.models;
|
||||||
|
|
||||||
|
import SuMoC.backend.user.models.User;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
@EqualsAndHashCode
|
||||||
|
public class WeeklyMobilityStatsId implements Serializable {
|
||||||
|
private User user;
|
||||||
|
private Integer year;
|
||||||
|
private Integer weekNumber;
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package SuMoC.backend.trend.services;
|
||||||
|
|
||||||
|
import SuMoC.backend.trend.WeeklyMobilityStatsRepository;
|
||||||
|
import SuMoC.backend.trend.statcalculation.WeeklyMobilityStatsCalculator;
|
||||||
|
import SuMoC.backend.trip.TripRepository;
|
||||||
|
import SuMoC.backend.trip.models.Trip;
|
||||||
|
import jakarta.transaction.Transactional;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.time.DayOfWeek;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Transactional
|
||||||
|
public class StatTableUpdateService {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(StatTableUpdateService.class);
|
||||||
|
|
||||||
|
private final TripRepository tripRepository;
|
||||||
|
|
||||||
|
private final WeeklyMobilityStatsRepository weeklyMobilityStatsRepository;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculates weekly mobility stats for the week of a given LocalDate.
|
||||||
|
*/
|
||||||
|
public void updateWeeklyMobilityStatsForAllUsers(LocalDate week) {
|
||||||
|
logger.info("Starting calculation of weekly mobility stats for all users.");
|
||||||
|
// Get all trips of the last full week
|
||||||
|
LocalDate weekStart = week.with(DayOfWeek.MONDAY);
|
||||||
|
LocalDate weekEnd = weekStart.plusWeeks(1);
|
||||||
|
LocalDateTime startDateTime = weekStart.atStartOfDay();
|
||||||
|
LocalDateTime endDateTime = weekEnd.atStartOfDay();
|
||||||
|
List<Trip> trips = tripRepository.findValidTripsInWeek(startDateTime, endDateTime);
|
||||||
|
|
||||||
|
// Groupy trips by userId
|
||||||
|
// TODO verify that we correctly set up the repository find method to avoid querying each trip's user separately (N+1 problem)
|
||||||
|
Map<Long, List<Trip>> tripsByUser = trips.stream()
|
||||||
|
.collect(Collectors.groupingBy(trip -> trip.getUser().getId()));
|
||||||
|
|
||||||
|
// Calc last full week passed
|
||||||
|
Integer year = week.getYear();
|
||||||
|
Integer weekNumber = week.get(java.time.temporal.IsoFields.WEEK_OF_WEEK_BASED_YEAR);
|
||||||
|
|
||||||
|
// For each user that made at least one trip, calculate weekly mobility stats and save to DB
|
||||||
|
for (Map.Entry<Long, List<Trip>> entry : tripsByUser.entrySet()) {
|
||||||
|
Long userId = entry.getKey();
|
||||||
|
List<Trip> userTrips = entry.getValue();
|
||||||
|
var stats = WeeklyMobilityStatsCalculator.calculateStats(year, weekNumber, userTrips);
|
||||||
|
weeklyMobilityStatsRepository.save(stats);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info("Finished calculation of weekly mobility stats for all users.");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
package SuMoC.backend.trend.services;
|
||||||
|
|
||||||
|
import SuMoC.backend.trend.TrendDetection;
|
||||||
|
import SuMoC.backend.trend.WeeklyMobilityStatsRepository;
|
||||||
|
import SuMoC.backend.trend.config.TrendDetectionProperties;
|
||||||
|
import SuMoC.backend.trend.enums.DeltaType;
|
||||||
|
import SuMoC.backend.trend.enums.StatAttribute;
|
||||||
|
import SuMoC.backend.trend.enums.TrendTimespan;
|
||||||
|
import SuMoC.backend.trend.enums.TrendType;
|
||||||
|
import SuMoC.backend.trend.models.WeeklyMobilityStats;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class TrendDetectorService {
|
||||||
|
|
||||||
|
private final WeeklyMobilityStatsRepository weeklyMobilityStatsRepository;
|
||||||
|
|
||||||
|
private final TrendDetectionProperties trendDetectionProperties;
|
||||||
|
|
||||||
|
public List<TrendDetection> detectWeeklyTrends(Integer year, Integer weekNumber, StatAttribute attribute) {
|
||||||
|
// Fetch stats for current and previous week
|
||||||
|
List<WeeklyMobilityStats> previousWeekStatsList;
|
||||||
|
if (weekNumber > 1) {
|
||||||
|
previousWeekStatsList = weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber - 1);
|
||||||
|
} else {
|
||||||
|
// we are forgetting about week 53 here, but it's rare enough to ignore for now
|
||||||
|
previousWeekStatsList = weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year - 1, 52);
|
||||||
|
}
|
||||||
|
List<WeeklyMobilityStats> currentWeekStatsList = weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber);
|
||||||
|
|
||||||
|
// Convert to maps for easy userId-based lookup
|
||||||
|
Map<Long, WeeklyMobilityStats> previousWeekStats = previousWeekStatsList.stream()
|
||||||
|
.collect(Collectors.toMap(stats -> stats.getUser().getId(), stats -> stats));
|
||||||
|
|
||||||
|
Map<Long, WeeklyMobilityStats> currentWeekStats = currentWeekStatsList.stream()
|
||||||
|
.collect(Collectors.toMap(stats -> stats.getUser().getId(), stats -> stats));
|
||||||
|
|
||||||
|
// Detect trends for provided attribute
|
||||||
|
List<TrendDetection> detectedTrends = new ArrayList<>();
|
||||||
|
for (Map.Entry<Long, WeeklyMobilityStats> entry : currentWeekStats.entrySet()) {
|
||||||
|
Long userId = entry.getKey();
|
||||||
|
WeeklyMobilityStats currentStats = entry.getValue();
|
||||||
|
WeeklyMobilityStats previousStats = previousWeekStats.get(userId);
|
||||||
|
|
||||||
|
if (previousStats != null) {
|
||||||
|
double currentValue = currentStats.getValueFor(attribute);
|
||||||
|
double previousValue = previousStats.getValueFor(attribute);
|
||||||
|
|
||||||
|
if (previousValue != 0) {
|
||||||
|
double percentageChange = ((currentValue - previousValue) / previousValue) * 100.0;
|
||||||
|
|
||||||
|
if (percentageChange >= trendDetectionProperties.getPositiveThreshold()) {
|
||||||
|
detectedTrends.add(new TrendDetection(
|
||||||
|
currentStats.getUser(),
|
||||||
|
TrendTimespan.WEEKLY,
|
||||||
|
TrendType.INCREASING,
|
||||||
|
StatAttribute.CAR_DISTANCE,
|
||||||
|
DeltaType.PERCENTAGE,
|
||||||
|
percentageChange
|
||||||
|
));
|
||||||
|
} else if (percentageChange <= trendDetectionProperties.getNegativeThreshold()) {
|
||||||
|
detectedTrends.add(new TrendDetection(
|
||||||
|
previousStats.getUser(),
|
||||||
|
TrendTimespan.WEEKLY,
|
||||||
|
TrendType.DECREASING,
|
||||||
|
StatAttribute.CAR_DISTANCE,
|
||||||
|
DeltaType.PERCENTAGE,
|
||||||
|
percentageChange
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return detectedTrends;
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user