270 Commits
Author SHA1 Message Date
Elias Harb 4063160133 TripSeeder removed
LocationBasedServices/sumoc-backend/pipeline/pr-main This commit looks good
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-25 18:54:20 +01:00
Elias Harb 427267c4bf Revert "Merge branch 'testPhase' of https://project.nes.uni-due.de/gitea/laaser/sumoc-backend into testPhase"
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
LocationBasedServices/sumoc-backend/pipeline/pr-main This commit looks good
This reverts commit 82b9ae15d9, reversing
changes made to 29e4096e95.
2026-02-25 18:41:10 +01:00
Elias Harb 82b9ae15d9 Merge branch 'testPhase' of https://project.nes.uni-due.de/gitea/laaser/sumoc-backend into testPhase
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-25 18:40:22 +01:00
Elias Harb 29e4096e95 Setting up Gamification for test phase 2026-02-25 18:40:05 +01:00
Elias Harb 1d2c04d95c Setting up Gamification for test phase
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-25 18:37:04 +01:00
harb 29956d0b92 Merge pull request 'Bug fix: getPicture Endpoint' (#24) from ChallengesDummyPics into main
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Reviewed-on: #24
2026-02-25 01:58:26 +01:00
Elias Harb 932fc88b2e Bug fix: getPicture Endpoint
LocationBasedServices/sumoc-backend/pipeline/pr-main Build queued...
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
- got error that object was too large for transaction ... again
2026-02-25 01:55:10 +01:00
harb d7cb3c0e8e Merge pull request 'add challenge Dummy picture' (#23) from ChallengesDummyPics into main
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Reviewed-on: #23
2026-02-25 00:23:27 +01:00
Elias Harb 7c347caea9 add challenge Dummy picture
LocationBasedServices/sumoc-backend/pipeline/pr-main Build queued...
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-25 00:17:35 +01:00
kakoschke 29fb04d6ec Merge pull request 'make reset password Kotlin/Android app functional' (#22) from passwordResetRefactoring into main
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Reviewed-on: #22

passt!
2026-02-23 18:47:33 +01:00
Elias Harb 82014b1d9c make reset password Kotlin/Android app functional
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
LocationBasedServices/sumoc-backend/pipeline/pr-main This commit looks good
- small refactor for resetPassword
2026-02-23 18:30:15 +01:00
neuhauss 57e9beb33f Merge pull request 'WIP FirebaseMessageBuilder.java adaptiert, sodass auch iOS Apps Push Benachrichtigungen erhalten und intercepten können.' (#21) from add-ios-notification into main
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Reviewed-on: #21
2026-02-23 11:47:24 +01:00
neuhauss 30de34b47a Merge branch 'main' into add-ios-notification
LocationBasedServices/sumoc-backend/pipeline/pr-main This commit looks good
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-23 11:40:49 +01:00
neuhauss 007680fccf include supporting trip ids in regulartrip dto that is used for carrousel display
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-22 18:43:02 +01:00
neuhauss cf7d847993 bugfix, stupid back and forth conversion of instant and localtime caused wrong resulting time 2026-02-22 18:21:49 +01:00
neuhauss dad0077279 bugfix, arrival and departure were mixed up 2026-02-22 18:04:34 +01:00
neuhauss 0bc692d64a fix logic bug, no exception should be thrown if weather is bad 2026-02-22 17:51:06 +01:00
neuhauss 16bf41beaa add endpoint to delete all mobility data of a user 2026-02-22 17:39:49 +01:00
neuhauss 98cb2536a2 add endpoint to delete all trips of user 2026-02-22 17:26:42 +01:00
neuhauss 776b8857b6 add endpoint to delete trip with given id 2026-02-22 17:23:38 +01:00
Daniel b6ce9a73ce FirebaseMessageBuilder.java adaptiert, sodass auch iOS Apps Push Benachrichtigungen erhalten und intercepten können.
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
LocationBasedServices/sumoc-backend/pipeline/pr-main This commit looks good
2026-02-20 16:26:22 +01:00
Daniel 906050ad89 openapi.yaml
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-20 12:38:13 +01:00
Daniel 46a6b2fb7a added OtpRequestDTO to fix RequestBody for @PostMapping("/request-otp-for-password-reset")
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-20 12:28:13 +01:00
Daniel e333b3b9ce Saving encoded OTP instead of raw OTP with PasswordEncoder.encode()
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-19 13:57:13 +01:00
Daniel b64eff7ae6 set localhost and port for MailService
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-19 12:37:23 +01:00
Daniel f04e5d7c06 summary and desc appi
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-18 18:02:41 +01:00
Daniel 4fb02a3f69 test refactor
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-18 15:50:04 +01:00
Daniel e1f8cf123b passwordformat checker, test for checkup
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-18 15:37:02 +01:00
Daniel cc6028bab5 brevo smtp server (300 mails/day free)
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Test written for changing Password based on otp

some other stuff
2026-02-18 15:06:21 +01:00
Daniel 80ba4c33b6 OTP Code updated to 6 Digit Code, was 5 before.
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-17 20:34:21 +01:00
Daniel 3d4f6a4d26 Working Implementation for resetting passwords based on a One Time Passcode (OTP). first request Token by stating your email to /request-password-forgot. OTP will be sent via email. Then just type in email, the OTP and a new password to /reset-password.
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
IMPORTANT - EMAIL SETUP in application.properties (if gmail):
#mail provider
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=<email>
# Nutze bei Gmail ein "App-Passwort", nicht dein normales (16 stellig)
spring.mail.password=xxxx xxxx xxxx xxxx
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
2026-02-17 18:56:59 +01:00
laaser 2c0dfaf77b Bugfix:
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
- Trips brauchten weitere Annotation um zyklische Abhängigkeit zu verhindern
- Anpassen FriendCode länge und generierung
2026-02-16 15:50:10 +01:00
laaser 3051bda1e4 Bugfix: Challenges make Map mutable -> hashmap<>(Map.of)
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-10 20:19:20 +01:00
laaser a2acdd88f8 Merge branch 'main' into deploy 2026-02-10 20:06:57 +01:00
laaser 9e41239ef8 Merge branch 'main' of https://project.nes.uni-due.de/gitea/lbs/sumoc-backend
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-10 20:03:13 +01:00
laaser 8d65e35f88 Bugfix: fix image, badge und challenge loading to lazy load. Set Email to lowercase 2026-02-10 20:03:08 +01:00
neuhauss 8f62d853e4 fix check if user is logged in
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-10 16:00:15 +01:00
neuhauss d5c8342729 reset db
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-10 15:39:50 +01:00
neuhauss 9d5ad0ca6d Merge branch 'main' into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-10 15:30:11 +01:00
neuhauss a2aa22a34a persist data 2026-02-10 15:30:06 +01:00
neuhauss 82ddcb193c stop resetting db 2026-02-10 15:29:45 +01:00
neuhauss 8b2de7b9c3 filter out transit alternatives that make no sense to user when walking inside transit route is > direct walking
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-10 15:28:33 +01:00
neuhauss c165fce833 seed leaderboards with dummy data 2026-02-10 14:56:19 +01:00
neuhauss 20d948bcdf add endpoint to invalidate notification token 2026-02-10 14:09:26 +01:00
neuhauss 1b549cc5fc remove unnecessary geocoding for regular trip centers -> we already have address of alternative route -> saves on geocoding calls 2026-02-10 13:39:30 +01:00
neuhauss 18e8d10f6b allow geocoding from non logged in users 2026-02-10 13:34:49 +01:00
neuhauss e84269390e Merge remote-tracking branch 'origin/deploy' into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-10 12:02:20 +01:00
neuhauss 5eb157b435 reset broken db 2026-02-10 12:02:11 +01:00
neuhauss b95355c10f parallelize regular trip detection for massively improved performance
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-09 14:30:32 +01:00
neuhauss f7d7f6bc53 regular trip calculation: batch db writes for improved performance 2026-02-09 13:56:59 +01:00
neuhauss a401b9a6c1 increase tolerated additinoal travel time for testing phase of app 2026-02-09 13:27:13 +01:00
laaser cc6990a2a1 Bugfix: Last commit didnt fix profile upload. I fucked up. Hope this does :')
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-08 03:59:13 +01:00
laaser f88f5a03ef Bugfix: Profile upload did have problems with the request annotation. remove the prefix manually
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-08 03:34:52 +01:00
laaser d5ef781162 Bugfix: Change setProfilePicture to requestBody to fix HTTP 415
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-08 02:44:43 +01:00
laaser 1c6caa71ce Bugfix: ChallengeMapper couldnt handle empty images
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-08 02:39:22 +01:00
harb b1ac1619d2 Merge pull request 'fix null pointer with getting challenge with null image' (#17) from main3 into main
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Reviewed-on: #17
2026-02-06 01:51:52 +01:00
Elias Harb 6f9f7c1ba0 fix null pointer with getting challenge with null image
LocationBasedServices/sumoc-backend/pipeline/pr-main Build queued...
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-06 01:50:19 +01:00
neuhauss f961b3c2b3 add regular trip notifications to carrousel system
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-05 19:33:55 +01:00
neuhauss 2d39c0bef8 generate regular stupid car trips by default to trigger regular trip alternatives 2026-02-05 19:33:42 +01:00
neuhauss 1a8961831f fix bug 2026-02-05 19:33:08 +01:00
neuhauss 82017e3c50 add triggering mock trip to factory 2026-02-05 19:32:40 +01:00
neuhauss f0dd32c22f update stat service + repo to use instant 2026-02-05 19:32:29 +01:00
neuhauss 99b5882c82 implemented alternative carrousel system, already working with alternative notifications for ad hoc alternatives 2026-02-05 18:06:23 +01:00
neuhauss b60e900e24 Merge remote-tracking branch 'origin/main'
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-05 11:57:48 +01:00
neuhauss fb41f80061 add NotificationLimiter to avoid sending too many notifications per hour
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-05 11:56:24 +01:00
laaser e2a6b5919a Endpoint to get own XP
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-03 20:19:47 +01:00
laaser 60d335f16d challenges
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-03 20:07:47 +01:00
neuhauss 4fe86b6845 remove call to currentUserService to prevent 401 on not logged in users
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-02 10:39:07 +01:00
neuhauss c43101e5dc test bugfix
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-02 10:26:56 +01:00
neuhauss d882c8e3b3 align with directions controller for testing
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-02 10:21:32 +01:00
neuhauss 14cb4f4f88 reorder routes
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-02 10:11:06 +01:00
neuhauss e5e6dc9e2a Merge branch 'routing_endpoint'
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-01 19:37:22 +01:00
neuhauss 8eaea03b47 fix bug, carta needs to handle arrivalTime OR departureTime being null
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-01 19:36:08 +01:00
neuhauss ff4d352e08 extend todo comment
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-01 19:23:45 +01:00
neuhauss 657acbc736 refactor routeDTO creation + handle different time cases 2026-02-01 19:15:00 +01:00
neuhauss 6393a4a650 reformat RouteDTO 2026-02-01 19:14:29 +01:00
neuhauss cb397e7e63 implement routing/drections endpoint for requesting routes without alternatives logic, includes refactoring of previous alternative routing logic into carta DirectionsService to reuse code
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-01 18:07:37 +01:00
harb 69347f8f56 Merge pull request 'StatsListAdd' (#16) from StatsListAdd into main
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Reviewed-on: #16
2026-02-01 01:06:35 +01:00
Elias Harb e68e163214 Prevent Json nesting for stats
LocationBasedServices/sumoc-backend/pipeline/pr-main Build queued...
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
- stats are cyclic which is awful for transmitting the stats to the client

Could not write JSON: Document nesting depth (1001) exceeds the maximum allowed (1000, from StreamWriteConstraints.getMaxNestingDepth())
2026-02-01 00:52:55 +01:00
Elias Harb 5e16591913 Added Endpoint to retrieve all stats 2026-01-31 23:26:14 +01:00
neuhauss 6aaff14c0d Merge branch 'main' into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-30 16:22:22 +01:00
neuhauss 1b39185454 Merge branch 'notifications_for_friendship_request'
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-30 16:22:16 +01:00
neuhauss 43ab63f77d add testing endpoint for friendship request notification
LocationBasedServices/sumoc-backend/pipeline/head Build started...
2026-01-30 16:22:10 +01:00
neuhauss d72a12d089 Merge branch 'main' into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-30 16:12:39 +01:00
neuhauss 39e385cac3 add testing endpoint for regular trip detection (very slow yet)
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-30 16:11:55 +01:00
neuhauss e41fff0840 add correct test for dow conversion 2026-01-30 16:11:29 +01:00
neuhauss 256145f65b fix bug in day of week conversion 2026-01-30 16:11:17 +01:00
neuhauss c636d04fea fix test by switching to springboottest 2026-01-30 12:30:07 +01:00
neuhauss 5490958d6e add README for notification system 2026-01-30 11:50:10 +01:00
neuhauss 06b35c13b6 add notification for received friendship request 2026-01-30 11:49:53 +01:00
neuhauss 48063d442c switch to currentUserService 2026-01-30 11:49:34 +01:00
harb 29b6ac052f Merge pull request 'add friendCode to userDTOs' (#15) from friendCodeFix into main
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Reviewed-on: #15
2026-01-29 23:40:27 +01:00
Elias Harb c3f291a08b add friendCode to userDTOs
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
LocationBasedServices/sumoc-backend/pipeline/pr-main Build started...
2026-01-29 23:21:57 +01:00
laaser 30fe944387 Merge branch 'deploy' of https://project.nes.uni-due.de/gitea/lbs/sumoc-backend into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-29 20:53:44 +01:00
laaser 43cf5239fc Merge branch 'deploy' 2026-01-29 20:51:38 +01:00
laaser 53cfce5359 Adding profile pictures to leaderboards. adapting privacy visibility to leaderboards.
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-29 20:48:08 +01:00
laaser fb94421247 Fix Tests:
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
1. test/application.properties: add keystore and change geocoding
2. change List in RoutingPreferences to mutable type
2026-01-28 20:13:24 +01:00
neuhauss 4567ca16f0 Merge branch 'route_alternatives'
LocationBasedServices/sumoc-backend/pipeline/head There was a failure building this commit
2026-01-28 18:04:30 +01:00
neuhauss 88fcbfb728 fix entrypoint
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-28 10:16:25 +01:00
neuhauss 400c31cc34 fix entrypoint
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-28 10:16:01 +01:00
neuhauss a8f95b680a fix entrypoint
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-28 10:15:43 +01:00
neuhauss f051efa9eb Merge branch 'main' into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-27 21:41:59 +01:00
neuhauss 522393bdd7 Merge remote-tracking branch 'origin/main'
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-27 21:40:35 +01:00
neuhauss 768acc1841 update adminer port
LocationBasedServices/sumoc-backend/pipeline/head Build started...
2026-01-27 21:39:59 +01:00
laaser 7bbbf903de Merge branch 'main' into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-27 17:52:03 +01:00
laaser 850410ec46 Fix BadgeSeeder
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-27 17:44:16 +01:00
laaser 85ca90fa7c Merge branch 'main' into cachingAndPP
# Conflicts:
#	src/main/java/SuMoC/backend/gamification/badges/BadgeController.java
#	src/main/java/SuMoC/backend/gamification/scoretable/LeaderboardController.java
#	src/main/java/SuMoC/backend/gamification/scoretable/LeaderboardService.java
#	src/main/java/SuMoC/backend/user/controller/UserController.java
#	src/main/java/SuMoC/backend/user/models/User.java
2026-01-27 16:51:14 +01:00
laaser 46a8ca67a0 Fix tests and profile picture 2026-01-27 15:55:16 +01:00
neuhauss a691e911a2 Merge branch 'main' into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-27 11:15:41 +01:00
neuhauss c6fe80145b add test user for all pg members
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-27 11:15:18 +01:00
neuhauss 5b6cc1c679 test of adminer container
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-27 09:06:53 +01:00
laaser 43e91670b3 repair badge images -> set to Base64 for transport
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-27 00:37:33 +01:00
neuhauss e2e1cc48a0 refactor to proper unit test
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-26 17:43:18 +01:00
neuhauss 0564733c39 stop resetting db
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-26 16:25:24 +01:00
neuhauss 9aed0a2703 Merge branch 'main' into deploy 2026-01-26 16:24:37 +01:00
neuhauss fb0989ef95 run application in berlin timezone
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-26 16:24:15 +01:00
neuhauss 607ce804da seed davids test user 2026-01-26 16:24:03 +01:00
laaser 72efa472fa Adding images and category to badges 2026-01-26 01:59:28 +01:00
neuhauss 23e5affa71 Merge branch 'main' into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
# Conflicts:
#	docker-compose.yml
2026-01-25 19:49:04 +01:00
neuhauss 9b475a37e1 Merge branch 'route_alternatives'
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
# Conflicts:
#	.gitignore
#	docker-compose.yml
2026-01-25 18:43:43 +01:00
neuhauss fb49fa2130 prevent error when firebase is already inited
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-25 18:22:17 +01:00
laaser 00cbff062e Merge branch 'main' into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-23 15:12:02 +01:00
laaser edabef4fb3 Manually auth for Leaderboard
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-23 15:09:22 +01:00
laaser 75af061871 Merge main
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-23 14:29:01 +01:00
laaser b4d6c1ea13 Totally unsave loggingpage
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-23 14:24:01 +01:00
neuhauss cd07bf16cf add entrypoint script to decrypt secrets on application startup with key provided as env
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-23 12:32:53 +01:00
neuhauss de2f7af6c7 Merge branch 'deploy' into test_firebase_key_decryption 2026-01-23 10:34:29 +01:00
neuhauss a2be274ca3 add encrypted fcm key for messaging service account 2026-01-23 10:34:22 +01:00
laaser cc15245680 Forgot to upload
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-23 10:29:56 +01:00
laaser 0d7f97af5e Bugfix: keysave should work now on docker and device
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-23 10:05:46 +01:00
neuhauss ebc5de34cd try to get rid of postgres15 db
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-23 00:29:11 +01:00
neuhauss c117b7a049 now wipe db volume again
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-23 00:19:55 +01:00
neuhauss c61d870173 fix docker compose
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-23 00:14:29 +01:00
neuhauss d56bdd97d7 deactivate firebase
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-23 00:08:12 +01:00
neuhauss 8e0c2cfc3e try fix db
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-23 00:01:47 +01:00
neuhauss 321b7c8035 fix db volume name
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-22 23:43:39 +01:00
neuhauss b18878fcb2 fix db volume name
LocationBasedServices/sumoc-backend/pipeline/head There was a failure building this commit
2026-01-22 23:39:41 +01:00
neuhauss 0cdf4a09f3 deploy with logs
LocationBasedServices/sumoc-backend/pipeline/head There was a failure building this commit
2026-01-22 23:25:50 +01:00
neuhauss e7b6295dad deploy with logs
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-22 23:19:26 +01:00
neuhauss 3c83274d4f switch back to docker volumes for db for drop access
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-22 23:12:19 +01:00
neuhauss 6b56ecb5cb deploy
LocationBasedServices/sumoc-backend/pipeline/head There was a failure building this commit
2026-01-22 23:05:40 +01:00
neuhauss add016b51e Merge branch 'refs/heads/deploy' into test_firebase_key_decryption 2026-01-22 22:47:30 +01:00
neuhauss 98d940625b deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-22 22:43:20 +01:00
neuhauss 2af94e6b65 deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-22 22:37:47 +01:00
neuhauss 7253576a53 fix missing import 2026-01-22 22:36:35 +01:00
neuhauss a0a3dd4e28 fix typo
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-22 22:29:00 +01:00
harb 3f60692987 Merge pull request 'Badge Seeder for initial Badges' (#10) from initialDataForBadges into main
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Reviewed-on: #10
2026-01-22 22:28:05 +01:00
Elias Harb f39d24e2d1 Badge Seeder for initial Badges 2026-01-22 22:28:05 +01:00
neuhauss 94858282da fix typo
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-22 22:20:48 +01:00
neuhauss 6c4a2f7176 using folder instead of docker volumes
LocationBasedServices/sumoc-backend/pipeline/head There was a failure building this commit
2026-01-22 22:00:21 +01:00
neuhauss 90a3297873 reset db + dont copy fcm key until deployed on jenkins credentials
LocationBasedServices/sumoc-backend/pipeline/head There was a failure building this commit
2026-01-22 21:28:35 +01:00
neuhauss 846bbbbea6 Merge branch 'main' into deploy
# Conflicts:
#	docker-compose.yml
#	src/main/resources/application.properties
2026-01-22 21:27:21 +01:00
neuhauss 218ceeada3 Merge branch 'route_alternatives'
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
# Conflicts:
#	src/main/java/SuMoC/backend/user/models/User.java
2026-01-22 19:49:35 +01:00
neuhauss 923a123f33 fix error in jenkinsfile
LocationBasedServices/sumoc-backend/pipeline/head There was a failure building this commit
2026-01-22 19:37:16 +01:00
neuhauss 6f407a26fd test: deploy fcm messaging key on server
LocationBasedServices/sumoc-backend/pipeline/head There was a failure building this commit
2026-01-22 19:34:13 +01:00
neuhauss 1a15dd5a60 fix test by providing properties - ugly but works
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-22 18:57:16 +01:00
neuhauss 76e9251001 switch to using stored users routing preferences in all routing services 2026-01-22 16:29:56 +01:00
neuhauss fb9276ca15 store routingpreferences for each user in database, get and update via service, create with default for new users 2026-01-22 15:59:38 +01:00
laaser 4c1476944a Bugfix:
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
1. /data/ is readonly on macOS -> changed to ./keys/
2. Changed Friendcode Annotation to unique
2026-01-22 14:44:19 +01:00
neuhauss abb8211e16 implement endpoint to request friendships by friendcode 2026-01-22 14:24:48 +01:00
laaser 8e4d6bf820 Fix all Tests
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-22 13:40:26 +01:00
laaser 917ed77a95 Implement Caching and fix minor errors
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-22 09:34:24 +01:00
harb 59a43be9ee Merge pull request 'JWT available after restart' (#9) from JWTFix into main
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Reviewed-on: #9
2026-01-21 20:02:40 +01:00
Elias Harb 14e77cbf0f JWT available after restart 2026-01-21 20:02:40 +01:00
harb 5d695b35ba Merge pull request 'Badges and states added' (#6) from Badges into main
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Reviewed-on: #6
Reviewed-by: David Neuhauss <david.neuhauss@stud.uni-due.de>
2026-01-21 20:02:25 +01:00
Elias Harb 72828c9a0d added MobilityScore 2026-01-21 20:02:25 +01:00
Elias Harb c70059b366 Badges and states added 2026-01-21 20:02:25 +01:00
neuhauss 3a1752573e merge fixes
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-21 10:34:13 +01:00
neuhauss 2eab549360 Merge branch 'main' into route_alternatives
# Conflicts:
#	src/main/java/SuMoC/backend/security/SecurityConfiguration.java
#	src/main/java/SuMoC/backend/user/models/User.java
#	src/main/resources/application.properties
2026-01-21 10:30:23 +01:00
neuhauss 2b9ce78e1c switch to carta for geocoding but keep docker nominatim as option in case we want to use it
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-21 10:27:23 +01:00
laaser 159c03142a Implemented User Profilepicture | PLEASE check again if implemented right 2026-01-21 02:28:38 +01:00
neuhauss f3bd4dddc2 switch to folders for volumes
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-20 11:07:50 +01:00
neuhauss a78ebbfbb5 create separate docker compose for local full dockerized execution 2026-01-20 11:07:35 +01:00
neuhauss 2f88a611b8 update jenkinsfile - no db reset
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-20 11:03:08 +01:00
neuhauss 8d0210b210 Merge branch 'main' into deploy
LocationBasedServices/sumoc-backend/pipeline/head There was a failure building this commit
2026-01-20 10:59:47 +01:00
neuhauss 7986f39d36 Merge remote-tracking branch 'origin/deploy' into deploy 2026-01-20 10:59:19 +01:00
neuhauss c8410a8231 update jenkinsfile to reset db 2026-01-20 10:59:06 +01:00
laaser d92b71179a Bugfix: Fix wrong OpenAPI schemas
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-20 01:28:11 +01:00
laaser 95e496ab85 Merge remote-tracking branch 'origin/deploy' into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-19 15:15:11 +01:00
laaser 140945dbc2 Merge remote-tracking branch 'origin/main' into deploy 2026-01-19 15:14:43 +01:00
laaser 0752a59fd9 Bugfix: BadgeController took a parameter, which was never used. OpenAPI couldn't build
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-19 13:12:53 +01:00
laaser 106bdbe220 Merge pull request 'Bugfix: PrivacyService didnt load UserRepository' (#4) from main into deploy
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Reviewed-on: #4
2026-01-19 12:53:37 +01:00
laaser 1cca645696 Bugfix: PrivacyService didnt load UserRepository
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
LocationBasedServices/sumoc-backend/pipeline/pr-deploy Build started...
2026-01-19 12:45:42 +01:00
neuhauss 7098fbe8cc revert to 8080
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-17 18:32:32 +01:00
laaser 9f854ce3ab test
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-17 18:04:06 +01:00
laaser 1369f4f25d change db to drop
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-17 16:12:29 +01:00
laaser 4e11dd2d78 Add role-based access control for gamification endpoints
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-16 17:58:49 +01:00
laaser f8c661ccb6 Enhance user privacy checks and improve error handling in user services
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-16 17:15:25 +01:00
neuhauss d099909aab implement full service chain where scheduled task detects regular trips every day and schedules notifications with better alternatives if available
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-16 13:19:19 +01:00
neuhauss b08d9dd22d add code to convert safely between java's and sql indexes for day of week, verify with test 2026-01-16 11:09:30 +01:00
laaser 8bace01238 Privacy Service for centralized Heuristics
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-16 00:12:14 +01:00
laaser 29a7811c97 Badge Tests
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Add Badge and UserBadge functionality with criteria support and service updates
2026-01-15 19:55:52 +01:00
neuhauss 56e594b625 add tests for regular trip detection algorithm 2026-01-14 17:47:35 +01:00
neuhauss 8ee6992f88 send ad hoc alternative route notifications for recent uploaded trips 2026-01-14 15:34:59 +01:00
neuhauss ddbf925caf log notification send fail reason in db for easier debugging 2026-01-14 15:34:29 +01:00
neuhauss 41f04620ba added devcontroller test endpoint for sending route_adhoc notification 2026-01-14 14:35:32 +01:00
neuhauss ce665d143f add tests for NotificationSchedulerServiceTest
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-13 18:44:27 +01:00
neuhauss 51c742b746 remove builder from TrendDetectionDTO so that trendConnotation can be calculated in constructor 2026-01-13 18:44:12 +01:00
laaser 813390286f Leaderboard Tests
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Refactor FriendshipTestFactory and LeaderboardService: streamline methods and improve readability; update Stats and UserTestFactory for consistency
2026-01-13 18:26:46 +01:00
neuhauss 11ce10a8d8 implemented scheduled tasks and notification scheduler so that whole chain task -> detected trends -> scheduled notification -> notification sent by worker is working 2026-01-13 18:07:15 +01:00
neuhauss 521a4ba957 add notification cleanup task 2026-01-13 17:04:17 +01:00
neuhauss bc3dd9b59b correctly recognize firebase errors when sending exceptions 2026-01-13 16:48:18 +01:00
neuhauss 06aa0ce3cc implemented scheduled worker that processes queued notifications 2026-01-13 16:42:31 +01:00
neuhauss bef418d77d basic firebase notification sending + token registration logic 2026-01-13 14:43:36 +01:00
neuhauss ba642d10a5 add demo endpoint for notification mocks
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-13 12:22:44 +01:00
laaser fd5bdd6083 Merge remote-tracking branch 'origin/main' into gamification/scoretables 2026-01-13 12:14:22 +01:00
neuhauss f1a214b5db Fix test, second route2 should be filtered
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-13 10:56:29 +01:00
neuhauss dd86b857d4 increase acceptable additional travel time for adhoc alternatives
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-13 10:44:41 +01:00
neuhauss c8f667bba7 increase acceptable additional travel time for oncall alternatives
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-13 10:44:20 +01:00
neuhauss 008313d651 add missing carta modality "metro"
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-13 09:47:16 +01:00
neuhauss 7e8edab77a made firebase config optional so backend starts without a key present
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-13 08:50:48 +01:00
neuhauss 23da358686 improvements to regular trip detection algorithm -> next step: write tests that verify approach
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-12 16:32:14 +01:00
neuhauss 474813b2b9 first implementation of iterative greedy algorithm to detect regular trips 2026-01-12 16:19:28 +01:00
neuhauss 160b883bfc add h3 cells to trip model as preparation for route pattern detection
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-11 19:40:46 +01:00
neuhauss 1b74f6125c implement full logic to filter ad hoc route suggestions against weather conditions
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-11 14:00:44 +01:00
laaser 6bb438f786 Refactor Leaderboard functionality: rename methods and endpoints for consistency
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-11 13:34:17 +01:00
neuhauss 4d112a599f alternative filter: fix bug - physical activity thresholds only for phyiscal acitivies 2026-01-10 18:04:21 +01:00
neuhauss a643db3133 implement client for meteo weather api
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-10 17:54:36 +01:00
neuhauss 4fb5d9c5f8 implement client for meteo weather api 2026-01-10 17:53:22 +01:00
neuhauss 1f439338da implement basic structure for ad hoc suggestions where we send user a notification for better alternatives after user finished trip
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
- notification logic still missing
- Weather api missing
2026-01-10 17:09:44 +01:00
neuhauss ea3c941b84 inject alternative filtering properties into filterer for more flexible usage 2026-01-10 17:09:00 +01:00
neuhauss 8e3cb83d27 basic firebase connection + notification structure 2026-01-10 13:56:31 +01:00
neuhauss 4c9b69a0d0 Merge branch 'main' into trend_notifications
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-09 15:56:19 +01:00
neuhauss ea2494db49 override nominatim base url to docker standard when run in full docker setup
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-09 15:56:03 +01:00
neuhauss 86073411b0 Merge branch 'route_alternatives' into trend_notifications
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
# Conflicts:
#	src/main/resources/application.properties
2026-01-09 15:25:59 +01:00
neuhauss 671dabad3b align both dockerfiles + never update nominatim once built
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-09 15:23:43 +01:00
neuhauss b2718efa4c align postgres versions in docker compose files
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-09 14:54:06 +01:00
laaser 0630bdd2a5 Implement scheduled tasks to reset weekly and monthly stats in StatsService
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-08 16:17:21 +01:00
laaser a9bb7cfa33 Refactor score table to leaderboard, update related models and services for consistency
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-08 15:08:28 +01:00
laaser caff26d7ca Implement score table functionality with ScoreTable, ScoreEntry, and ScoreTableService; add Timeframe and ScoreType enums; enhance User and StatsList models for better stats management
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-08 02:51:29 +01:00
neuhauss 0f54353263 refactor filtering logic which determines if additional time of an alternative route isacceptable
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-08 01:47:32 +01:00
neuhauss 41bda73041 routingalternatives: consider transit options 2026-01-08 00:32:50 +01:00
neuhauss 4410c0b3bc Merge branch 'fix_time_handling' into trend_notifications
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
# Conflicts:
#	src/main/java/SuMoC/backend/seed/trip/DevTripSeeder.java
#	src/main/resources/application.properties
2026-01-07 23:59:56 +01:00
neuhauss ca41233397 Merge branch 'fix_time_handling' into route_alternatives
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-07 23:57:27 +01:00
neuhauss e88d651c71 refactor to use Instant instead of LocalDateTime
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-07 23:56:50 +01:00
neuhauss 137923d9a6 RoutingController.java log error message when substituting nominatim with mock data
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-07 20:03:42 +01:00
neuhauss 6e458edd5c implement trend detection logic
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
- for now aimed to detect weekly trends in car distances, easily extendable to all other attributes of the statsm model
- including test
2026-01-07 15:28:35 +01:00
neuhauss ec0615f6df rename service 2026-01-07 13:45:12 +01:00
neuhauss c010f34479 add weekly schedulded task that calculates weekly mobility statistics for each user that made a trip in that week -> basis for deteting trend changes in mobility behaviour
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-06 17:55:04 +01:00
neuhauss 17636f0b65 basic structure for notification system 2026-01-06 17:54:11 +01:00
laaser 266d9ff3bb fix import
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-06 17:38:43 +01:00
laaser bff1659186 implement BadgeController with CRUD operations for badges and update BadgeService for improved error handling
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-06 17:19:18 +01:00
laaser 8c5fff5a3b implement gamification badges system with UserBadge and Badge models, and BadgeService for badge management
# Conflicts:
#	.gitignore
#	src/main/java/SuMoC/backend/user/models/User.java
2026-01-06 17:18:24 +01:00
neuhauss bda244a2e8 Merge pull request 'route_alternatives into main' (#3) from route_alternatives into main
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Reviewed-on: #3
2026-01-06 14:08:34 +01:00
neuhauss dfa5ee9559 add co2emissions to trip model and update tripfactory
LocationBasedServices/sumoc-backend/pipeline/pr-main Build queued...
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-06 14:07:39 +01:00
neuhauss ce7494a95f add coordinates to trip plus switch to lombok getters setters to reduce boilerplate 2026-01-06 14:02:54 +01:00
neuhauss 5c45937fba add lombok-mapstruct-binding dep to prevent errors when using both lombok and mapstruct 2026-01-06 14:02:02 +01:00
neuhauss 80ba8b1c19 RoutingController return mock route dtos if nominatim is not yet up
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-06 10:54:14 +01:00
neuhauss 5e63753bf7 run in dev profile for now, added user and trip seeder for development testing purposes
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-04 18:21:08 +01:00
neuhauss a716986d91 Merge branch 'main' into route_alternatives
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-03 19:28:35 +01:00
neuhauss e93bdde124 add trip validation and invalidation functionality in TripService and TripController
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-03 19:28:21 +01:00
neuhauss 45cf83aa78 add self-action check in FriendshipController to prevent users from blocking or requesting friendship with themselves
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-03 18:57:23 +01:00
neuhauss 6c589a22ac Merge branch 'main' into route_alternatives
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-03 18:52:48 +01:00
neuhauss 1daa400a90 fix two bugs in FriendshipService where wrong dto was returned for all users blocked by sender and repository was not flushed after delete operation
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-03 18:52:34 +01:00
neuhauss 3ae5b85cc0 extend FriendshipServiceTest 2026-01-03 18:51:41 +01:00
neuhauss 5f5365d5bc WIP - RoutingController now no longer returns mock data, working alternative calculation for bike and walking
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Yet to implement: transit routes from carta, consider weather
2026-01-02 17:13:19 +01:00
neuhauss 12aed5ef26 refactor geocoding to service for internal use + return addressdto
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-02 15:11:10 +01:00
neuhauss 0437117d9e Merge branch 'geocoding' into route_alternatives
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-02 14:29:42 +01:00
neuhauss 52788a9c83 update modality names to align with android app + routingservice WIP
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-01-02 14:29:17 +01:00
neuhauss c6dabb9cd9 add a nominatim container to docker setup that is available via GeocodingController to reverse geocode lat / lon to address
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2025-12-30 23:17:01 +01:00
neuhauss 6eb36f5b58 wip routing service
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2025-12-30 18:41:30 +01:00
neuhauss 6bd78c597f update alternative routing dto structure according to meeting results
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2025-12-28 21:53:20 +01:00
neuhauss 54c28ff83a trying to fix carta api specs by hand for better api docs
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2025-12-26 18:35:41 +01:00
neuhauss 980e026fe3 Merge branch 'main' into route_alternatives
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2025-12-26 16:57:02 +01:00
neuhauss 938a618bf2 added fix script for loops in carta api specs + poc alternative endpoint 2025-12-26 16:46:09 +01:00
laaser 3ea13530bc Add OpenAPI documentation generation and update security configuration
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2025-12-24 00:35:05 +01:00
laaser 0a78c302d4 Merge pull request 'test_current' (#2) from test_current into main
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Reviewed-on: #2

Nochmal drüber geschaut. Sieht ok aus.
2025-12-23 12:33:04 +01:00
neuhauss 44c2fc0832 prototypical wrapper for carta client 2025-12-22 20:59:13 +01:00
neuhauss 3f6260edf3 add generated carta client 2025-12-22 18:45:30 +01:00
neuhauss afec6af878 add carta.json 2025-12-18 17:15:39 +01:00
241 changed files with 25859 additions and 714 deletions
+3 -1
View File
@@ -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/
+12
View File
@@ -33,3 +33,15 @@ 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
/secrets/fcm-key.json
/data/keys/jwt-public.pem
/data/keys/jwt-private.pem
/logs/app.log
+9 -2
View File
@@ -17,5 +17,12 @@ COPY --from=build /app/target/*SNAPSHOT.jar app.jar
# Port freigeben # Port freigeben
EXPOSE 8080 EXPOSE 8080
# App starten # Copy entrypoint script
CMD ["java", "-jar", "app.jar"] COPY entrypoint.sh .
RUN chmod +x entrypoint.sh
# Copy secrets
COPY secrets/ ./secrets/
# Start entrypoint first for key decryption
ENTRYPOINT ["./entrypoint.sh"]
Vendored
+14 -1
View File
@@ -16,16 +16,29 @@ node('built-in') {
// deploy the build output on the server // deploy the build output on the server
stage ('Deploy') { stage ('Deploy') {
if (env.BRANCH_NAME == "deploy") { if (env.BRANCH_NAME == "deploy") {
withCredentials([sshUserPrivateKey(credentialsId: "sumoc-server-key", keyFileVariable: "KEYFILE")]) { withCredentials([
sshUserPrivateKey(credentialsId: "sumoc-server-key", keyFileVariable: "KEYFILE")
// file(credentialsId: "firebase-messaging-key", variable: "FIREBASE_MESSAGING_KEYFILE")
]) {
echo "Copy docker images to server ..." echo "Copy docker images to server ..."
sh 'scp -i $KEYFILE .env pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE .env pg-sumoc@apps-dev.nes:~'
sh 'scp -i $KEYFILE docker-compose.yml pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE docker-compose.yml pg-sumoc@apps-dev.nes:~'
sh 'scp -i $KEYFILE docker-load.sh pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE docker-load.sh pg-sumoc@apps-dev.nes:~'
sh 'scp -i $KEYFILE -r docker_images pg-sumoc@apps-dev.nes:~' sh 'scp -i $KEYFILE -r docker_images pg-sumoc@apps-dev.nes:~'
echo "Resetting database..."
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose down -v"'
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"'
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm -f sumoc-backend_postgres_data"'
echo "Load docker images on server ..." echo "Load docker images on server ..."
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"' sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"'
echo "Restarting docker containers on server ..." echo "Restarting docker containers on server ..."
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "sudo systemctl restart sumoc-docker"' sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "sudo systemctl restart sumoc-docker"'
echo "Waiting for containers to start..."
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "sleep 10 && docker ps"'
echo "Database logs:"
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker logs sumoc_db"'
echo "Backend logs:"
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker logs sumoc-backend"'
} }
} else { } else {
echo "Skipping deployment for non-deploy branch." echo "Skipping deployment for non-deploy branch."
+17 -1
View File
@@ -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"
+41
View File
@@ -0,0 +1,41 @@
volumes:
nominatim-data:
postgres_data:
services:
backend:
build: .
image: backend:latest
container_name: sumoc-backend
ports:
- "8080:8080"
env_file:
- .env
depends_on:
- db
restart: unless-stopped
db:
image: postgres:16.2-alpine
container_name: sumoc_db
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=admin
- POSTGRES_DB=sumoc
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
restart: always
nominatim:
image: mediagis/nominatim:5.2
container_name: nominatim
environment:
PBF_URL: https://download.geofabrik.de/europe/germany/nordrhein-westfalen-latest.osm.pbf
REPLICATION_ENABLED: false
volumes:
- nominatim-data:/var/lib/postgresql/14/main
restart: unless-stopped
ports:
- "6666:8080"
+38 -8
View File
@@ -1,3 +1,7 @@
volumes:
postgres_data:
jwt_keys:
# nominatim-data:
services: services:
backend: backend:
@@ -8,22 +12,48 @@ services:
- "8080:8080" - "8080:8080"
env_file: env_file:
- .env - .env
environment:
TZ: Europe/Berlin
FCM_DECRYPTION_KEY: ${FCM_DECRYPTION_KEY}
RSA_PRIVATE_KEY_PATH: /data/keys/jwt-private.pem
RSA_PUBLIC_KEY_PATH: /data/keys/jwt-public.pem
volumes:
- jwt_keys:/data/keys
depends_on:
- db
restart: unless-stopped
adminer:
image: adminer:5.4.1-standalone
container_name: sumoc-adminer
ports:
- "8079:8080"
depends_on: depends_on:
- db - db
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 - TZ=Europe/Berlin
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"
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
# Decrypt secrets if key is provided
if [ -z "$FCM_DECRYPTION_KEY" ]; then
echo "No decryption key provided, skipping decryption."
else
echo "Decryption key provided, decrypting secrets..."
openssl enc -d -aes-256-cbc -pbkdf2 -in ./secrets/fcm-key.json.enc -out ./secrets/fcm-key.json -k "$FCM_DECRYPTION_KEY"
if [ $? -ne 0 ]; then
echo "Decryption failed!"
exit 1
fi
echo "Decryption successful."
fi
exec java -jar app.jar
+32
View File
@@ -0,0 +1,32 @@
#!/bin/bash
# 1. Spring Boot starten
echo "Starte Spring Boot..."
./mvnw spring-boot:run &
# Prozess-ID speichern, um später ggf. zu stoppen
SPRING_PID=$!
# Warten, bis der Server verfügbar ist
echo "Warte auf Serverstart..."
until curl -s http://localhost:8080/v3/api-docs.yaml -o /dev/null; do
sleep 2
done
# 2. OpenAPI-Spezifikation herunterladen
echo "Lade OpenAPI-Spezifikation herunter..."
curl http://localhost:8080/v3/api-docs.yaml -o openapi.yaml
# 3. Swift-Client generieren
echo "Generiere Swift-Client..."
openapi-generator-cli generate -i openapi.yaml -g swift5 -o app/ios-api --additional-properties=useClasses=true
# 4. Kotlin-Client generieren
echo "Generiere Kotlin-Client..."
openapi-generator-cli generate -i openapi.yaml -g kotlin -o app/android-api
# Optional: Spring Boot stoppen
echo "Stoppe Spring Boot..."
kill $SPRING_PID
echo "Fertig!"
+2494
View File
File diff suppressed because it is too large Load Diff
+7
View File
@@ -0,0 +1,7 @@
{
"$schema": "./node_modules/@openapitools/openapi-generator-cli/config.schema.json",
"spaces": 2,
"generator-cli": {
"version": "7.14.0"
}
}
+115 -11
View File
@@ -54,6 +54,10 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId> <artifactId>spring-boot-starter-validation</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency> <dependency>
<groupId>com.h2database</groupId> <groupId>com.h2database</groupId>
<artifactId>h2</artifactId> <artifactId>h2</artifactId>
@@ -87,8 +91,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 +130,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 +157,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 +166,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 +239,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 +264,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>
+9
View File
@@ -0,0 +1,9 @@
# Workflow
1. Encrypt key locally ```openssl enc -aes-256-cbc -pbkdf2 -salt -in KEY.json -out KEY.json.enc```
2. Provide decryption password during runtime as env var via docker compose
3. Decrypt key in entrypoint script
## Decrypt locally for development
```openssl enc -d -aes-256-cbc -pbkdf2 -in KEY.json.enc -out KEY.json```
Binary file not shown.
@@ -2,8 +2,10 @@ package SuMoC.backend;
import org.springframework.boot.SpringApplication; import org.springframework.boot.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,20 @@
package SuMoC.backend.carrousel.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "sumoc.alternative-carrousel")
public class CarrouselProperties {
/**
* Maximum number of alternative suggestions to show in the carrousel.
*/
private int maxCarrouselItems = 5;
/**
* Time window in days to consider recent suggestions for a user.
*/
private int recentSuggestionWindowDays = 7;
}
@@ -0,0 +1,30 @@
package SuMoC.backend.carrousel.controller;
import SuMoC.backend.carrousel.dto.AlternativeCarrouselDTO;
import SuMoC.backend.carrousel.service.CarrouselService;
import SuMoC.backend.user.service.CurrentUserService;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Controller for providing a carrousel of alternative routes for displaying on the app startpage.
*/
@RestController
@RequestMapping("/routing/alternative/carrousel")
@RequiredArgsConstructor
public class RoutingAlternativeCarrouselController {
private final CarrouselService carrouselService;
private final CurrentUserService currentUserService;
@GetMapping("/request")
@Schema(description = "Provides a carrousel of alternative routes for displaying on the app startpage.")
public ResponseEntity<AlternativeCarrouselDTO> getAlternativeCarrousel() {
return ResponseEntity.ok(carrouselService.getCarrouselForUser(currentUserService.get().getId()));
}
}
@@ -0,0 +1,21 @@
package SuMoC.backend.carrousel.dto;
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
import SuMoC.backend.routing.dtos.RouteDTO;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Schema(description = "Context for the alternative carrousel for a ad-hoc alternative suggestion.")
public class AdHocAlternativeContext extends RouteAlternativeContext {
@Schema(description = "The trip id associated with this alternative route suggestion.")
private Long tripId;
public AdHocAlternativeContext(RouteDTO alternative, Long tripId) {
super(alternative, CarrouselCandidateType.ADHOC_ALTERNATIVE);
this.tripId = tripId;
}
}
@@ -0,0 +1,16 @@
package SuMoC.backend.carrousel.dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
@AllArgsConstructor
public class AlternativeCarrouselDTO {
private List<RouteAlternativeContext> alternatives;
}
@@ -0,0 +1,18 @@
package SuMoC.backend.carrousel.dto;
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
import SuMoC.backend.regulartrip.dtos.MinimalDetectedRegularTripDTO;
import SuMoC.backend.routing.dtos.RouteDTO;
import lombok.Getter;
@Getter
public class RegularTripAlternativeContext extends RouteAlternativeContext {
private final MinimalDetectedRegularTripDTO detectedRegularTrip;
public RegularTripAlternativeContext(RouteDTO alternative, MinimalDetectedRegularTripDTO detectedRegularTrip) {
super(alternative, CarrouselCandidateType.REGULAR_TRIP_ALTERNATIVE);
this.detectedRegularTrip = detectedRegularTrip;
}
}
@@ -0,0 +1,24 @@
package SuMoC.backend.carrousel.dto;
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
import SuMoC.backend.routing.dtos.RouteDTO;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Schema(description = "Wrapper for alternative routes in the carousel.")
@NoArgsConstructor
public abstract class RouteAlternativeContext {
protected CarrouselCandidateType carrouselCandidateType;
protected RouteDTO alternative;
protected RouteAlternativeContext(RouteDTO alternative, CarrouselCandidateType carrouselCandidateType) {
this.carrouselCandidateType = carrouselCandidateType;
this.alternative = alternative;
}
}
@@ -0,0 +1,6 @@
package SuMoC.backend.carrousel.enums;
public enum CarrouselCandidateType {
ADHOC_ALTERNATIVE,
REGULAR_TRIP_ALTERNATIVE,
}
@@ -0,0 +1,45 @@
package SuMoC.backend.carrousel.models;
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
import SuMoC.backend.regulartrip.dtos.MinimalDetectedRegularTripDTO;
import SuMoC.backend.routing.dtos.RouteDTO;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes;
import java.time.Instant;
/**
* Entity representing a candidate for the alternatives carrousel. We use this to keep track of alternatives we have
* suggested the user via notifications earlier, so that wen can also show them in the carrousel.
*/
@Entity
@Table(name = "carrousel_candidates")
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class CarrouselCandidate {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private CarrouselCandidateType candidateType;
@Column(nullable = false)
private Long userId;
private Long adHocTripId;
@JdbcTypeCode(SqlTypes.JSON)
private MinimalDetectedRegularTripDTO detectedRegularTrip;
@JdbcTypeCode(SqlTypes.JSON)
private RouteDTO suggestedAlternative;
private Instant suggestedAt;
}
@@ -0,0 +1,22 @@
package SuMoC.backend.carrousel.repository;
import SuMoC.backend.carrousel.models.CarrouselCandidate;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.time.Instant;
import java.util.List;
public interface CarrouselCandidateRepository extends JpaRepository<CarrouselCandidate, Long> {
@Query("""
SELECT c
FROM CarrouselCandidate c
WHERE c.userId = :userId
AND c.suggestedAt >= :cutOff
ORDER BY c.suggestedAt DESC
""")
List<CarrouselCandidate> findByUserIdDesc(Long userId, Instant cutOff);
void deleteAllByUserId(Long userId);
}
@@ -0,0 +1,107 @@
package SuMoC.backend.carrousel.service;
import SuMoC.backend.carrousel.config.CarrouselProperties;
import SuMoC.backend.carrousel.dto.AdHocAlternativeContext;
import SuMoC.backend.carrousel.dto.AlternativeCarrouselDTO;
import SuMoC.backend.carrousel.dto.RegularTripAlternativeContext;
import SuMoC.backend.carrousel.dto.RouteAlternativeContext;
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
import SuMoC.backend.carrousel.models.CarrouselCandidate;
import SuMoC.backend.carrousel.repository.CarrouselCandidateRepository;
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
import SuMoC.backend.regulartrip.dtos.MinimalDetectedRegularTripDTO;
import SuMoC.backend.routing.dtos.RouteDTO;
import SuMoC.backend.trip.models.Trip;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
@Service
@RequiredArgsConstructor
public class CarrouselService {
private final CarrouselCandidateRepository carrouselCandidateRepository;
private final CarrouselProperties carrouselProperties;
public void addAdHocTripCandidates(Trip trip, List<RouteDTO> suggestedAlternatives) {
for (var alternative : suggestedAlternatives) {
CarrouselCandidate candidate = CarrouselCandidate.builder()
.userId(trip.getUser().getId())
.adHocTripId(trip.getId())
.suggestedAlternative(alternative)
.suggestedAt(Instant.now())
.candidateType(CarrouselCandidateType.ADHOC_ALTERNATIVE)
.build();
carrouselCandidateRepository.save(candidate);
}
}
public List<CarrouselCandidate> getRegularTripCandidates(Long userId, DetectedRegularTripDTO detectedRegularTrip, List<RouteDTO> suggestedAlternatives) {
List<CarrouselCandidate> candidates = new ArrayList<>();
for (var alternative : suggestedAlternatives) {
CarrouselCandidate candidate = CarrouselCandidate.builder()
.userId(userId)
.detectedRegularTrip(MinimalDetectedRegularTripDTO.fromDetectedRegularTripDTO(detectedRegularTrip))
.suggestedAlternative(alternative)
.suggestedAt(Instant.now())
.candidateType(CarrouselCandidateType.REGULAR_TRIP_ALTERNATIVE)
.build();
candidates.add(candidate);
}
return candidates;
}
public AlternativeCarrouselDTO getCarrouselForUser(Long userId) {
var candidates = carrouselCandidateRepository.findByUserIdDesc(userId, Instant.now().minus(Duration.ofDays(carrouselProperties.getRecentSuggestionWindowDays())));
if (candidates.isEmpty()) {
return new AlternativeCarrouselDTO(List.of());
}
var alternativeEntries = candidates.stream()
.limit(carrouselProperties.getMaxCarrouselItems())
.map(this::mapToCarrouselAlternativeEntry)
.toList();
return new AlternativeCarrouselDTO(alternativeEntries);
}
/**
* Converts a CarrouselCandidate to a RouteAlternativeContext, which is the format expected by the frontend carousel.
*
* @param candidate
* @return
*/
private RouteAlternativeContext mapToCarrouselAlternativeEntry(CarrouselCandidate candidate) {
switch (candidate.getCandidateType()) {
case ADHOC_ALTERNATIVE -> {
return fromAdHocCandidate(candidate);
}
case REGULAR_TRIP_ALTERNATIVE -> {
return fromRegularTripCandidate(candidate);
}
default -> throw new IllegalStateException("Unimplemented candidate type: " + candidate.getCandidateType());
}
}
private RouteAlternativeContext fromAdHocCandidate(CarrouselCandidate candidate) {
return new AdHocAlternativeContext(candidate.getSuggestedAlternative(), candidate.getAdHocTripId());
}
private RouteAlternativeContext fromRegularTripCandidate(CarrouselCandidate candidate) {
var minRegularTrip = candidate.getDetectedRegularTrip();
return new RegularTripAlternativeContext(
candidate.getSuggestedAlternative(),
minRegularTrip
);
}
}
@@ -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 != null ? arrivalTime.getEpochSecond() : null,
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,32 @@
package SuMoC.backend.carta;
public interface DirectionsRequest {
Double getOriginLat();
void setOriginLat(Double originLat);
Double getOriginLon();
void setOriginLon(Double originLon);
Double getDestinationLat();
void setDestinationLat(Double destinationLat);
Double getDestinationLon();
void setDestinationLon(Double destinationLon);
java.time.Instant getArrivalTime();
void setArrivalTime(java.time.Instant arrivalTime);
java.time.Instant getDepartureTime();
void setDepartureTime(java.time.Instant departureTime);
SuMoC.backend.routing.dtos.RoutingPreferencesDTO getRoutingPreferencesDTO();
void setRoutingPreferencesDTO(SuMoC.backend.routing.dtos.RoutingPreferencesDTO routingPreferencesDTO);
}
@@ -0,0 +1,322 @@
package SuMoC.backend.carta;
import SuMoC.backend.geocoding.AddressDTO;
import SuMoC.backend.geocoding.GeoCodingService;
import SuMoC.backend.routing.dtos.RouteDTO;
import SuMoC.backend.routing.dtos.StepDTO;
import SuMoC.backend.routing.exceptions.NoCarRouteFoundException;
import SuMoC.backend.routing.exceptions.NoCarbonEmissionFoundException;
import SuMoC.backend.routing.services.CartaTransitRouteProcessor;
import SuMoC.backend.trip.Modality;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import sumoc.backend.carta.client.model.Direction;
import sumoc.backend.carta.client.model.Route;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import static SuMoC.backend.trip.Modality.BICYCLE;
import static SuMoC.backend.trip.Modality.CAR;
@Service
@RequiredArgsConstructor
public class DirectionsService {
private final CartaClient cartaClient;
private final GeoCodingService geoCodingService;
public List<RouteDTO> getPossibleAlternativeRoutes(DirectionsRequest requestDTO) {
return getPossibleRoutes(requestDTO, false);
}
/**
* Returns possible routes for the request - no sanity filtering regarding travel times etc. is applied.
* TODO this does not handle the case where origin/destination is provided as address only -> geocoding call to carta needed -> do in directions controller
*/
public List<RouteDTO> getPossibleRoutes(DirectionsRequest requestDTO, boolean includeCarRoute) {
assert requestDTO.getRoutingPreferencesDTO() != null;
HashMap<String, Direction> directionMap = getPossibleDirections(requestDTO);
ArrayList<RouteDTO> suggestedRoutes = new ArrayList<>();
// TODO derive origin/destination either from address or coordinates
// Fetch origin and destination addresses concurrently
var addressesMono = Mono.zip(
geoCodingService.getAddress(requestDTO.getOriginLat(), requestDTO.getOriginLon()),
geoCodingService.getAddress(requestDTO.getDestinationLat(), requestDTO.getDestinationLon())
);
var addressesTuple = addressesMono.block();
AddressDTO originAddress = addressesTuple.getT1();
AddressDTO destinationAddress = addressesTuple.getT2();
// Setting up car data for baseline
Route carRoute;
try {
carRoute = directionMap.get("car").getRoutes().getFirst();
} catch (NullPointerException e) {
throw new NoCarRouteFoundException("No car route to compare to was found.");
}
double carCarbondDioxide;
try {
carCarbondDioxide = carRoute.getEmission().getCarbonDioxide();
} catch (NullPointerException e) {
throw new NoCarbonEmissionFoundException("No carbon emission was provided for the car route.");
}
double carDuration = carRoute.getDuration();
// Creating RouteDTOs for all available modes
if (includeCarRoute) {
Direction carDirection = directionMap.get("car");
if (carDirection.getRoutes() != null && !carDirection.getRoutes().isEmpty()) {
suggestedRoutes.add(createRouteDTO(
requestDTO,
carRoute,
List.of(new StepDTO(CAR, carRoute.getDistance())),
originAddress,
destinationAddress,
null,
null,
carCarbondDioxide,
carDuration,
false
));
}
}
if (directionMap.containsKey("bike")) {
Direction bikeDirection = directionMap.get("bike");
if (bikeDirection.getRoutes() != null && !bikeDirection.getRoutes().isEmpty()) {
Route bikeRoute = bikeDirection.getRoutes().getFirst();
suggestedRoutes.add(createRouteDTO(
requestDTO,
bikeRoute,
List.of(new StepDTO(BICYCLE, bikeRoute.getDistance())),
originAddress,
destinationAddress,
null,
null,
carCarbondDioxide,
carDuration,
false
));
}
}
if (directionMap.containsKey("walk")) {
Direction walkDirection = directionMap.get("walk");
if (walkDirection.getRoutes() != null && !walkDirection.getRoutes().isEmpty()) {
Route walkRoute = walkDirection.getRoutes().getFirst();
suggestedRoutes.add(createRouteDTO(
requestDTO,
walkRoute,
List.of(new StepDTO(Modality.WALKING, walkRoute.getDistance())),
originAddress,
destinationAddress,
null,
null,
carCarbondDioxide,
carDuration,
false
));
}
}
if (directionMap.containsKey("transit")) {
Direction transitDirection = directionMap.get("transit");
if (transitDirection.getRoutes() != null && !transitDirection.getRoutes().isEmpty()) {
for (Route route : transitDirection.getRoutes()) {
CartaTransitRouteProcessor routeProcessor = new CartaTransitRouteProcessor(route);
suggestedRoutes.add(createRouteDTO(
requestDTO,
route,
routeProcessor.getSteps(),
originAddress,
destinationAddress,
routeProcessor.getFirstStopName(),
routeProcessor.getLastStopName(),
carCarbondDioxide,
carDuration,
true
));
}
}
}
return suggestedRoutes;
}
private RouteDTO createRouteDTO(
DirectionsRequest requestDTO,
Route route,
List<StepDTO> steps,
AddressDTO originAddress,
AddressDTO destinationAddress,
String firstStopName,
String lastStopName,
double carVariantco2Emission,
double carVariantTimeSeconds,
boolean isTransit
) {
Instant arrivalTime;
Instant departureTime;
// Baseline is comparing with car version, except for alternative route requests
double timeDifferenceSeconds = route.getDuration() - carVariantTimeSeconds;
if (requestDTO.getArrivalTime() != null && requestDTO.getDepartureTime() != null) {
// Case 1: both arrival and departure time provided -> must be alternative route request
if (isTransit) { // for transit routes, we need to look up the exact arrival time at the last stop
arrivalTime = cartaTimeToInstant(route.getSteps().getLast().getStopTime(), requestDTO.getArrivalTime());
} else {
arrivalTime = requestDTO.getArrivalTime();
}
departureTime = arrivalTime.minusSeconds(route.getDuration());
timeDifferenceSeconds = route.getDuration() - (requestDTO.getArrivalTime().getEpochSecond() - requestDTO.getDepartureTime().getEpochSecond());
} else if (requestDTO.getArrivalTime() != null) {
// Case 2: only arrival time provided
if (isTransit) {
arrivalTime = cartaTimeToInstant(route.getSteps().getLast().getStopTime(), requestDTO.getArrivalTime());
} else {
arrivalTime = requestDTO.getArrivalTime();
}
departureTime = arrivalTime.minusSeconds(route.getDuration());
} else {
// Case 3: only departure time provided
if (isTransit) {
departureTime = cartaTimeToInstant(route.getSteps().getFirst().getStartTime(), requestDTO.getDepartureTime());
} else {
departureTime = requestDTO.getDepartureTime();
}
arrivalTime = departureTime.plusSeconds(route.getDuration());
}
double co2savings = carVariantco2Emission - route.getEmission().getCarbonDioxide();
RouteDTO routeDTO = new RouteDTO(
originAddress,
firstStopName,
route.getSourceCoordinate().getLatitude(),
route.getSourceCoordinate().getLongitude(),
destinationAddress,
lastStopName,
route.getTargetCoordinate().getLatitude(),
route.getTargetCoordinate().getLongitude(),
departureTime,
arrivalTime,
steps,
co2savings,
timeDifferenceSeconds,
route.getEmission().getCarbonDioxide()
);
return routeDTO;
}
/**
* 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> getPossibleDirections(DirectionsRequest 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;
}
/**
* Converts a Carta time (seconds since midnight of current day) to an Instant.
*
* @return
*/
private Instant cartaTimeToInstant(Integer secondsSinceMidnight, Instant instantOfReferenceDay) {
LocalDate date = instantOfReferenceDay.atZone(ZoneId.systemDefault()).toLocalDate();
LocalDateTime startOfDay = date.atStartOfDay();
LocalDateTime resultDateTime = startOfDay.plusSeconds(secondsSinceMidnight);
return resultDateTime.atZone(ZoneId.systemDefault()).toInstant();
}
/**
* Makes an individual call to the CARTA API and returns a direction future.
*/
private CompletableFuture<Direction> getCartaFuture(
DirectionsRequest requestDTO,
String mode,
String types,
int alternatives
) {
Instant departureTime = null;
Instant arrivalTime = null;
if (requestDTO.getArrivalTime() != null) {
arrivalTime = requestDTO.getArrivalTime();
} else if (requestDTO.getDepartureTime() != null) {
departureTime = requestDTO.getDepartureTime();
} else {
throw new IllegalArgumentException("Either arrivalTime or departureTime must be provided.");
}
// TODO derive origin either from address or coordinates
return cartaClient.asyncGetRoute(
requestDTO.getOriginLat() + "," + requestDTO.getOriginLon(),
requestDTO.getDestinationLat() + "," + requestDTO.getDestinationLon(),
mode,
arrivalTime,
departureTime,
alternatives, // alternatives
null, // walkingSpeed
null, // transferTime TODO what is default? adapt?
types,
null, // range
// TODO only if coordinates are provided directly
requestDTO.getOriginLat() + "," + requestDTO.getOriginLon()
);
}
}
@@ -0,0 +1,32 @@
package SuMoC.backend.common.converter;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import java.time.DayOfWeek;
/**
* This converter handles the conversion between Java's DayOfWeek enum and the SQL DAY_OF_WEEK integer representation.
* In Java, DayOfWeek uses 1 (Monday) to 7 (Sunday), while SQL's DAY_OF_WEEK function returns 0 (Sunday) to 6 (Saturday).
*/
@Converter(autoApply = true)
public class DayOfWeekConverter implements AttributeConverter<DayOfWeek, Integer> {
@Override
public Integer convertToDatabaseColumn(DayOfWeek attribute) {
if (attribute == null) {
return null;
}
// Convert Java DayOfWeek (1=Monday, ..., 7=Sunday) to SQL DOW (0=Sunday, ..., 6=Saturday)
return attribute.getValue() % 7;
}
@Override
public DayOfWeek convertToEntityAttribute(Integer dbData) {
if (dbData == null) {
return null;
}
// Convert SQL DOW (0=Sunday, ..., 6=Saturday) to Java DayOfWeek (1=Monday, ..., 7=Sunday)
return DayOfWeek.of(dbData == 0 ? 7 : dbData);
}
}
@@ -0,0 +1,39 @@
package SuMoC.backend.config;
import SuMoC.backend.suggestion.config.RegularTripSuggestionProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync
@RequiredArgsConstructor
public class AsyncConfiguration {
private final RegularTripSuggestionProperties regularTripSuggestionProperties;
/**
* Custom thread pool executor for parallel processing of regular trip suggestions.
* Configured with parallelism setting from application properties.
*/
@Bean(name = "regularTripSuggestionExecutor")
public Executor regularTripSuggestionExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
int parallelism = regularTripSuggestionProperties.getParallelism();
executor.setCorePoolSize(parallelism);
executor.setMaxPoolSize(parallelism);
executor.setQueueCapacity(500); // Queue capacity for pending tasks
executor.setThreadNamePrefix("regular-trip-");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
executor.initialize();
return executor;
}
}
@@ -0,0 +1,22 @@
package SuMoC.backend.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.web.filter.ShallowEtagHeaderFilter;
@Configuration
public class CachingConfig {
/**
* Register a filter that adds ETag headers to HTTP responses for caching purposes.
*/
@Bean
public FilterRegistrationBean<ShallowEtagHeaderFilter> etagFilter() {
FilterRegistrationBean<ShallowEtagHeaderFilter> filter = new FilterRegistrationBean<>(new ShallowEtagHeaderFilter());
filter.addUrlPatterns("/*");
filter.setName("etagFilter");
filter.setOrder(1);
return filter;
}
}
@@ -0,0 +1,294 @@
package SuMoC.backend.dev;
import SuMoC.backend.firebase.FirebaseMessageBuilder;
import SuMoC.backend.h3.H3Service;
import SuMoC.backend.meteo.ForecastService;
import SuMoC.backend.meteo.MeteoClient;
import SuMoC.backend.notification.enums.NotificationStatus;
import SuMoC.backend.notification.enums.NotificationType;
import SuMoC.backend.notification.models.Notification;
import SuMoC.backend.notification.repositories.NotificationRepository;
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
import SuMoC.backend.routing.dtos.RouteDTO;
import SuMoC.backend.scheduling.ScheduledTasks;
import SuMoC.backend.suggestion.services.RegularTripSuggestionService;
import SuMoC.backend.trend.dto.TrendDetectionDTO;
import SuMoC.backend.trend.services.StatTableUpdateService;
import SuMoC.backend.user.dtos.FriendshipDTO;
import SuMoC.backend.user.dtos.MinimalUserDTO;
import SuMoC.backend.user.enums.FriendShipStatus;
import SuMoC.backend.user.mapper.UserMapper;
import SuMoC.backend.user.models.User;
import SuMoC.backend.user.repository.UserRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.Message;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
@RestController
@RequestMapping("/dev")
@Profile("dev")
public class DevController {
private final ScheduledTasks scheduledTasks;
private final StatTableUpdateService statTableUpdateService;
private final FirebaseMessaging firebaseMessaging;
private final MeteoClient meteoClient;
private final ForecastService forecastService;
private final FirebaseMessageBuilder firebaseMessageBuilder;
private final ObjectMapper objectMapper;
private final NotificationRepository notificationRepository;
private final UserRepository userRepository;
private final UserMapper userMapper;
private final H3Service h3Service;
private final RegularTripSuggestionService regularTripSuggestionService;
public DevController(
ScheduledTasks scheduledTasks,
StatTableUpdateService statTableUpdateService,
@Autowired(required = false) FirebaseMessaging firebaseMessaging,
MeteoClient meteoClient,
ForecastService forecastService,
FirebaseMessageBuilder firebaseMessageBuilder,
ObjectMapper objectMapper,
NotificationRepository notificationRepository, UserRepository userRepository, UserMapper userMapper, H3Service h3Service, RegularTripSuggestionService regularTripSuggestionService
) {
this.scheduledTasks = scheduledTasks;
this.statTableUpdateService = statTableUpdateService;
this.firebaseMessaging = firebaseMessaging;
this.meteoClient = meteoClient;
this.forecastService = forecastService;
this.firebaseMessageBuilder = firebaseMessageBuilder;
this.objectMapper = objectMapper;
this.notificationRepository = notificationRepository;
this.userRepository = userRepository;
this.userMapper = userMapper;
this.h3Service = h3Service;
this.regularTripSuggestionService = regularTripSuggestionService;
}
@PostMapping("/trigger-trend-calculation")
public void triggerTrendCalculation() {
LocalDate dayOfLastWeek = LocalDate.now().minusDays(7);
LocalDate day2WeeksAgo = LocalDate.now().minusDays(14);
LocalDate day3WeeksAgo = LocalDate.now().minusDays(21);
statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(dayOfLastWeek);
statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(day2WeeksAgo);
statTableUpdateService.updateWeeklyMobilityStatsForAllUsers(day3WeeksAgo);
}
@GetMapping("/test-firebase-trend-notification/{fcm_token}")
@Operation(description = "Immediately sends a test notification of type TREND to the provided FCM token.")
public ResponseEntity<String> SendTestTrendNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
if (firebaseMessaging == null) {
return ResponseEntity.status(503)
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
}
try {
Notification notification = new Notification();
notification.setType(NotificationType.TREND);
notification.setData(objectMapper.writeValueAsString(TrendDetectionDTO.mockTrendDetectionDTO()));
Message mockTrendMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
// Send to a topic (no device registration needed)
String message = firebaseMessaging.sendAsync(
mockTrendMessage
).get();
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
} catch (Exception e) {
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
}
}
@GetMapping("/test-firebase-adhoc-route-notification/{fcm_token}")
@Operation(description = "Immediately sends a test notification of type ADHOC_ALTERNATIVE to the provided FCM token.")
public ResponseEntity<String> SendTestAdhocRouteNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
if (firebaseMessaging == null) {
return ResponseEntity.status(503)
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
}
try {
Notification notification = new Notification();
notification.setType(NotificationType.ADHOC_ALTERNATIVE);
List<RouteDTO> mockRoutes = List.of(RouteDTO.getMockRouteDTO(), RouteDTO.getMockRouteDTO());
notification.setData(objectMapper.writeValueAsString(mockRoutes));
Message mockAdhocMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
// Send to a topic (no device registration needed)
String message = firebaseMessaging.sendAsync(
mockAdhocMessage
).get();
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
} catch (Exception e) {
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
}
}
@GetMapping("/test-firebase-regular-trip-notification/{fcm_token}")
@Operation(description = "Immediately sends a test notification of type REGULAR_TRIP_ALTERNATIVE to the provided FCM token.")
public ResponseEntity<String> SendTestRegularTripAlternativeNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
if (firebaseMessaging == null) {
return ResponseEntity.status(503)
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
}
try {
Notification notification = new Notification();
notification.setType(NotificationType.REGULAR_TRIP_ALTERNATIVE);
RouteDTO mockRoute = RouteDTO.getMockRouteDTO();
notification.setData(objectMapper.writeValueAsString(mockRoute));
Message mockRegularTripMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
// Send to a topic (no device registration needed)
String message = firebaseMessaging.sendAsync(
mockRegularTripMessage
).get();
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
} catch (Exception e) {
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
}
}
@GetMapping("/test-firebase-friendship-request-notification/{fcm_token}")
@Operation(description = "Immediately sends a test notification of type FRIENDSHIP_REQUEST_RECEIVED to the provided FCM token.")
public ResponseEntity<String> SendTestRFriendshipRequestReceivedNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
if (firebaseMessaging == null) {
return ResponseEntity.status(503)
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
}
try {
Notification notification = new Notification();
notification.setType(NotificationType.FRIENDSHIP_REQUEST_RECEIVED);
FriendshipDTO friendshipDTO = new FriendshipDTO(
1L,
2L,
new MinimalUserDTO(
2L,
"request_public_name"
),
FriendShipStatus.PENDING,
Instant.now()
);
notification.setData(objectMapper.writeValueAsString(friendshipDTO));
Message mockRegularTripMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
String message = firebaseMessaging.sendAsync(
mockRegularTripMessage
).get();
return ResponseEntity.ok("✓ Firebase message sent to topic: " + message);
} catch (Exception e) {
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
}
}
@GetMapping("/test-notification-from-detected-regular-trip")
@Operation(description = "Testing endpoint that mocks the detection of regular trips and then tests the alternative calculation and notification scheduling.")
public ResponseEntity<String> testNotificationFromDetectedRegularTrip() {
if (firebaseMessaging == null) {
return ResponseEntity.status(503)
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
}
try {
// we seed user 1 and 2 in the dev data loader
HashMap<Long, List<DetectedRegularTripDTO>> detectedRegularTripsByUser = new HashMap<>();
List<DetectedRegularTripDTO> list1 = List.of(
DetectedRegularTripDTO.getTriggeringMock(h3Service, 1L)
);
List<DetectedRegularTripDTO> list2 = List.of(
DetectedRegularTripDTO.getTriggeringMock(h3Service, 2L)
);
detectedRegularTripsByUser.put(1L, list1);
detectedRegularTripsByUser.put(2L, list2);
regularTripSuggestionService.checkAlternativesAndNotify(detectedRegularTripsByUser);
return ResponseEntity.ok("✓ Test notifications from detected regular trips processed.");
} catch (Exception e) {
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
}
}
@Operation(description = "Immediately queues a notification to the fcm key specified in application-dev.properties to be processed by the notification queue.")
@GetMapping("/queue-test-notification")
public ResponseEntity<String> queueTestNotification() {
if (firebaseMessaging == null) {
return ResponseEntity.status(503)
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
}
try {
User user = userRepository.findByEmail("user1@email.com").orElseThrow();
TrendDetectionDTO mockDTO = TrendDetectionDTO.mockTrendDetectionDTO();
mockDTO.setUserId(user.getId());
Notification notification = Notification.builder()
.type(NotificationType.TREND)
.data(objectMapper.writeValueAsString(mockDTO))
.user(user)
.earliestTimeOfDayToSend(LocalTime.now())
.createdAt(Instant.now())
.status(NotificationStatus.PENDING)
.build();
notificationRepository.save(notification);
return ResponseEntity.ok("✓ Test notification queued.");
} catch (Exception e) {
return ResponseEntity.status(500).body("✗ Failed: " + e.getMessage());
}
}
@Operation(description = "Tests the method cleaning old notifications from the database.")
@GetMapping("/test-clean-old-notifications")
public void testCleanOldNotifications() throws JsonProcessingException, InterruptedException {
User user = userRepository.findByEmail("user1@email.com").orElseThrow();
Notification notification = Notification.builder()
.type(NotificationType.TREND)
.data(objectMapper.writeValueAsString(TrendDetectionDTO.mockTrendDetectionDTO()))
.user(user)
.earliestTimeOfDayToSend(LocalTime.now())
.createdAt(Instant.now().minus(Duration.ofDays(60)))
.status(NotificationStatus.SENT)
.build();
notificationRepository.save(notification);
Thread.sleep(5000);
scheduledTasks.scheduleCleanUpOldNotifications();
}
@GetMapping("/test-meteo")
public void testMeteoClient() {
try {
// Test with Zurich coordinates
double lat = 51.44378662109375;
double lon = 7.007565975189209;
var forecast = forecastService.getTodayYesterdayForecast(
lat,
lon);
} catch (Exception e) {
}
}
@PostMapping("/test-detection-and-notification-regular-trips")
public void testDetectionAndNotificationOfRegularTrips() {
regularTripSuggestionService.detectAndNotifyRegularTripsForTodaysDayOfWeek();
}
}
@@ -0,0 +1,15 @@
package SuMoC.backend.dev;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "sumoc.dev")
public class DevProperties {
/**
* Will be used to init the seeded users with in the dev profile.
*/
private String fcmKey = "";
}
@@ -0,0 +1,56 @@
package SuMoC.backend.firebase;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.FirebaseMessaging;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.io.InputStream;
@Configuration
@EnableConfigurationProperties(FirebaseProperties.class)
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "firebase.config", name = "enabled", havingValue = "true", matchIfMissing = false)
public class FirebaseConfiguration {
private final FirebaseProperties firebaseProperties;
@Bean
FirebaseMessaging firebaseMessaging(FirebaseApp firebaseApp) {
return FirebaseMessaging.getInstance(firebaseApp);
}
@Bean
FirebaseApp firebaseApp(GoogleCredentials credentials) {
try {
return FirebaseApp.getInstance();
} catch (IllegalStateException e) {
// App doesn't exist yet, create it
FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(credentials)
.build();
return FirebaseApp.initializeApp(options);
}
}
@Bean
GoogleCredentials googleCredentials(FirebaseProperties firebaseProperties) throws IOException {
if (firebaseProperties.serviceAccount() != null) {
try (InputStream is = firebaseProperties.serviceAccount().getInputStream()) {
return GoogleCredentials.fromStream(is);
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
// Use standard credentials chain. Useful when running inside GKE
return GoogleCredentials.getApplicationDefault();
}
}
}
@@ -0,0 +1,35 @@
package SuMoC.backend.firebase;
import SuMoC.backend.notification.models.Notification;
import com.google.firebase.messaging.ApnsConfig;
import com.google.firebase.messaging.Aps;
import com.google.firebase.messaging.ApsAlert;
import com.google.firebase.messaging.Message;
import org.springframework.stereotype.Service;
@Service
public class FirebaseMessageBuilder {
public Message generateMessage(Notification notification, String token) {
var builder = Message.builder().setToken(token);
builder.putData("type", notification.getType().toString());
builder.putData("data", notification.getData());
//Setup, so iOS can receive and intercept Push Notifications
builder.setNotification(com.google.firebase.messaging.Notification.builder()
.setTitle("Sumoc Update")
.setBody("Deine Nachricht ist da!")
.build())
.setApnsConfig(ApnsConfig.builder()
.setAps(Aps.builder()
.setMutableContent(true)
.setSound("default") // WICHTIG: Ohne Sound oft keine Anzeige
.setBadge(1)
.build())
.build());
return builder.build();
}
}
@@ -0,0 +1,12 @@
package SuMoC.backend.firebase;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.io.Resource;
@ConfigurationProperties(prefix = "firebase.config")
public record FirebaseProperties(
Boolean enabled,
Resource serviceAccount
) {
}
@@ -0,0 +1,18 @@
package SuMoC.backend.gamification;
public enum Timeframe {
TOTAL("totalStats"),
MONTHLY("monthlyStats"),
WEEKLY("weeklyStats");
private final String statsField;
Timeframe(String statsField) {
this.statsField = statsField;
}
public String getStatsField() {
return statsField;
}
}
@@ -0,0 +1,129 @@
package SuMoC.backend.gamification.badges;
import SuMoC.backend.gamification.badges.models.UserBadgeDTO;
import SuMoC.backend.gamification.badges.models.BadgeDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/badges")
public class BadgeController {
private BadgeService badgeService;
@Autowired
public BadgeController(BadgeService badgeService) {
this.badgeService = badgeService;
}
@Operation(summary = "Create a new badge")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Badge created successfully",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = BadgeDTO.class))),
@ApiResponse(responseCode = "400", description = "Invalid input data"),
@ApiResponse(responseCode = "409", description = "Badge already exists")
})
@PostMapping("/createBadge")
public ResponseEntity<BadgeDTO> createBadge(@RequestBody @Valid BadgeDTO badge) {
BadgeDTO createdBadge = badgeService.createBadge(badge);
return ResponseEntity.status(HttpStatus.CREATED).body(createdBadge);
}
@Operation(summary = "Delete a badge by ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Badge deleted successfully"),
@ApiResponse(responseCode = "404", description = "Badge not found")
})
@DeleteMapping("/deleteBadge/{badgeId}")
public ResponseEntity<Void> deleteBadgeById(@PathVariable Long badgeId) {
badgeService.deleteBadge(badgeId);
return ResponseEntity.ok().build();
}
@Operation(summary = "Modify a badge by ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Badge modified successfully",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = BadgeDTO.class))),
@ApiResponse(responseCode = "404", description = "Badge not found"),
@ApiResponse(responseCode = "400", description = "Invalid input data")
})
@PutMapping("/modifyBadge")
public ResponseEntity<BadgeDTO> modifyBadgeById(
@RequestBody @Valid BadgeDTO badge) {
BadgeDTO modifiedBadge = badgeService.modifyBadge(badge);
return ResponseEntity.status(HttpStatus.OK).body(modifiedBadge);
}
@Operation(summary = "Get a badge by ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Badge retrieved successfully",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = BadgeDTO.class))),
@ApiResponse(responseCode = "304", description = "Not modified since last request"),
@ApiResponse(responseCode = "404", description = "Badge not found")
})
@GetMapping("/getBadge/{badgeId}")
public ResponseEntity<BadgeDTO> getBadgeById(@PathVariable Long badgeId) {
BadgeDTO badge = badgeService.getBadgeById(badgeId);
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(356, TimeUnit.DAYS))
.body(badge);
}
@Operation(summary = "Get all badges")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Badges retrieved successfully",
content = @Content(mediaType = "application/json",
array = @ArraySchema(schema = @Schema(implementation = BadgeDTO.class))
)),
@ApiResponse(responseCode = "304", description = "Not modified since last request"),
@ApiResponse(responseCode = "404", description = "No badges found")
})
@GetMapping("/getAllBadges")
public ResponseEntity<List<BadgeDTO>> getAllBadges(){
List<BadgeDTO> badges = badgeService.getAllBadges();
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(365, TimeUnit.DAYS))
.body(badges);
}
@Operation(summary = "Get Badges by user")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Badges retrieved successfully"),
@ApiResponse(responseCode = "404", description = "No badges found for user")
})
@GetMapping("/getBadges/{userId}")
public ResponseEntity<List<UserBadgeDTO>> getBadgesByUser(@PathVariable("userId") Long userId) {
List<UserBadgeDTO> badges = badgeService.getUserBadges(userId);
return ResponseEntity.ok(badges);
}
@Operation(summary = "Check badges for current user and award newly unlocked ones")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Check successful")
})
@PostMapping("/checkBadgeAndAward")
public ResponseEntity<Void> checkAndAwardBadges() {
badgeService.checkAndAwardBadges();
return ResponseEntity.ok().build();
}
}
@@ -0,0 +1,15 @@
package SuMoC.backend.gamification.badges;
import SuMoC.backend.gamification.badges.models.Badge;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface BadgeRepository extends JpaRepository<Badge, Long> {
Optional<Badge> findByName(String name);
List<Badge> getBadgeById(Long id);
}
@@ -0,0 +1,130 @@
package SuMoC.backend.gamification.badges;
import SuMoC.backend.gamification.Timeframe;
import SuMoC.backend.gamification.badges.mapper.BadgeMapper;
import SuMoC.backend.gamification.badges.mapper.UserBadgeMapper;
import SuMoC.backend.gamification.badges.models.Badge;
import SuMoC.backend.gamification.badges.models.BadgeDTO;
import SuMoC.backend.gamification.badges.models.UserBadge;
import SuMoC.backend.gamification.badges.models.UserBadgeDTO;
import SuMoC.backend.user.models.User;
import SuMoC.backend.user.service.CurrentUserService;
import SuMoC.backend.user.service.PrivacyService;
import jakarta.transaction.Transactional;
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
@Transactional
public class BadgeService {
private final CurrentUserService currentUser;
private final BadgeRepository badgeRepository;
private final UserBadgeRepository userBadgeRepository;
private final PrivacyService privacyService;
public BadgeService(CurrentUserService currentUser, BadgeRepository badgeRepository, UserBadgeRepository userBadgeRepository, PrivacyService privacyService) {
this.currentUser = currentUser;
this.badgeRepository = badgeRepository;
this.userBadgeRepository = userBadgeRepository;
this.privacyService = privacyService;
}
public BadgeDTO createBadge(BadgeDTO badgeDTO) {
badgeRepository.findByName(badgeDTO.getName())
.ifPresent(b -> {
throw new ResponseStatusException(HttpStatus.CONFLICT, "Badge existiert bereits");
});
Badge badge = BadgeMapper.toEntity(badgeDTO);
Badge savedBadge = badgeRepository.save(badge);
return BadgeMapper.toDTO(savedBadge);
}
public void checkAndAwardBadges() {
User user = currentUser.get();
List<Badge> badges = badgeRepository.findAll();
for (Badge badge : badges) {
// Prüfe, ob Nutzer schon den Badge hat
boolean alreadyHas = user.getBadges().stream()
.anyMatch(ub -> ub.getBadge().equals(badge));
if (alreadyHas) continue;
// Nur prüfen, wenn es überhaupt Kriterien gibt
Map<String, Integer> criteria = badge.getCriteria();
boolean qualifies = criteria != null && !criteria.isEmpty() &&
criteria.entrySet().stream()
.allMatch(entry ->
user.getStats().getStatValue(Timeframe.TOTAL, entry.getKey()) >= entry.getValue()
);
if (qualifies) {
UserBadge userBadge = new UserBadge();
userBadge.setUser(user);
userBadge.setBadge(badge);
userBadge.setAwardedAt(LocalDateTime.now());
userBadgeRepository.save(userBadge);
user.getBadges().add(userBadge);
// TODO: Remove in production
System.out.println("Badge " + badge.getName() + " vergeben an " + user.getPrivateName() +
". Mit Condition: " + badge.getCriteria().toString());
}
}
}
public BadgeDTO modifyBadge(BadgeDTO badgeDTO) {
Badge badge = badgeRepository.findById(badgeDTO.getId())
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Badge nicht gefunden"));
BadgeMapper.updateEntityFromDTO(badge, badgeDTO);
Badge savedBadge = badgeRepository.save(badge);
return BadgeMapper.toDTO(savedBadge);
}
public void deleteBadge(Long id) {
Badge badge = badgeRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Badge nicht gefunden"));
badgeRepository.delete(badge);
}
public BadgeDTO getBadgeById(Long badgeId) {
Badge badge = badgeRepository.findById(badgeId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Badge nicht gefunden"));
return BadgeMapper.toDTO(badge);
}
public List<BadgeDTO> getAllBadges() {
List<Badge> badges = badgeRepository.findAll();
return badges.stream()
.map(BadgeMapper::toDTO)
.toList();
}
public List<UserBadgeDTO> getUserBadges(Long id) {
User sender = currentUser.get();
List<UserBadge> badges = new ArrayList<>();
if(Objects.equals(id, sender.getId())) {
badges = userBadgeRepository.findByUserId(sender.getId());
} else {
if(privacyService.checkVisibility(sender, id)) {
badges = userBadgeRepository.findByUserId(id);
}
}
return badges.stream()
.map(UserBadgeMapper::toDTO)
.toList();
}
}
@@ -0,0 +1,12 @@
package SuMoC.backend.gamification.badges;
import SuMoC.backend.gamification.badges.models.UserBadge;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserBadgeRepository extends JpaRepository<UserBadge, Long> {
List<UserBadge> findByUserId(Long userId);
}
@@ -0,0 +1,54 @@
package SuMoC.backend.gamification.badges.mapper;
import SuMoC.backend.gamification.badges.models.Badge;
import SuMoC.backend.gamification.badges.models.BadgeDTO;
import SuMoC.backend.gamification.badges.models.BadgeImageEntity;
import SuMoC.backend.images.ImageBase64Util;
import org.mapstruct.Mapper;
import java.util.Base64;
@Mapper
public interface BadgeMapper {
static BadgeDTO toDTO(Badge badge) {
BadgeDTO dto = new BadgeDTO();
dto.setId(badge.getId());
dto.setName(badge.getName());
dto.setDescription(badge.getDescription());
dto.setCategory(badge.getCategory());
dto.setCriteria(badge.getCriteria());
dto.setImageBase64(ImageBase64Util.encode(badge.getImage().getImageData()));
return dto;
}
static Badge toEntity(BadgeDTO dto) {
Badge badge = new Badge();
badge.setId(dto.getId());
badge.setName(dto.getName());
badge.setDescription(dto.getDescription());
badge.setCategory(dto.getCategory());
badge.setCriteria(dto.getCriteria());
badge.setImage(new BadgeImageEntity(badge, ImageBase64Util.decode(dto.getImageBase64())));
return badge;
}
static void updateEntityFromDTO(Badge badge, BadgeDTO dto) {
badge.setName(dto.getName());
badge.setDescription(dto.getDescription());
badge.setCategory(dto.getCategory());
badge.setCriteria(dto.getCriteria());
// Bild aktualisieren
if (dto.getImageBase64() != null && !dto.getImageBase64().isEmpty()) {
byte[] imageData = Base64.getDecoder().decode(dto.getImageBase64());
if (badge.getImage() == null) {
badge.setImage(new BadgeImageEntity(badge, imageData));
} else {
badge.getImage().setImageData(imageData);
}
}
}
}
@@ -0,0 +1,43 @@
package SuMoC.backend.gamification.badges.mapper;
import SuMoC.backend.gamification.badges.models.Badge;
import SuMoC.backend.gamification.badges.models.UserBadge;
import SuMoC.backend.gamification.badges.models.UserBadgeDTO;
import org.mapstruct.Mapper;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
@Mapper
public class UserBadgeMapper {
public static UserBadgeDTO toDTO(UserBadge userBadge) {
UserBadgeDTO dto = new UserBadgeDTO();
Badge badge = userBadge.getBadge();
dto.setBadgeId(badge.getId());
dto.setName(badge.getName());
dto.setDescription(badge.getDescription());
dto.setCategory(badge.getCategory());
dto.setCriteria(badge.getCriteria());
dto.setAwardedAt(userBadge.getAwardedAt());
if (badge.getImage() != null && badge.getImage().getImageData() != null) {
String base64Image = Base64.getEncoder().encodeToString(badge.getImage().getImageData());
dto.setImageBase64(base64Image);
}
return dto;
}
public static List<UserBadgeDTO> toDTO(List<UserBadge> userBadges) {
List<UserBadgeDTO> dtos = new ArrayList<>();
for(UserBadge badge : userBadges ) {
dtos.add(UserBadgeMapper.toDTO(badge));
}
return dtos;
}
}
@@ -0,0 +1,77 @@
package SuMoC.backend.gamification.badges.models;
import SuMoC.backend.images.ImageEntity;
import jakarta.persistence.*;
import java.util.HashMap;
import java.util.Map;
@Entity
public class Badge {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
private BadgeCategory category;
@OneToOne(mappedBy = "badge", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private BadgeImageEntity image;
@ElementCollection
@CollectionTable(name = "badge_criteria", joinColumns = @JoinColumn(name = "badge_id"))
@MapKeyColumn(name = "criteria_name")
@Column(name = "criteria_value")
private Map<String, Integer> criteria = new HashMap<>();
// Constructors
public Badge(String name, String description, BadgeCategory category) {
this.name = name;
this.description = description;
this.category = category;
this.image = new BadgeImageEntity(this, null);
}
public Badge(String name, String description, BadgeCategory category, Map<String, Integer> criteria) {
this.name = name;
this.description = description;
this.category = category;
this.criteria = criteria;
}
public Badge(String name, String description, BadgeCategory category, Map<String, Integer> criteria, BadgeImageEntity image) {
this.name = name;
this.description = description;
this.category = category;
this.criteria = criteria;
this.image = image;
}
public Badge() {}
// Getter & Setter
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public BadgeCategory getCategory() { return category; }
public void setCategory(BadgeCategory category) { this.category = category; }
public BadgeImageEntity getImage() { return image; }
public void setImage(BadgeImageEntity image) {
this.image = image;
if (image != null) {
image.setBadge(this);
}
}
public Map<String, Integer> getCriteria() { return criteria; }
public void setCriteria(Map<String, Integer> criteria) { this.criteria = criteria; }
}
@@ -0,0 +1,23 @@
package SuMoC.backend.gamification.badges.models;
public enum BadgeCategory {
XP,
MOBILITY_SCORE,
CO2,
IDLE,
WALKING,
BICYCLE,
ESCOOTER,
BUS,
TRAM,
TRAIN,
CAR,
OPNV,
MONTHLY, // Get 10000 XP in January; Travel over 100 KM by train in May
HIDDEN
}
@@ -0,0 +1,79 @@
package SuMoC.backend.gamification.badges.models;
import java.util.Map;
public class BadgeDTO {
private Long id;
private String name;
private String description;
private BadgeCategory category;
private Map<String, Integer> criteria;
private String imageBase64;
// Constructors
public BadgeDTO() {}
public BadgeDTO(String name, String description, BadgeCategory category) {
this.name = name;
this.description = description;
this.category = category;
}
public BadgeDTO(Long id, String name, String description, BadgeCategory category) {
this.id = id;
this.name = name;
this.description = description;
this.category = category;
}
public BadgeDTO(String name, String description, BadgeCategory category, Map<String, Integer> criteria) {
this.name = name;
this.description = description;
this.category = category;
this.criteria = criteria;
}
public BadgeDTO(Long id, String name, String description, BadgeCategory category, Map<String, Integer> criteria) {
this.id = id;
this.name = name;
this.description = description;
this.category = category;
this.criteria = criteria;
}
public BadgeDTO(String name, String description, BadgeCategory category, Map<String, Integer> criteria, String imageBase64) {
this.name = name;
this.description = description;
this.category = category;
this.criteria = criteria;
this.imageBase64 = imageBase64;
}
public BadgeDTO(Long id, String name, String description, BadgeCategory category, Map<String, Integer> criteria, String imageBase64) {
this.id = id;
this.name = name;
this.description = description;
this.category = category;
this.criteria = criteria;
this.imageBase64 = imageBase64;
}
// Getter & Setter
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public BadgeCategory getCategory() { return category; }
public void setCategory(BadgeCategory category) { this.category = category; }
public Map<String, Integer> getCriteria() { return criteria; }
public void setCriteria(Map<String, Integer> criteria) { this.criteria = criteria; }
public String getImageBase64() { return imageBase64; }
public void setImageBase64(String imageBase64) { this.imageBase64 = imageBase64; }
}
@@ -0,0 +1,33 @@
package SuMoC.backend.gamification.badges.models;
import SuMoC.backend.images.ImageEntity;
import jakarta.persistence.DiscriminatorValue;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToOne;
@Entity
@DiscriminatorValue("BADGE")
public class BadgeImageEntity extends ImageEntity {
@OneToOne
@JoinColumn(name = "badge_id")
private Badge badge;
public BadgeImageEntity() {
super();
}
public BadgeImageEntity(Badge badge, byte[] imageData) {
super(imageData);
this.badge = badge;
}
public Badge getBadge() {
return badge;
}
public void setBadge(Badge badge) {
this.badge = badge;
}
}
@@ -0,0 +1,39 @@
package SuMoC.backend.gamification.badges.models;
import SuMoC.backend.user.models.User;
import jakarta.persistence.*;
import java.time.LocalDateTime;
@Entity
public class UserBadge {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// TODO: Discuss if this Duplex Joint really makes sense
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
private User user;
@ManyToOne
@JoinColumn(name = "badge_id", nullable = false)
private Badge badge;
private LocalDateTime awardedAt;
// Getter & Setter
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
public Badge getBadge() { return badge; }
public void setBadge(Badge badge) { this.badge = badge; }
public LocalDateTime getAwardedAt() { return awardedAt; }
public void setAwardedAt(LocalDateTime awardedAt) { this.awardedAt = awardedAt; }
}
@@ -0,0 +1,70 @@
package SuMoC.backend.gamification.badges.models;
import java.time.LocalDateTime;
import java.util.Map;
public class UserBadgeDTO {
private Long badgeId;
private String name;
private String description;
private BadgeCategory category;
private Map<String, Integer> criteria;
private LocalDateTime awardedAt;
private String imageBase64;
// Getter & Setter
public Long getBadgeId() {
return badgeId;
}
public void setBadgeId(Long badgeId) {
this.badgeId = badgeId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BadgeCategory getCategory() {
return this.category;
}
public void setCategory(BadgeCategory category) {
this.category = category;
}
public Map<String, Integer> getCriteria() {
return criteria;
}
public void setCriteria(Map<String, Integer> criteria) {
this.criteria = criteria;
}
public LocalDateTime getAwardedAt() {
return awardedAt;
}
public void setAwardedAt(LocalDateTime awardedAt) {
this.awardedAt = awardedAt;
}
public String getImageBase64() { return imageBase64; }
public void setImageBase64(String imageBase64) { this.imageBase64 = imageBase64; }
}
@@ -0,0 +1,150 @@
package SuMoC.backend.gamification.challenges;
import SuMoC.backend.gamification.challenges.Models.ChallengeDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Controller
@RequestMapping("/challenges")
class ChallengeController {
private ChallengeService challengeService;
@Autowired
public ChallengeController(ChallengeService challengeService) {
this.challengeService = challengeService;
}
// Admin Endpoints
@Operation(summary = "Create a new challenge")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Challenge created successfully",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = ChallengeDTO.class))),
@ApiResponse(responseCode = "400", description = "Invalid input data"),
})
@PostMapping("/createChallenge")
public ResponseEntity<ChallengeDTO> createChallenge(@RequestBody @Valid ChallengeDTO challengeDTO) {
ChallengeDTO createdChallenge = challengeService.createChallenge(challengeDTO);
return ResponseEntity.status(HttpStatus.CREATED).body(createdChallenge);
}
@Operation(summary = "Delete a challenge by ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Challenge deleted successfully"),
@ApiResponse(responseCode = "404", description = "Challenge not found")
})
@DeleteMapping("/deleteChallenge/{challengeId}")
public ResponseEntity<Void> deleteChallengeById(@PathVariable Long challengeId) {
challengeService.deleteChallenge(challengeId);
return ResponseEntity.ok().build();
}
@Operation(summary = "Modify a challenge by ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Challenge modified successfully",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = ChallengeDTO.class))),
@ApiResponse(responseCode = "404", description = "Challenge not found"),
@ApiResponse(responseCode = "400", description = "Invalid input data")
})
@PutMapping("/modifyChallenge")
public ResponseEntity<ChallengeDTO> modifyChallengeById(
@RequestBody @Valid ChallengeDTO challengeDTO) {
ChallengeDTO modifiedChallenge = challengeService.modifyChallenge(challengeDTO);
return ResponseEntity.status(HttpStatus.OK).body(modifiedChallenge);
}
@Operation(summary = "Get a challenge by ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Challenge retrieved successfully",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = ChallengeDTO.class))),
@ApiResponse(responseCode = "304", description = "Not modified since last request"),
@ApiResponse(responseCode = "404", description = "Challenge not found")
})
@GetMapping("/getChallenge/{challengeId}")
public ResponseEntity<ChallengeDTO> getChallengeById(@PathVariable Long challengeId) {
ChallengeDTO challengeDTO = challengeService.getChallengeById(challengeId);
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(356, TimeUnit.DAYS))
.body(challengeDTO);
}
@Operation(summary = "Get all challenges")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Challenges retrieved successfully",
content = @Content(mediaType = "application/json",
array = @ArraySchema(schema = @Schema(implementation = ChallengeDTO.class))
)),
@ApiResponse(responseCode = "304", description = "Not modified since last request"),
@ApiResponse(responseCode = "404", description = "No challenges found")
})
@GetMapping("/getAllChallenges")
public ResponseEntity<List<ChallengeDTO>> getAllChallenges(){
List<ChallengeDTO> challenges = challengeService.getAllChallenges();
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(365, TimeUnit.DAYS))
.body(challenges);
}
@Operation(summary = "Activate a challenge by ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Challenge activated successfully"),
@ApiResponse(responseCode = "404", description = "Challenge not found")
})
@PutMapping("/activateChallenge/{challengeId}")
public ResponseEntity<Void> activateChallengeById(@PathVariable Long challengeId) {
challengeService.activateChallenge(challengeId);
return ResponseEntity.ok().build();
}
@Operation(summary = "Deactivate a challenge by ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Challenge deactivated successfully"),
@ApiResponse(responseCode = "404", description = "Challenge not found")
})
@PutMapping("/deactivateChallenge/{challengeId}")
public ResponseEntity<Void> deactivateChallengeById(@PathVariable Long challengeId) {
challengeService.deactivateChallenge(challengeId);
return ResponseEntity.ok().build();
}
// User Endpoints
@Operation(summary = "Get all available challenges")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Available challenges retrieved successfully",
content = @Content(mediaType = "application/json",
array = @ArraySchema(schema = @Schema(implementation = ChallengeDTO.class))
)),
@ApiResponse(responseCode = "304", description = "Not modified since last request"),
@ApiResponse(responseCode = "404", description = "No available challenges found")
})
@GetMapping("/getAvailableChallenges")
public ResponseEntity<List<ChallengeDTO>> getAvailableChallenges() {
List<ChallengeDTO> challenges = challengeService.getAvailableChallenges();
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(7, TimeUnit.DAYS))
.body(challenges);
}
}
@@ -0,0 +1,34 @@
package SuMoC.backend.gamification.challenges;
import SuMoC.backend.gamification.challenges.Models.Challenge;
import SuMoC.backend.images.ImageEntity;
import jakarta.persistence.DiscriminatorValue;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToOne;
@Entity
@DiscriminatorValue("CHALLENGE")
public class ChallengeImageEntity extends ImageEntity {
@OneToOne
@JoinColumn(name = "challenge_id")
private Challenge challenge;
public ChallengeImageEntity() {
super();
}
public ChallengeImageEntity(Challenge challenge, byte[] imageData) {
super(imageData);
}
public Challenge getChallenge() {
return challenge;
}
public void setChallenge(Challenge challenge) {
this.challenge = challenge;
}
}
@@ -0,0 +1,62 @@
package SuMoC.backend.gamification.challenges;
import SuMoC.backend.gamification.challenges.Models.Challenge;
import SuMoC.backend.gamification.challenges.Models.ChallengeDTO;
import SuMoC.backend.images.ImageBase64Util;
import org.mapstruct.Mapper;
import java.util.Optional;
@Mapper
public interface ChallengeMapper {
static ChallengeDTO toDTO(Challenge challenge) {
ChallengeDTO dto = new ChallengeDTO();
dto.setId(challenge.getId());
dto.setName(challenge.getName());
dto.setDescription(challenge.getDescription());
dto.setCriteria(challenge.getCriteria());
dto.setReward(challenge.getReward());
dto.setBase64image(
Optional.ofNullable(challenge.getImage())
.map(ChallengeImageEntity::getImageData)
.map(ImageBase64Util::encode)
.orElse(null)
);
return dto;
}
static Challenge toEntity(ChallengeDTO dto) {
Challenge challenge = new Challenge();
challenge.setId(dto.getId());
challenge.setName(dto.getName());
challenge.setDescription(dto.getDescription());
challenge.setCriteria(dto.getCriteria());
challenge.setReward(dto.getReward());
if (dto.getBase64image() != null && !dto.getBase64image().isBlank()) {
byte[] bytes = ImageBase64Util.decode(dto.getBase64image());
ChallengeImageEntity img = new ChallengeImageEntity();
img.setImageData(bytes);
challenge.setImage(img);
}
return challenge;
}
static void updateEntityFromDTO(Challenge challenge, ChallengeDTO dto) {
challenge.setName(dto.getName());
challenge.setDescription(dto.getDescription());
challenge.setCriteria(dto.getCriteria());
challenge.setReward(dto.getReward());
if (dto.getBase64image() != null && !dto.getBase64image().isEmpty()) {
byte[] imageData = ImageBase64Util.decode(dto.getBase64image());
if (challenge.getImage() == null) {
challenge.setImage(new ChallengeImageEntity(challenge, imageData));
} else {
challenge.getImage().setImageData(imageData);
}
}
}
}
@@ -0,0 +1,23 @@
package SuMoC.backend.gamification.challenges;
import SuMoC.backend.gamification.challenges.Models.Challenge;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface ChallengeRepository extends JpaRepository<Challenge, Long> {
List<Challenge> findAllByActiveIs(Boolean active);
@Query("""
SELECT DISTINCT c FROM Challenge c
JOIN c.criteria crit
WHERE KEY(crit) IS NOT NULL
AND VALUE(crit) IS NOT NULL
""")
List<Challenge> findAllWithValidCriteria();
Optional<Challenge> findByName(String name);
}
@@ -0,0 +1,144 @@
package SuMoC.backend.gamification.challenges;
import SuMoC.backend.gamification.Timeframe;
import SuMoC.backend.gamification.challenges.Models.Challenge;
import SuMoC.backend.gamification.challenges.Models.ChallengeDTO;
import SuMoC.backend.user.models.User;
import SuMoC.backend.user.repository.UserRepository;
import SuMoC.backend.user.service.CurrentUserService;
import jakarta.transaction.Transactional;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.util.Collections;
import java.util.List;
import static java.lang.Math.min;
@Service
@Transactional
public class ChallengeService {
private final CurrentUserService currentUser;
private final ChallengeRepository challengeRepository;
private final UserRepository userRepository;
public ChallengeService(CurrentUserService currentUser, ChallengeRepository challengeRepository, UserRepository userRepository) {
this.currentUser = currentUser;
this.challengeRepository = challengeRepository;
this.userRepository = userRepository;
}
// Management of Challenges
public ChallengeDTO createChallenge(ChallengeDTO challengeDTO) {
Challenge challenge = ChallengeMapper.toEntity(challengeDTO);
Challenge savedChallenge = challengeRepository.save(challenge);
return ChallengeMapper.toDTO(savedChallenge);
}
public ChallengeDTO getChallengeById(Long id) {
Challenge challenge = challengeRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Challenge not found"));
return ChallengeMapper.toDTO(challenge);
}
public List<ChallengeDTO> getAllChallenges() {
List<Challenge> challenges = challengeRepository.findAll();
return challenges.stream()
.map(ChallengeMapper::toDTO)
.toList();
}
public ChallengeDTO modifyChallenge(ChallengeDTO challengeDTO) {
Challenge existingChallenge = challengeRepository.findById(challengeDTO.getId())
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Challenge not found"));
ChallengeMapper.updateEntityFromDTO(existingChallenge, challengeDTO);
Challenge updatedChallenge = challengeRepository.save(existingChallenge);
return ChallengeMapper.toDTO(updatedChallenge);
}
public void deleteChallenge(Long id) {
Challenge challenge = challengeRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Challenge not found"));
challengeRepository.delete(challenge);
}
public void deactivateChallenge(Long id) {
Challenge challenge = challengeRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Challenge not found"));
challenge.setActive(false);
challengeRepository.save(challenge);
}
public void activateChallenge(Long id) {
Challenge challenge = challengeRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Challenge not found"));
challenge.setActive(true);
challengeRepository.save(challenge);
}
// User Requests
public List<ChallengeDTO> getAvailableChallenges() {
List<Challenge> challenges = challengeRepository.findAllByActiveIs(true);
return challenges.stream()
.map(ChallengeMapper::toDTO)
.toList();
}
public void checkAndAwardChallenges(String field, Long value) {
User user = currentUser.get();
Long currentStat = user.getStats().getStatValue(Timeframe.WEEKLY, field);
Long newStat = currentStat + value;
List<Challenge> activeChallenges = challengeRepository.findAllByActiveIs(true);
for (Challenge challenge : activeChallenges) {
Integer target = challenge.getCriteria().get(field);
if (target != null && currentStat < target && newStat >= target) {
user.getStats().addToAllStats("XP", challenge.getReward());
userRepository.save(user);
}
}
}
// Additional Methods
@Transactional
public void setActiveById(Long challengeId, Boolean active) {
Challenge challenge = challengeRepository.findById(challengeId)
.orElseThrow();
challenge.setActive(active);
}
@Transactional
@Scheduled(cron = "0 0 0 ? * MON")
public void weeklyChallengeScheduler() {
List<Challenge> activeChallenges = challengeRepository.findAllByActiveIs(true);
activeChallenges.forEach(challenge -> {
setActiveById(challenge.getId(), false);
});
List<Challenge> allChallenges = challengeRepository.findAllWithValidCriteria();
int limit = min(allChallenges.size(), 3);
if (limit == 0) {
return;
}
Collections.shuffle(allChallenges);
allChallenges.stream()
.limit(limit)
.forEach(challenge -> setActiveById(challenge.getId(), true));
}
}
@@ -0,0 +1,116 @@
package SuMoC.backend.gamification.challenges.Models;
import SuMoC.backend.gamification.challenges.ChallengeImageEntity;
import jakarta.persistence.*;
import java.util.HashMap;
import java.util.Map;
@Entity
public class Challenge {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
@OneToOne(mappedBy = "challenge", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private ChallengeImageEntity image;
@ElementCollection
@CollectionTable(name = "challenge_criteria", joinColumns = @JoinColumn(name = "challenge_id"))
@MapKeyColumn(name = "criteria_name")
@Column(name = "criteria_value")
private Map<String, Integer> criteria = new HashMap<>();
private Integer reward;
private Boolean active;
// Constructors
public Challenge(String name, String description) {
this(name, description, null, 0);
}
public Challenge(String name, String description, Map<String, Integer> criteria, Integer reward) {
this(name, description, criteria, reward, new ChallengeImageEntity(null, null));
}
public Challenge(String name, String description, Map<String, Integer> criteria, Integer reward, ChallengeImageEntity image) {
this.name = name;
this.description = description;
this.criteria = criteria;
this.reward = reward;
this.image = image;
this.active = false;
}
public Challenge() {
}
// Getter & Setter
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ChallengeImageEntity getImage() {
return image;
}
public void setImage(ChallengeImageEntity image) {
this.image = image;
if (image != null) {
image.setChallenge(this);
}
}
public Map<String, Integer> getCriteria() {
return criteria;
}
public void setCriteria(Map<String, Integer> criteria) {
this.criteria = criteria;
}
public Integer getReward() {
return reward;
}
public void setReward(Integer reward) {
this.reward = reward;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
}
@@ -0,0 +1,85 @@
package SuMoC.backend.gamification.challenges.Models;
import java.util.Map;
public class ChallengeDTO {
private Long id;
private String name;
private String description;
private String base64image;
private Map<String, Integer> criteria;
private Integer reward;
// Constructors
public ChallengeDTO() {}
public ChallengeDTO(Long id, String name, String description, String base64image, Map<String, Integer> criteria, Integer reward) {
this.id = id;
this.name = name;
this.description = description;
this.base64image = base64image;
this.criteria = criteria;
this.reward = reward;
}
public ChallengeDTO(Long id, String name, String description, Map<String, Integer> criteria, Integer reward) {
this(id, name, description, null, criteria, reward);
}
public ChallengeDTO(Long id , String name, String description) {
this(id, name, description, null, 0);
}
// Getter & Setter
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getBase64image() {
return base64image;
}
public void setBase64image(String base64image) {
this.base64image = base64image;
}
public Map<String, Integer> getCriteria() {
return criteria;
}
public void setCriteria(Map<String, Integer> criteria) {
this.criteria = criteria;
}
public Integer getReward() {
return reward;
}
public void setReward(Integer reward) {
this.reward = reward;
}
}
@@ -0,0 +1,62 @@
package SuMoC.backend.gamification.scoretable;
import SuMoC.backend.gamification.scoretable.models.Leaderboard;
import SuMoC.backend.gamification.Timeframe;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/leaderboard")
public class LeaderboardController {
private LeaderboardService leaderboardService;
@Autowired
public LeaderboardController(LeaderboardService leaderboardService) {
this.leaderboardService = leaderboardService;
}
@Operation(summary = "Get the global score table")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successfully retrieved global score table",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = Leaderboard.class))),
@ApiResponse(responseCode = "304", description = "Not modified"),
@ApiResponse(responseCode = "400", description = "Bad request")
})
@GetMapping("/getLeaderboard")
public ResponseEntity<Leaderboard> getLeaderboard(@RequestParam Timeframe timeframe,
@RequestParam String field) {
Leaderboard leaderboard = this.leaderboardService.getLeaderboard( timeframe, field);
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(24, TimeUnit.HOURS))
.body(leaderboard);
}
@Operation(summary = "Get the friend score table")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successfully retrieved friend score table",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = Leaderboard.class))),
@ApiResponse(responseCode = "304", description = "Not modified"),
@ApiResponse(responseCode = "400", description = "Bad request")
})
@GetMapping("/getFriendLeaderboard")
public ResponseEntity<Leaderboard> getFriendLeaderboard(@RequestParam Timeframe timeframe,
@RequestParam String field) {
Leaderboard leaderboard = this.leaderboardService.getFriendLeaderboard(timeframe, field);
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(24, TimeUnit.HOURS))
.body(leaderboard);
}
}
@@ -0,0 +1,203 @@
package SuMoC.backend.gamification.scoretable;
import SuMoC.backend.gamification.scoretable.models.Leaderboard;
import SuMoC.backend.gamification.Timeframe;
import SuMoC.backend.gamification.scoretable.models.LeaderboardEntry;
import SuMoC.backend.images.ImageBase64Util;
import SuMoC.backend.user.models.User;
import SuMoC.backend.user.service.CurrentUserService;
import SuMoC.backend.user.service.FriendshipService;
import SuMoC.backend.user.service.PrivacyService;
import SuMoC.backend.user.stats.*;
import jakarta.transaction.Transactional;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
@Service
@Transactional
public class LeaderboardService {
private final FriendshipService friendshipService;
private final StatsListRepository statsListRepository;
private final CurrentUserService currentUser;
private final PrivacyService privacyService;
public LeaderboardService(
FriendshipService friendshipService,
StatsListRepository statsListRepository,
CurrentUserService currentUser,
PrivacyService privacyService) {
this.friendshipService = friendshipService;
this.statsListRepository = statsListRepository;
this.currentUser = currentUser;
this.privacyService = privacyService;
}
/**
* Method Overload to get the score table with a default limit of 30.
* @param timeframe
* @param field
* @return
*/
public Leaderboard getLeaderboard(Timeframe timeframe, String field) {
return getLeaderboard( timeframe, field, 30);
}
/**
* Get the global score table for a given user, timeframe, score type, and limit.
* @param timeframe
* @param field
* @param limit
* @return
*/
public Leaderboard getLeaderboard(Timeframe timeframe, String field, int limit) {
User user = currentUser.get();
List<StatsList> topStats = getTopStats(timeframe, field, limit);
Leaderboard leaderboard = new Leaderboard();
leaderboard.setEntries(new ArrayList<>());
List<User> friendships = friendshipService.getAcceptedFriends(user);
for (StatsList statsList : topStats) {
User topUser = statsList.getUser();
boolean ps = privacyService.checkVisibility(user, topUser.getId());
LeaderboardEntry entry = new LeaderboardEntry(
topUser.getId(),
ps ? topUser.getPrivateName() : topUser.getPublicName(),
friendships
.stream()
.anyMatch(o -> o.getId().equals(topUser.getId())),
statsList.getStatValue(timeframe, field),
ps ? ImageBase64Util.encode(topUser.getProfileImage().getImageData()) : null
);
leaderboard.getEntries().add(entry);
}
if (leaderboard.getEntries().stream().noneMatch(e -> e.getUserId().equals(user.getId()))) {
LeaderboardEntry userEntry = new LeaderboardEntry(
user.getId(),
user.getPrivateName(),
false,
user.getStats().getStatValue(timeframe, field),
ImageBase64Util.encode(user.getProfileImage().getImageData())
);
leaderboard.getEntries().add(userEntry);
}
leaderboard.getEntries().sort(
Comparator.comparingLong(LeaderboardEntry::getScore).reversed()
);
return leaderboard;
}
/**
* Method Overload to get the friend score table with a default limit of 30.
* @param timeframe
* @param field
* @return
*/
public Leaderboard getFriendLeaderboard(Timeframe timeframe, String field) {
return getFriendLeaderboard(timeframe, field, 30);
}
/**
* Get the friend score table for a given user, timeframe, score type, and limit.
* @param timeframe
* @param field
* @param limit
* @return
*/
public Leaderboard getFriendLeaderboard(Timeframe timeframe, String field, int limit) {
User user = currentUser.get();
List<User> friends = friendshipService.getAcceptedFriends(user);
Leaderboard leaderboard = new Leaderboard();
leaderboard.setEntries(new ArrayList<>());
for (User friend : friends) {
StatsList statsList = friend.getStats();
boolean ps = privacyService.checkVisibility(user, friend.getId());
Long statValue = statsList.getStatValue(timeframe, field);
LeaderboardEntry entry = new LeaderboardEntry(
friend.getId(),
ps ? friend.getPrivateName() : friend.getPublicName(),
true,
statValue,
ps ? ImageBase64Util.encode(friend.getProfileImage().getImageData()): null
);
leaderboard.getEntries().add(entry);
}
if (leaderboard.getEntries().stream().noneMatch(e -> e.getUserId().equals(user.getId()))) {
leaderboard.getEntries().add(new LeaderboardEntry(
user.getId(),
user.getPrivateName(),
false,
user.getStats().getStatValue(timeframe, field),
ImageBase64Util.encode(user.getProfileImage().getImageData())
));
}
leaderboard.getEntries().sort(
Comparator.comparingLong(LeaderboardEntry::getScore).reversed()
);
return leaderboard;
}
/**
* Get the top stats for a given timeframe and stat field.
* @param timeframe
* @param statField
* @param limit
* @return
*/
public List<StatsList> getTopStats(
Timeframe timeframe,
String statField,
int limit
) {
Pageable pageable = PageRequest.of(0, limit);
return statsListRepository
.findAll(
StatsListSpecifications.orderByStat(timeframe, statField),
pageable
)
.getContent();
}
/**
* Get the rank of a specific value for a given timeframe and stat field.
* @param timeframe
* @param statField
* @param value
* @return
*/
public long getRank(
Timeframe timeframe,
String statField,
long value
) {
return statsListRepository.count(
StatsListSpecifications
.higherThan(timeframe, statField, value)
) + 1;
}
}
@@ -0,0 +1,37 @@
package SuMoC.backend.gamification.scoretable.models;
import SuMoC.backend.gamification.Timeframe;
import java.util.List;
public class Leaderboard {
private Timeframe timeframe;
private LeaderboardType leaderboardType;
private List<LeaderboardEntry> entries;
// Constructor
public Leaderboard(Timeframe timeframe, LeaderboardType leaderboardType, List<LeaderboardEntry> entries) {
this.timeframe = timeframe;
this.leaderboardType = leaderboardType;
this.entries = entries;
}
public Leaderboard() {}
// Getter & Setter
public Timeframe getTimeframe() { return timeframe; }
public void setTimeframe(Timeframe timeframe) { this.timeframe = timeframe; }
public LeaderboardType getScoreType() { return leaderboardType; }
public void setScoreType(LeaderboardType leaderboardType) { this.leaderboardType = leaderboardType; }
public List<LeaderboardEntry> getEntries() { return entries; }
public void setEntries(List<LeaderboardEntry> entries) { this.entries = entries; }
}
@@ -0,0 +1,41 @@
package SuMoC.backend.gamification.scoretable.models;
public class LeaderboardEntry {
private Long userId;
private String username;
private Boolean isFriend;
private Long score;
private String base64ProfilePicture;
public LeaderboardEntry(Long userId, String username, Boolean isFriend, Long score, String base64ProfilePicture) {
this.userId = userId;
this.username = username;
this.isFriend = isFriend;
this.score = score;
this.base64ProfilePicture = base64ProfilePicture;
}
public LeaderboardEntry() {}
// Getter & Setter
public Long getUserId() { return userId; }
public void setUserId(Long userId) { this.userId = userId; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public Boolean getIsFriend() { return isFriend; }
public void setIsFriend(Boolean isFriend) { this.isFriend = isFriend; }
public Long getScore() { return score; }
public void setScore(Long score) { this.score = score; }
public String getBase64ProfilePicture() {
return base64ProfilePicture;
}
public void setBase64ProfilePicture(String base64ProfilePicture) {
this.base64ProfilePicture = base64ProfilePicture;
}
}
@@ -0,0 +1,7 @@
package SuMoC.backend.gamification.scoretable.models;
public enum LeaderboardType {
XP,
CO2,
KM
}
@@ -0,0 +1,37 @@
package SuMoC.backend.geocoding;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Setter
@Getter
@NoArgsConstructor
public class AddressDTO {
// Getters and setters
private String houseNumber;
private String road;
private String suburb;
private String cityDistrict;
private String city;
private String state;
private String iso3166_2_lvl4;
private String postcode;
private String country;
private String countryCode;
// Constructor with fields
public AddressDTO(String houseNumber, String road, String suburb, String cityDistrict, String city, String state, String iso3166_2_lvl4, String postcode, String country, String countryCode) {
this.houseNumber = houseNumber;
this.road = road;
this.suburb = suburb;
this.cityDistrict = cityDistrict;
this.city = city;
this.state = state;
this.iso3166_2_lvl4 = iso3166_2_lvl4;
this.postcode = postcode;
this.country = country;
this.countryCode = countryCode;
}
}
@@ -0,0 +1,83 @@
package SuMoC.backend.geocoding;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import java.util.HashMap;
import java.util.Map;
public class CartaLocationClient implements GeocodingClient {
private static final Logger logger = LoggerFactory.getLogger(CartaLocationClient.class);
private final WebClient cartaLocationClient;
public CartaLocationClient(WebClient cartaLocationClient) {
this.cartaLocationClient = cartaLocationClient;
}
@Override
public Mono<GeocodingResponse> reverse(double lat, double lon) {
String query = lat + "," + lon;
logger.debug("Calling Carta location API with query: {}, type: BUILDING, limit: 3", query);
return cartaLocationClient.get()
.uri(uriBuilder -> {
var uri = uriBuilder.path("/location/search")
.queryParam("q", query)
.queryParam("type", "BUILDING")
.queryParam("limit", 3)
.build();
logger.debug("Full Carta location API URL: {}", uri);
return uri;
})
.retrieve()
.bodyToMono(CartaLocationResponse[].class)
.doOnNext(responses -> logger.debug("Received {} results from Carta location API",
responses != null ? responses.length : 0))
.map(responses -> {
if (responses == null || responses.length == 0) {
logger.error("Carta location API returned empty response for coordinates: lat={}, lon={}", lat, lon);
return new GeocodingResponse(null);
}
logger.debug("Using first result: {}", responses[0]);
return mapToGeocodingResponse(responses[0]);
})
.onErrorResume(error -> {
logger.error("Error calling Carta location API for coordinates: lat={}, lon={}", lat, lon, error);
return Mono.just(new GeocodingResponse(null));
});
}
private GeocodingResponse mapToGeocodingResponse(CartaLocationResponse response) {
Map<String, String> addressMap = new HashMap<>();
// Map Carta fields to Nominatim-style address format
if (response.building() != null) {
addressMap.put("house_number", response.building());
}
if (response.street() != null) {
addressMap.put("road", response.street());
}
if (response.suburb() != null) {
addressMap.put("suburb", response.suburb());
}
if (response.city() != null) {
addressMap.put("city", response.city());
}
if (response.state() != null) {
addressMap.put("state", response.state());
}
if (response.postcode() != null) {
addressMap.put("postcode", response.postcode());
}
if (response.country() != null) {
addressMap.put("country", response.country());
}
return new GeocodingResponse(addressMap);
}
}
@@ -0,0 +1,22 @@
package SuMoC.backend.geocoding;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public record CartaLocationResponse(
Double longitude,
Double latitude,
String country,
String state,
String county,
String city,
String suburb,
String neighborhood,
String locality,
String street,
String building,
String postcode,
String name
) {
}
@@ -0,0 +1,38 @@
package SuMoC.backend.geocoding;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
@Service
public class GeoCodingService {
private final GeocodingClient geocodingClient;
public GeoCodingService(GeocodingClient geocodingClient) {
this.geocodingClient = geocodingClient;
}
public Mono<AddressDTO> getAddress(double lat, double lon) {
return geocodingClient.reverse(lat, lon)
.map(this::mapToAddressDTO);
}
private AddressDTO mapToAddressDTO(GeocodingResponse response) {
var addressMap = response.address();
if (addressMap == null) {
return new AddressDTO(null, null, null, null, null, null, null, null, null, null);
}
return new AddressDTO(
addressMap.get("house_number"),
addressMap.get("road"),
addressMap.get("suburb"),
addressMap.get("city_district"),
addressMap.get("city"),
addressMap.get("state"),
addressMap.get("ISO3166-2-lvl4"),
addressMap.get("postcode"),
addressMap.get("country"),
addressMap.get("country_code")
);
}
}
@@ -0,0 +1,7 @@
package SuMoC.backend.geocoding;
import reactor.core.publisher.Mono;
public interface GeocodingClient {
Mono<GeocodingResponse> reverse(double lat, double lon);
}
@@ -0,0 +1,41 @@
package SuMoC.backend.geocoding;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;
@Configuration
@EnableConfigurationProperties(GeocodingProperties.class)
public class GeocodingConfig {
@Bean
@ConditionalOnProperty(name = "geocoding.provider", havingValue = "docker", matchIfMissing = true)
public WebClient nominatimWebClient(GeocodingProperties properties) {
return WebClient.builder()
.baseUrl(properties.nominatim().baseUrl())
.build();
}
@Bean(name = "geocodingClient")
@ConditionalOnProperty(name = "geocoding.provider", havingValue = "docker", matchIfMissing = true)
public GeocodingClient nominatimClient(WebClient nominatimWebClient) {
return new NominatimClient(nominatimWebClient);
}
@Bean
@ConditionalOnProperty(name = "geocoding.provider", havingValue = "carta")
public WebClient cartaLocationWebClient(GeocodingProperties properties) {
return WebClient.builder()
.baseUrl(properties.carta().baseUrl())
.build();
}
@Bean(name = "geocodingClient")
@ConditionalOnProperty(name = "geocoding.provider", havingValue = "carta")
public GeocodingClient cartaLocationClient(WebClient cartaLocationWebClient) {
return new CartaLocationClient(cartaLocationWebClient);
}
}
@@ -0,0 +1,25 @@
package SuMoC.backend.geocoding;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping("/geocoding")
public class GeocodingController {
private final GeoCodingService geoCodingService;
public GeocodingController(GeoCodingService geoCodingService) {
this.geoCodingService = geoCodingService;
}
@GetMapping("/reverse")
@Operation(description = "Returns the address at the given lat / lon.")
public Mono<AddressDTO> reverse(@RequestParam double lat, @RequestParam double lon) {
return geoCodingService.getAddress(lat, lon);
}
}
@@ -0,0 +1,21 @@
package SuMoC.backend.geocoding;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "geocoding")
public record GeocodingProperties(
String provider,
NominatimConfig nominatim,
CartaConfig carta
) {
public record NominatimConfig(
String baseUrl
) {
}
public record CartaConfig(
String baseUrl
) {
}
}
@@ -0,0 +1,9 @@
package SuMoC.backend.geocoding;
import java.util.Map;
public record GeocodingResponse(
Map<String, String> address
) {
}
@@ -0,0 +1,27 @@
package SuMoC.backend.geocoding;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
public class NominatimClient implements GeocodingClient {
private final WebClient nominatimClient;
public NominatimClient(WebClient nominatimClient) {
this.nominatimClient = nominatimClient;
}
@Override
public Mono<GeocodingResponse> reverse(double lat, double lon) {
return nominatimClient.get()
.uri(uriBuilder -> uriBuilder.path("/reverse")
.queryParam("lat", lat)
.queryParam("lon", lon)
.queryParam("format", "jsonv2")
.build())
.retrieve()
.bodyToMono(ReverseResponse.class)
.map(response -> new GeocodingResponse(response.address()));
}
}
@@ -0,0 +1,18 @@
package SuMoC.backend.geocoding;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;
public record ReverseResponse(
@JsonProperty("place_id") long placeId,
String licence,
@JsonProperty("osm_type") String osmType,
@JsonProperty("osm_id") long osmId,
String lat,
String lon,
@JsonProperty("display_name") String displayName,
@JsonProperty("address") Map<String, String> address
) {
}
@@ -0,0 +1,31 @@
package SuMoC.backend.h3;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "h3")
@Getter
@Setter
public class H3Configuration {
/**
* H3 resolution for route pattern detection.
* Typically slightly lower resolution for broader matching.
*/
private int routePatternResolution = 10;
/**
* Number of hexagonal rings to include when matching route patterns.
* K-ring depth where k=1 includes immediate neighbors (6 hexagons),
* k=2 includes two rings (18 hexagons), etc.
* Higher values allow fuzzier location matching but may incorrectly
* group distinct locations.
* Consider resolution when setting.
* Default: 1 (immediate neighbors only)
*/
private int routePatternNeighborRings = 1;
}
@@ -0,0 +1,86 @@
package SuMoC.backend.h3;
import com.uber.h3core.H3Core;
import com.uber.h3core.util.LatLng;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.List;
/**
* Service for H3 spatial indexing operations.
* H3 is a hierarchical hexagonal geospatial indexing system.
*/
@Service
public class H3Service {
private final H3Core h3;
private final H3Configuration config;
public H3Service(H3Configuration config) {
this.config = config;
try {
this.h3 = H3Core.newInstance();
} catch (IOException e) {
throw new RuntimeException("Failed to initialize H3Core", e);
}
}
/**
* Convert latitude/longitude to H3 cell ID with specific resolution.
*
* @param latitude Latitude in degrees
* @param longitude Longitude in degrees
* @param resolution H3 resolution (0-15, higher = more precise)
* @return H3 cell ID as hex string
*/
public String latLngToCell(double latitude, double longitude, int resolution) {
return h3.latLngToCellAddress(latitude, longitude, resolution);
}
/**
* Convert latitude/longitude to H3 cell ID using route pattern resolution.
* This is typically used for detecting regular trip patterns.
*
* @param latitude Latitude in degrees
* @param longitude Longitude in degrees
* @return H3 cell ID as hex string
*/
public String latLngToCellForRoute(double latitude, double longitude) {
return latLngToCell(latitude, longitude, config.getRoutePatternResolution());
}
/**
* Convert H3 cell ID to center latitude/longitude.
*
* @param cellId H3 cell ID as hex string
* @return LatLng of cell center
*/
public LatLng cellToLatLng(String cellId) {
return h3.cellToLatLng(cellId);
}
/**
* Get all cells within k distance of the given cell (excluding the cell it self).
* K-ring distance means cells reachable in k steps on the hexagonal grid.
*
* @param cellId H3 cell ID as hex string
* @param k Distance (number of rings, 0 = only the cell itself)
* @return List of H3 cell IDs including the origin cell
*/
public List<String> getKRingNeighbors(String cellId, int k) {
return h3.gridRing(cellId, k);
}
/**
* Get K-ring neighbors using the configured route pattern resolution distance.
* Ring means the center cell is not included.
* Useful for finding nearby locations when matching trip patterns.
*
* @param cellId H3 cell ID as hex string
* @return List of H3 cell IDs within configured neighbor distance
*/
public List<String> getRoutePatternNeighbors(String cellId) {
return getKRingNeighbors(cellId, config.getRoutePatternNeighborRings());
}
}
@@ -0,0 +1,23 @@
package SuMoC.backend.images;
import java.util.Base64;
public final class ImageBase64Util {
private ImageBase64Util() {
}
public static String encode(byte[] imageData) {
if (imageData == null || imageData.length == 0) {
return null;
}
return Base64.getEncoder().encodeToString(imageData);
}
public static byte[] decode(String base64Image) {
if (base64Image == null || base64Image.isEmpty()) {
return null;
}
return Base64.getDecoder().decode(base64Image);
}
}
@@ -0,0 +1,41 @@
package SuMoC.backend.images;
import jakarta.persistence.*;
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "dtype")
public class ImageEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Lob
//@Column(columnDefinition = "BYTEA")
//@Column(columnDefinition = "BLOB")
private byte[] imageData;
public ImageEntity() {
}
public ImageEntity(byte[] imageData) {
this.imageData = imageData;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public byte[] getImageData() {
return imageData;
}
public void setImageData(byte[] imageData) {
this.imageData = imageData;
}
}
@@ -0,0 +1,8 @@
package SuMoC.backend.images;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ImageEntityRepository extends JpaRepository<ImageEntity, Long> {
}
@@ -0,0 +1,21 @@
package SuMoC.backend.images;
public class ImageRequestDTO {
private String base64ProfilePicture;
public ImageRequestDTO(String base64ProfilePicture) {
this.base64ProfilePicture = base64ProfilePicture;
}
public ImageRequestDTO() {}
public String getBase64ProfilePicture() {
return base64ProfilePicture;
}
public void setBase64ProfilePicture(String base64ProfilePicture) {
this.base64ProfilePicture = base64ProfilePicture;
}
}
@@ -0,0 +1,20 @@
package SuMoC.backend.logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@Controller
public class LogPageController {
@GetMapping("/logs")
public String logs(Model model) throws IOException {
String content = Files.readString(Path.of("logs/app.log"));
model.addAttribute("logs", content);
return "logs";
}
}
@@ -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,51 @@
package SuMoC.backend.notification;
import SuMoC.backend.notification.enums.NotificationProvider;
import SuMoC.backend.notification.services.NotificationTokenService;
import SuMoC.backend.user.models.User;
import SuMoC.backend.user.repository.UserRepository;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/notifications")
@RequiredArgsConstructor
public class NotificationController {
private final UserRepository userRepository;
private final NotificationTokenService notificationTokenService;
// TODO extend security context with user id to avoid unnecessary db query
private User getAuthenticatedUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return userRepository.findByEmail(authentication.getName()).orElseThrow(() -> new RuntimeException("User not found"));
}
@PutMapping("/register-device-token")
@Operation(summary = "Registers a device token for push notifications for the authenticated user.")
public ResponseEntity<Void> registerDeviceToken(@RequestBody RegisterDeviceTokenRequest request) {
User user = getAuthenticatedUser();
notificationTokenService.registerDeviceToken(user, request.provider(), request.token());
return ResponseEntity.ok().build();
}
@PutMapping("/unregister-device-token")
@Operation(description = "Unregisters the device token for push notifications for the authenticated user.")
public ResponseEntity<Void> unregisterDeviceToken() {
User user = getAuthenticatedUser();
notificationTokenService.unregisterDeviceToken(user);
return ResponseEntity.ok().build();
}
// Simple record for request body
public record RegisterDeviceTokenRequest(String token, NotificationProvider provider) {
}
}
@@ -0,0 +1,56 @@
# Notification System Overview
This document provides an overview of the notification system for client developers integrating with the backend. It
explains notification types, expected payloads, and device token registration.
## Notification Types
Notifications sent to clients are categorized by `NotificationType`:
- **TREND**: Informs users about changes in their mobility trends (e.g., reduced car usage). See
`TrendNotificationService`.
- **ADHOC_ALTERNATIVE**: Suggests a more sustainable alternative after a recent trip upload. See
`AdHocSuggestionService`.
- **REGULAR_TRIP_ALTERNATIVE**: Suggests an alternative for a detected regular trip (e.g., weekly commute). See
`RegularTripSuggestionService`.
- **FRIENDSHIP_REQUEST_RECEIVED**: Notifies about a new pending friendship request.
See `NotificationType.java` for the full enum.
## Notification Payloads
Each notification type includes a data payload. The main DTOs in the notification body are:
- **TREND**: Contains a list of `TrendDetectionDTO` objects, each describing a detected trend for the user. The
structure includes fields such as `userId`, `timespan`, `type`, `attribute`, `deltaType`, `changeValue`, and
`trendConnotation`. See `TrendDetectionDTO.java` for details.
- **ADHOC_ALTERNATIVE**: Contains a list of `RouteDTO` objects representing the best alternative(s) for a recent trip (
see `AdHocSuggestionService`).
- **REGULAR_TRIP_ALTERNATIVE**: Contains a list of 1 or 2 `RouteDTO` objects for the best alternative(s) to a detected
regular trip, depending on user preferences (e.g., if `preferPhysicalActivity` is set, two alternatives may be
included). See `RegularTripSuggestionService` and `RegularTripDetectionService` for details.
- **FRIENDSHIP_REQUEST_RECEIVED**: Contains a `friendshipDTO` where `friend` is the user who sent the request. See
`FriendshipDTO.java`.
## Device Token Registration
To receive push notifications, clients must register their device token. Token registration is handled in the
`NotificationController`. The backend stores or updates the token for the authenticated user.
### Unregistering Device Token
When a user logs out, the client should call the device token unregistration endpoint to remove the device token from
the backend. This ensures the user will no longer receive push notifications on that device after logout.
- **Endpoint:** `PUT /notifications/unregister-device-token`
---
## For Backend Developers
To queue notifications for users, use the `NotificationSchedulerService` as the main entry point. This service provides
methods to schedule notifications with the appropriate type and payload. See `NotificationSchedulerService.java` for
usage details.
---
For further details, refer to the respective service and DTO classes in the codebase.
@@ -0,0 +1,29 @@
package SuMoC.backend.notification.config;
import SuMoC.backend.notification.enums.NotificationType;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Data
@Component
@ConfigurationProperties(prefix = "sumoc.notification")
public class NotificationProperties {
/**
* Maximum number of failed send attempts before giving up on a notification.
*/
private int maxFailedSendAttempts = 3;
/**
* Maximum number of notifications to send to a user per hour per notification type.
*/
private Map<NotificationType, Integer> maxNotificationsPerHourPerType = new HashMap<>(Map.of(
NotificationType.TREND, 1,
NotificationType.ADHOC_ALTERNATIVE, 1,
NotificationType.REGULAR_TRIP_ALTERNATIVE, 1,
NotificationType.FRIENDSHIP_REQUEST_RECEIVED, 3
));
}
@@ -0,0 +1,5 @@
package SuMoC.backend.notification.enums;
public enum NotificationProvider {
FIREBASE,
}
@@ -0,0 +1,16 @@
package SuMoC.backend.notification.enums;
public enum NotificationStatus {
/**
* Has never been sent successfully. Will be retried.
*/
PENDING,
/**
* Has been sent successfully.
*/
SENT,
/**
* Has failed to send and will not be retried.
*/
FAILED
}
@@ -0,0 +1,24 @@
package SuMoC.backend.notification.enums;
/**
* Notification type that will be included in the data sent to the mobile devices.
*/
public enum NotificationType {
/**
* Informing about a change in mobility trends, e.g. driving less car.
*/
TREND,
/**
* An alternative suggestion following the upload of a recent trip.
*/
ADHOC_ALTERNATIVE,
/**
* An alternative suggestion that refers to a detected regular trip.
* E.g. user drives by car every monday at 8 am and there is a sustainable alternative.
*/
REGULAR_TRIP_ALTERNATIVE,
/**
* A notification informing the user about a new pending friendship request.
*/
FRIENDSHIP_REQUEST_RECEIVED,
}
@@ -0,0 +1,5 @@
package SuMoC.backend.notification.interfaces;
public interface Notifieable {
Long getUserId();
}
@@ -0,0 +1,9 @@
package SuMoC.backend.notification.interfaces;
import java.time.LocalTime;
public interface NotifieableWithTime {
Long getUserId();
LocalTime getEarliestTimeOfDayToSend();
}
@@ -0,0 +1,65 @@
package SuMoC.backend.notification.models;
import SuMoC.backend.notification.enums.NotificationStatus;
import SuMoC.backend.notification.enums.NotificationType;
import SuMoC.backend.user.models.User;
import jakarta.persistence.*;
import lombok.*;
import java.time.Instant;
import java.time.LocalTime;
@Entity
@Table(name = "notifications")
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Notification {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
private User user;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private NotificationType type;
@Column(columnDefinition = "TEXT")
private String data; // Store serialized DTO as JSON
/**
* Time of day from which on a notification might be sent.
* Useful since we might want to send messages about specific trips immediately but not inform about trend changes
* etc. in the middle of night when calculating jobs might run.
*/
@Column(nullable = false)
private LocalTime earliestTimeOfDayToSend;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private NotificationStatus status = NotificationStatus.PENDING;
/**
* Number of retry attempts made to send this notification.
*/
@Column(nullable = false)
private int failedSendAttempts = 0;
@Column
private String lastFailureReason;
@Column(nullable = false)
private Instant createdAt;
@Column(nullable = true)
private Instant sentAt = null;
public void incrementFailedSendAttempts() {
this.failedSendAttempts++;
}
}
@@ -0,0 +1,23 @@
package SuMoC.backend.notification.models;
import SuMoC.backend.notification.enums.NotificationProvider;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
@Entity
public class NotificationToken {
@Id
@Column(name = "user_id", nullable = false, unique = true)
private Long userId;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private NotificationProvider provider;
@Column(nullable = false, length = 512)
private String token;
}
@@ -0,0 +1,42 @@
package SuMoC.backend.notification.repositories;
import SuMoC.backend.notification.models.Notification;
import SuMoC.backend.user.models.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import java.time.Instant;
import java.time.LocalTime;
import java.util.List;
public interface NotificationRepository extends JpaRepository<Notification, Long> {
@Query("""
SELECT n
FROM Notification n
LEFT JOIN FETCH n.user u
LEFT JOIN FETCH u.notificationToken
WHERE n.status = 'PENDING'
AND n.earliestTimeOfDayToSend <= :currentTime
""")
List<Notification> findPendingNotificationsToSend(LocalTime currentTime);
@Query("""
SELECT n
FROM Notification n
WHERE n.user.id = :userId
AND n.status = 'SENT'
AND n.createdAt >= :since
""")
List<Notification> getSentToUserSince(Long userId, Instant since);
@Modifying
@Query("""
DELETE
FROM Notification n
WHERE n.createdAt < :cutOff
""")
void deleteNotificationsOlder(Instant cutOff);
void deleteAllByUser(User user);
}

Some files were not shown because too many files have changed in this diff Show More